You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 50 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
8 years ago
11 years ago
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
9 years ago
9 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
10 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "container/list"
  8. "crypto/md5"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. _ "image/jpeg" // Needed for jpeg support
  15. "image/png"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. "code.gitea.io/gitea/modules/avatar"
  22. "code.gitea.io/gitea/modules/base"
  23. "code.gitea.io/gitea/modules/generate"
  24. "code.gitea.io/gitea/modules/git"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/structs"
  28. api "code.gitea.io/gitea/modules/structs"
  29. "code.gitea.io/gitea/modules/util"
  30. "github.com/Unknwon/com"
  31. "github.com/go-xorm/xorm"
  32. "golang.org/x/crypto/argon2"
  33. "golang.org/x/crypto/bcrypt"
  34. "golang.org/x/crypto/pbkdf2"
  35. "golang.org/x/crypto/scrypt"
  36. "golang.org/x/crypto/ssh"
  37. "xorm.io/builder"
  38. "xorm.io/core"
  39. )
  40. // UserType defines the user type
  41. type UserType int
  42. const (
  43. // UserTypeIndividual defines an individual user
  44. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  45. // UserTypeOrganization defines an organization
  46. UserTypeOrganization
  47. )
  48. const (
  49. algoBcrypt = "bcrypt"
  50. algoScrypt = "scrypt"
  51. algoArgon2 = "argon2"
  52. algoPbkdf2 = "pbkdf2"
  53. )
  54. const syncExternalUsers = "sync_external_users"
  55. var (
  56. // ErrUserNotKeyOwner user does not own this key error
  57. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  58. // ErrEmailNotExist e-mail does not exist error
  59. ErrEmailNotExist = errors.New("E-mail does not exist")
  60. // ErrEmailNotActivated e-mail address has not been activated error
  61. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  62. // ErrUserNameIllegal user name contains illegal characters error
  63. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  64. // ErrLoginSourceNotActived login source is not actived error
  65. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  66. // ErrUnsupportedLoginType login source is unknown error
  67. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  68. )
  69. // User represents the object of individual and member of organization.
  70. type User struct {
  71. ID int64 `xorm:"pk autoincr"`
  72. LowerName string `xorm:"UNIQUE NOT NULL"`
  73. Name string `xorm:"UNIQUE NOT NULL"`
  74. FullName string
  75. // Email is the primary email address (to be used for communication)
  76. Email string `xorm:"NOT NULL"`
  77. KeepEmailPrivate bool
  78. Passwd string `xorm:"NOT NULL"`
  79. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'pbkdf2'"`
  80. // MustChangePassword is an attribute that determines if a user
  81. // is to change his/her password after registration.
  82. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  83. LoginType LoginType
  84. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  85. LoginName string
  86. Type UserType
  87. OwnedOrgs []*User `xorm:"-"`
  88. Orgs []*User `xorm:"-"`
  89. Repos []*Repository `xorm:"-"`
  90. Location string
  91. Website string
  92. Rands string `xorm:"VARCHAR(10)"`
  93. Salt string `xorm:"VARCHAR(10)"`
  94. Language string `xorm:"VARCHAR(5)"`
  95. Description string
  96. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  97. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  98. LastLoginUnix util.TimeStamp `xorm:"INDEX"`
  99. // Remember visibility choice for convenience, true for private
  100. LastRepoVisibility bool
  101. // Maximum repository creation limit, -1 means use global default
  102. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  103. // Permissions
  104. IsActive bool `xorm:"INDEX"` // Activate primary email
  105. IsAdmin bool
  106. AllowGitHook bool
  107. AllowImportLocal bool // Allow migrate repository by local path
  108. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  109. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  110. // Avatar
  111. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  112. AvatarEmail string `xorm:"NOT NULL"`
  113. UseCustomAvatar bool
  114. // Counters
  115. NumFollowers int
  116. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  117. NumStars int
  118. NumRepos int
  119. // For organization
  120. NumTeams int
  121. NumMembers int
  122. Teams []*Team `xorm:"-"`
  123. Members []*User `xorm:"-"`
  124. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  125. // Preferences
  126. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  127. Theme string `xorm:"NOT NULL DEFAULT ''"`
  128. }
  129. // ColorFormat writes a colored string to identify this struct
  130. func (u *User) ColorFormat(s fmt.State) {
  131. log.ColorFprintf(s, "%d:%s",
  132. log.NewColoredIDValue(u.ID),
  133. log.NewColoredValue(u.Name))
  134. }
  135. // BeforeUpdate is invoked from XORM before updating this object.
  136. func (u *User) BeforeUpdate() {
  137. if u.MaxRepoCreation < -1 {
  138. u.MaxRepoCreation = -1
  139. }
  140. // Organization does not need email
  141. u.Email = strings.ToLower(u.Email)
  142. if !u.IsOrganization() {
  143. if len(u.AvatarEmail) == 0 {
  144. u.AvatarEmail = u.Email
  145. }
  146. if len(u.AvatarEmail) > 0 && u.Avatar == "" {
  147. u.Avatar = base.HashEmail(u.AvatarEmail)
  148. }
  149. }
  150. u.LowerName = strings.ToLower(u.Name)
  151. u.Location = base.TruncateString(u.Location, 255)
  152. u.Website = base.TruncateString(u.Website, 255)
  153. u.Description = base.TruncateString(u.Description, 255)
  154. }
  155. // AfterLoad is invoked from XORM after filling all the fields of this object.
  156. func (u *User) AfterLoad() {
  157. if u.Theme == "" {
  158. u.Theme = setting.UI.DefaultTheme
  159. }
  160. }
  161. // SetLastLogin set time to last login
  162. func (u *User) SetLastLogin() {
  163. u.LastLoginUnix = util.TimeStampNow()
  164. }
  165. // UpdateDiffViewStyle updates the users diff view style
  166. func (u *User) UpdateDiffViewStyle(style string) error {
  167. u.DiffViewStyle = style
  168. return UpdateUserCols(u, "diff_view_style")
  169. }
  170. // UpdateTheme updates a users' theme irrespective of the site wide theme
  171. func (u *User) UpdateTheme(themeName string) error {
  172. u.Theme = themeName
  173. return UpdateUserCols(u, "theme")
  174. }
  175. // getEmail returns an noreply email, if the user has set to keep his
  176. // email address private, otherwise the primary email address.
  177. func (u *User) getEmail() string {
  178. if u.KeepEmailPrivate {
  179. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  180. }
  181. return u.Email
  182. }
  183. // APIFormat converts a User to api.User
  184. func (u *User) APIFormat() *api.User {
  185. return &api.User{
  186. ID: u.ID,
  187. UserName: u.Name,
  188. FullName: u.FullName,
  189. Email: u.getEmail(),
  190. AvatarURL: u.AvatarLink(),
  191. Language: u.Language,
  192. IsAdmin: u.IsAdmin,
  193. LastLogin: u.LastLoginUnix.AsTime(),
  194. Created: u.CreatedUnix.AsTime(),
  195. }
  196. }
  197. // IsLocal returns true if user login type is LoginPlain.
  198. func (u *User) IsLocal() bool {
  199. return u.LoginType <= LoginPlain
  200. }
  201. // IsOAuth2 returns true if user login type is LoginOAuth2.
  202. func (u *User) IsOAuth2() bool {
  203. return u.LoginType == LoginOAuth2
  204. }
  205. // HasForkedRepo checks if user has already forked a repository with given ID.
  206. func (u *User) HasForkedRepo(repoID int64) bool {
  207. _, has := HasForkedRepo(u.ID, repoID)
  208. return has
  209. }
  210. // MaxCreationLimit returns the number of repositories a user is allowed to create
  211. func (u *User) MaxCreationLimit() int {
  212. if u.MaxRepoCreation <= -1 {
  213. return setting.Repository.MaxCreationLimit
  214. }
  215. return u.MaxRepoCreation
  216. }
  217. // CanCreateRepo returns if user login can create a repository
  218. func (u *User) CanCreateRepo() bool {
  219. if u.IsAdmin {
  220. return true
  221. }
  222. if u.MaxRepoCreation <= -1 {
  223. if setting.Repository.MaxCreationLimit <= -1 {
  224. return true
  225. }
  226. return u.NumRepos < setting.Repository.MaxCreationLimit
  227. }
  228. return u.NumRepos < u.MaxRepoCreation
  229. }
  230. // CanCreateOrganization returns true if user can create organisation.
  231. func (u *User) CanCreateOrganization() bool {
  232. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  233. }
  234. // CanEditGitHook returns true if user can edit Git hooks.
  235. func (u *User) CanEditGitHook() bool {
  236. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  237. }
  238. // CanImportLocal returns true if user can migrate repository by local path.
  239. func (u *User) CanImportLocal() bool {
  240. if !setting.ImportLocalPaths {
  241. return false
  242. }
  243. return u.IsAdmin || u.AllowImportLocal
  244. }
  245. // DashboardLink returns the user dashboard page link.
  246. func (u *User) DashboardLink() string {
  247. if u.IsOrganization() {
  248. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  249. }
  250. return setting.AppSubURL + "/"
  251. }
  252. // HomeLink returns the user or organization home page link.
  253. func (u *User) HomeLink() string {
  254. return setting.AppSubURL + "/" + u.Name
  255. }
  256. // HTMLURL returns the user or organization's full link.
  257. func (u *User) HTMLURL() string {
  258. return setting.AppURL + u.Name
  259. }
  260. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  261. func (u *User) GenerateEmailActivateCode(email string) string {
  262. code := base.CreateTimeLimitCode(
  263. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  264. setting.Service.ActiveCodeLives, nil)
  265. // Add tail hex username
  266. code += hex.EncodeToString([]byte(u.LowerName))
  267. return code
  268. }
  269. // GenerateActivateCode generates an activate code based on user information.
  270. func (u *User) GenerateActivateCode() string {
  271. return u.GenerateEmailActivateCode(u.Email)
  272. }
  273. // CustomAvatarPath returns user custom avatar file path.
  274. func (u *User) CustomAvatarPath() string {
  275. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  276. }
  277. // GenerateRandomAvatar generates a random avatar for user.
  278. func (u *User) GenerateRandomAvatar() error {
  279. return u.generateRandomAvatar(x)
  280. }
  281. func (u *User) generateRandomAvatar(e Engine) error {
  282. seed := u.Email
  283. if len(seed) == 0 {
  284. seed = u.Name
  285. }
  286. img, err := avatar.RandomImage([]byte(seed))
  287. if err != nil {
  288. return fmt.Errorf("RandomImage: %v", err)
  289. }
  290. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  291. // since random image is not a user's photo, there is no security for enumable
  292. if u.Avatar == "" {
  293. u.Avatar = fmt.Sprintf("%d", u.ID)
  294. }
  295. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  296. return fmt.Errorf("MkdirAll: %v", err)
  297. }
  298. fw, err := os.Create(u.CustomAvatarPath())
  299. if err != nil {
  300. return fmt.Errorf("Create: %v", err)
  301. }
  302. defer fw.Close()
  303. if _, err := e.ID(u.ID).Cols("avatar").Update(u); err != nil {
  304. return err
  305. }
  306. if err = png.Encode(fw, img); err != nil {
  307. return fmt.Errorf("Encode: %v", err)
  308. }
  309. log.Info("New random avatar created: %d", u.ID)
  310. return nil
  311. }
  312. // SizedRelAvatarLink returns a relative link to the user's avatar. When
  313. // applicable, the link is for an avatar of the indicated size (in pixels).
  314. func (u *User) SizedRelAvatarLink(size int) string {
  315. if u.ID == -1 {
  316. return base.DefaultAvatarLink()
  317. }
  318. switch {
  319. case u.UseCustomAvatar:
  320. if !com.IsFile(u.CustomAvatarPath()) {
  321. return base.DefaultAvatarLink()
  322. }
  323. return setting.AppSubURL + "/avatars/" + u.Avatar
  324. case setting.DisableGravatar, setting.OfflineMode:
  325. if !com.IsFile(u.CustomAvatarPath()) {
  326. if err := u.GenerateRandomAvatar(); err != nil {
  327. log.Error("GenerateRandomAvatar: %v", err)
  328. }
  329. }
  330. return setting.AppSubURL + "/avatars/" + u.Avatar
  331. }
  332. return base.SizedAvatarLink(u.AvatarEmail, size)
  333. }
  334. // RelAvatarLink returns a relative link to the user's avatar. The link
  335. // may either be a sub-URL to this site, or a full URL to an external avatar
  336. // service.
  337. func (u *User) RelAvatarLink() string {
  338. return u.SizedRelAvatarLink(base.DefaultAvatarSize)
  339. }
  340. // AvatarLink returns user avatar absolute link.
  341. func (u *User) AvatarLink() string {
  342. link := u.RelAvatarLink()
  343. if link[0] == '/' && link[1] != '/' {
  344. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  345. }
  346. return link
  347. }
  348. // GetFollowers returns range of user's followers.
  349. func (u *User) GetFollowers(page int) ([]*User, error) {
  350. users := make([]*User, 0, ItemsPerPage)
  351. sess := x.
  352. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  353. Where("follow.follow_id=?", u.ID).
  354. Join("LEFT", "follow", "`user`.id=follow.user_id")
  355. return users, sess.Find(&users)
  356. }
  357. // IsFollowing returns true if user is following followID.
  358. func (u *User) IsFollowing(followID int64) bool {
  359. return IsFollowing(u.ID, followID)
  360. }
  361. // GetFollowing returns range of user's following.
  362. func (u *User) GetFollowing(page int) ([]*User, error) {
  363. users := make([]*User, 0, ItemsPerPage)
  364. sess := x.
  365. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  366. Where("follow.user_id=?", u.ID).
  367. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  368. return users, sess.Find(&users)
  369. }
  370. // NewGitSig generates and returns the signature of given user.
  371. func (u *User) NewGitSig() *git.Signature {
  372. return &git.Signature{
  373. Name: u.GitName(),
  374. Email: u.getEmail(),
  375. When: time.Now(),
  376. }
  377. }
  378. func hashPassword(passwd, salt, algo string) string {
  379. var tempPasswd []byte
  380. switch algo {
  381. case algoBcrypt:
  382. tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
  383. return string(tempPasswd)
  384. case algoScrypt:
  385. tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
  386. case algoArgon2:
  387. tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
  388. case algoPbkdf2:
  389. fallthrough
  390. default:
  391. tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  392. }
  393. return fmt.Sprintf("%x", tempPasswd)
  394. }
  395. // HashPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO.
  396. func (u *User) HashPassword(passwd string) {
  397. u.PasswdHashAlgo = setting.PasswordHashAlgo
  398. u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
  399. }
  400. // ValidatePassword checks if given password matches the one belongs to the user.
  401. func (u *User) ValidatePassword(passwd string) bool {
  402. tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
  403. if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
  404. return true
  405. }
  406. if u.PasswdHashAlgo == algoBcrypt && bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(passwd)) == nil {
  407. return true
  408. }
  409. return false
  410. }
  411. // IsPasswordSet checks if the password is set or left empty
  412. func (u *User) IsPasswordSet() bool {
  413. return len(u.Passwd) > 0
  414. }
  415. // UploadAvatar saves custom avatar for user.
  416. // FIXME: split uploads to different subdirs in case we have massive users.
  417. func (u *User) UploadAvatar(data []byte) error {
  418. m, err := avatar.Prepare(data)
  419. if err != nil {
  420. return err
  421. }
  422. sess := x.NewSession()
  423. defer sess.Close()
  424. if err = sess.Begin(); err != nil {
  425. return err
  426. }
  427. u.UseCustomAvatar = true
  428. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  429. if err = updateUser(sess, u); err != nil {
  430. return fmt.Errorf("updateUser: %v", err)
  431. }
  432. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  433. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  434. }
  435. fw, err := os.Create(u.CustomAvatarPath())
  436. if err != nil {
  437. return fmt.Errorf("Create: %v", err)
  438. }
  439. defer fw.Close()
  440. if err = png.Encode(fw, *m); err != nil {
  441. return fmt.Errorf("Encode: %v", err)
  442. }
  443. return sess.Commit()
  444. }
  445. // DeleteAvatar deletes the user's custom avatar.
  446. func (u *User) DeleteAvatar() error {
  447. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  448. if len(u.Avatar) > 0 {
  449. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  450. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  451. }
  452. }
  453. u.UseCustomAvatar = false
  454. u.Avatar = ""
  455. if _, err := x.ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  456. return fmt.Errorf("UpdateUser: %v", err)
  457. }
  458. return nil
  459. }
  460. // IsOrganization returns true if user is actually a organization.
  461. func (u *User) IsOrganization() bool {
  462. return u.Type == UserTypeOrganization
  463. }
  464. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  465. func (u *User) IsUserOrgOwner(orgID int64) bool {
  466. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  467. if err != nil {
  468. log.Error("IsOrganizationOwner: %v", err)
  469. return false
  470. }
  471. return isOwner
  472. }
  473. // IsUserPartOfOrg returns true if user with userID is part of the u organisation.
  474. func (u *User) IsUserPartOfOrg(userID int64) bool {
  475. return u.isUserPartOfOrg(x, userID)
  476. }
  477. func (u *User) isUserPartOfOrg(e Engine, userID int64) bool {
  478. isMember, err := isOrganizationMember(e, u.ID, userID)
  479. if err != nil {
  480. log.Error("IsOrganizationMember: %v", err)
  481. return false
  482. }
  483. return isMember
  484. }
  485. // IsPublicMember returns true if user public his/her membership in given organization.
  486. func (u *User) IsPublicMember(orgID int64) bool {
  487. isMember, err := IsPublicMembership(orgID, u.ID)
  488. if err != nil {
  489. log.Error("IsPublicMembership: %v", err)
  490. return false
  491. }
  492. return isMember
  493. }
  494. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  495. return e.
  496. Where("uid=?", u.ID).
  497. Count(new(OrgUser))
  498. }
  499. // GetOrganizationCount returns count of membership of organization of user.
  500. func (u *User) GetOrganizationCount() (int64, error) {
  501. return u.getOrganizationCount(x)
  502. }
  503. // GetRepositories returns repositories that user owns, including private repositories.
  504. func (u *User) GetRepositories(page, pageSize int) (err error) {
  505. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  506. return err
  507. }
  508. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  509. func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
  510. var ids []int64
  511. sess := x.Table("repository").Cols("repository.id")
  512. if len(units) > 0 {
  513. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  514. sess = sess.In("repo_unit.type", units)
  515. }
  516. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  517. }
  518. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  519. func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
  520. var ids []int64
  521. sess := x.Table("repository").
  522. Cols("repository.id").
  523. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  524. Join("INNER", "team_repo", "repository.is_private != ? OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true)
  525. if len(units) > 0 {
  526. sess = sess.Join("INNER", "team_unit", "team_unit.team_id = team_user.team_id")
  527. sess = sess.In("team_unit.type", units)
  528. }
  529. return ids, sess.
  530. Where("team_user.uid = ?", u.ID).
  531. GroupBy("repository.id").Find(&ids)
  532. }
  533. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  534. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  535. ids, err := u.GetRepositoryIDs(units...)
  536. if err != nil {
  537. return nil, err
  538. }
  539. ids2, err := u.GetOrgRepositoryIDs(units...)
  540. if err != nil {
  541. return nil, err
  542. }
  543. return append(ids, ids2...), nil
  544. }
  545. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  546. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  547. return GetUserMirrorRepositories(u.ID)
  548. }
  549. // GetOwnedOrganizations returns all organizations that user owns.
  550. func (u *User) GetOwnedOrganizations() (err error) {
  551. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  552. return err
  553. }
  554. // GetOrganizations returns all organizations that user belongs to.
  555. func (u *User) GetOrganizations(all bool) error {
  556. ous, err := GetOrgUsersByUserID(u.ID, all)
  557. if err != nil {
  558. return err
  559. }
  560. u.Orgs = make([]*User, len(ous))
  561. for i, ou := range ous {
  562. u.Orgs[i], err = GetUserByID(ou.OrgID)
  563. if err != nil {
  564. return err
  565. }
  566. }
  567. return nil
  568. }
  569. // DisplayName returns full name if it's not empty,
  570. // returns username otherwise.
  571. func (u *User) DisplayName() string {
  572. trimmed := strings.TrimSpace(u.FullName)
  573. if len(trimmed) > 0 {
  574. return trimmed
  575. }
  576. return u.Name
  577. }
  578. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  579. // returns username otherwise.
  580. func (u *User) GetDisplayName() string {
  581. trimmed := strings.TrimSpace(u.FullName)
  582. if len(trimmed) > 0 && setting.UI.DefaultShowFullName {
  583. return trimmed
  584. }
  585. return u.Name
  586. }
  587. func gitSafeName(name string) string {
  588. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  589. }
  590. // GitName returns a git safe name
  591. func (u *User) GitName() string {
  592. gitName := gitSafeName(u.FullName)
  593. if len(gitName) > 0 {
  594. return gitName
  595. }
  596. // Although u.Name should be safe if created in our system
  597. // LDAP users may have bad names
  598. gitName = gitSafeName(u.Name)
  599. if len(gitName) > 0 {
  600. return gitName
  601. }
  602. // Totally pathological name so it's got to be:
  603. return fmt.Sprintf("user-%d", u.ID)
  604. }
  605. // ShortName ellipses username to length
  606. func (u *User) ShortName(length int) string {
  607. return base.EllipsisString(u.Name, length)
  608. }
  609. // IsMailable checks if a user is eligible
  610. // to receive emails.
  611. func (u *User) IsMailable() bool {
  612. return u.IsActive
  613. }
  614. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  615. if len(name) == 0 {
  616. return false, nil
  617. }
  618. return e.
  619. Where("id!=?", uid).
  620. Get(&User{LowerName: strings.ToLower(name)})
  621. }
  622. // IsUserExist checks if given user name exist,
  623. // the user name should be noncased unique.
  624. // If uid is presented, then check will rule out that one,
  625. // it is used when update a user name in settings page.
  626. func IsUserExist(uid int64, name string) (bool, error) {
  627. return isUserExist(x, uid, name)
  628. }
  629. // GetUserSalt returns a random user salt token.
  630. func GetUserSalt() (string, error) {
  631. return generate.GetRandomString(10)
  632. }
  633. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  634. func NewGhostUser() *User {
  635. return &User{
  636. ID: -1,
  637. Name: "Ghost",
  638. LowerName: "ghost",
  639. }
  640. }
  641. var (
  642. reservedUsernames = []string{
  643. "admin",
  644. "api",
  645. "assets",
  646. "avatars",
  647. "commits",
  648. "css",
  649. "debug",
  650. "error",
  651. "explore",
  652. "ghost",
  653. "help",
  654. "img",
  655. "install",
  656. "issues",
  657. "js",
  658. "less",
  659. "metrics",
  660. "new",
  661. "notifications",
  662. "org",
  663. "plugins",
  664. "pulls",
  665. "raw",
  666. "repo",
  667. "stars",
  668. "template",
  669. "user",
  670. "vendor",
  671. "login",
  672. "robots.txt",
  673. ".",
  674. "..",
  675. }
  676. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  677. )
  678. // isUsableName checks if name is reserved or pattern of name is not allowed
  679. // based on given reserved names and patterns.
  680. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  681. func isUsableName(names, patterns []string, name string) error {
  682. name = strings.TrimSpace(strings.ToLower(name))
  683. if utf8.RuneCountInString(name) == 0 {
  684. return ErrNameEmpty
  685. }
  686. for i := range names {
  687. if name == names[i] {
  688. return ErrNameReserved{name}
  689. }
  690. }
  691. for _, pat := range patterns {
  692. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  693. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  694. return ErrNamePatternNotAllowed{pat}
  695. }
  696. }
  697. return nil
  698. }
  699. // IsUsableUsername returns an error when a username is reserved
  700. func IsUsableUsername(name string) error {
  701. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  702. }
  703. // CreateUser creates record of a new user.
  704. func CreateUser(u *User) (err error) {
  705. if err = IsUsableUsername(u.Name); err != nil {
  706. return err
  707. }
  708. sess := x.NewSession()
  709. defer sess.Close()
  710. if err = sess.Begin(); err != nil {
  711. return err
  712. }
  713. isExist, err := isUserExist(sess, 0, u.Name)
  714. if err != nil {
  715. return err
  716. } else if isExist {
  717. return ErrUserAlreadyExist{u.Name}
  718. }
  719. u.Email = strings.ToLower(u.Email)
  720. isExist, err = sess.
  721. Where("email=?", u.Email).
  722. Get(new(User))
  723. if err != nil {
  724. return err
  725. } else if isExist {
  726. return ErrEmailAlreadyUsed{u.Email}
  727. }
  728. isExist, err = isEmailUsed(sess, u.Email)
  729. if err != nil {
  730. return err
  731. } else if isExist {
  732. return ErrEmailAlreadyUsed{u.Email}
  733. }
  734. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  735. u.LowerName = strings.ToLower(u.Name)
  736. u.AvatarEmail = u.Email
  737. u.Avatar = base.HashEmail(u.AvatarEmail)
  738. if u.Rands, err = GetUserSalt(); err != nil {
  739. return err
  740. }
  741. if u.Salt, err = GetUserSalt(); err != nil {
  742. return err
  743. }
  744. u.HashPassword(u.Passwd)
  745. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  746. u.MaxRepoCreation = -1
  747. u.Theme = setting.UI.DefaultTheme
  748. if _, err = sess.Insert(u); err != nil {
  749. return err
  750. }
  751. return sess.Commit()
  752. }
  753. func countUsers(e Engine) int64 {
  754. count, _ := e.
  755. Where("type=0").
  756. Count(new(User))
  757. return count
  758. }
  759. // CountUsers returns number of users.
  760. func CountUsers() int64 {
  761. return countUsers(x)
  762. }
  763. // get user by verify code
  764. func getVerifyUser(code string) (user *User) {
  765. if len(code) <= base.TimeLimitCodeLength {
  766. return nil
  767. }
  768. // use tail hex username query user
  769. hexStr := code[base.TimeLimitCodeLength:]
  770. if b, err := hex.DecodeString(hexStr); err == nil {
  771. if user, err = GetUserByName(string(b)); user != nil {
  772. return user
  773. }
  774. log.Error("user.getVerifyUser: %v", err)
  775. }
  776. return nil
  777. }
  778. // VerifyUserActiveCode verifies active code when active account
  779. func VerifyUserActiveCode(code string) (user *User) {
  780. minutes := setting.Service.ActiveCodeLives
  781. if user = getVerifyUser(code); user != nil {
  782. // time limit code
  783. prefix := code[:base.TimeLimitCodeLength]
  784. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  785. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  786. return user
  787. }
  788. }
  789. return nil
  790. }
  791. // VerifyActiveEmailCode verifies active email code when active account
  792. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  793. minutes := setting.Service.ActiveCodeLives
  794. if user := getVerifyUser(code); user != nil {
  795. // time limit code
  796. prefix := code[:base.TimeLimitCodeLength]
  797. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  798. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  799. emailAddress := &EmailAddress{Email: email}
  800. if has, _ := x.Get(emailAddress); has {
  801. return emailAddress
  802. }
  803. }
  804. }
  805. return nil
  806. }
  807. // ChangeUserName changes all corresponding setting from old user name to new one.
  808. func ChangeUserName(u *User, newUserName string) (err error) {
  809. if err = IsUsableUsername(newUserName); err != nil {
  810. return err
  811. }
  812. isExist, err := IsUserExist(0, newUserName)
  813. if err != nil {
  814. return err
  815. } else if isExist {
  816. return ErrUserAlreadyExist{newUserName}
  817. }
  818. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  819. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  820. }
  821. // Do not fail if directory does not exist
  822. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  823. return fmt.Errorf("Rename user directory: %v", err)
  824. }
  825. return nil
  826. }
  827. // checkDupEmail checks whether there are the same email with the user
  828. func checkDupEmail(e Engine, u *User) error {
  829. u.Email = strings.ToLower(u.Email)
  830. has, err := e.
  831. Where("id!=?", u.ID).
  832. And("type=?", u.Type).
  833. And("email=?", u.Email).
  834. Get(new(User))
  835. if err != nil {
  836. return err
  837. } else if has {
  838. return ErrEmailAlreadyUsed{u.Email}
  839. }
  840. return nil
  841. }
  842. func updateUser(e Engine, u *User) error {
  843. _, err := e.ID(u.ID).AllCols().Update(u)
  844. return err
  845. }
  846. // UpdateUser updates user's information.
  847. func UpdateUser(u *User) error {
  848. return updateUser(x, u)
  849. }
  850. // UpdateUserCols update user according special columns
  851. func UpdateUserCols(u *User, cols ...string) error {
  852. return updateUserCols(x, u, cols...)
  853. }
  854. func updateUserCols(e Engine, u *User, cols ...string) error {
  855. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  856. return err
  857. }
  858. // UpdateUserSetting updates user's settings.
  859. func UpdateUserSetting(u *User) error {
  860. if !u.IsOrganization() {
  861. if err := checkDupEmail(x, u); err != nil {
  862. return err
  863. }
  864. }
  865. return updateUser(x, u)
  866. }
  867. // deleteBeans deletes all given beans, beans should contain delete conditions.
  868. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  869. for i := range beans {
  870. if _, err = e.Delete(beans[i]); err != nil {
  871. return err
  872. }
  873. }
  874. return nil
  875. }
  876. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  877. func deleteUser(e *xorm.Session, u *User) error {
  878. // Note: A user owns any repository or belongs to any organization
  879. // cannot perform delete operation.
  880. // Check ownership of repository.
  881. count, err := getRepositoryCount(e, u)
  882. if err != nil {
  883. return fmt.Errorf("GetRepositoryCount: %v", err)
  884. } else if count > 0 {
  885. return ErrUserOwnRepos{UID: u.ID}
  886. }
  887. // Check membership of organization.
  888. count, err = u.getOrganizationCount(e)
  889. if err != nil {
  890. return fmt.Errorf("GetOrganizationCount: %v", err)
  891. } else if count > 0 {
  892. return ErrUserHasOrgs{UID: u.ID}
  893. }
  894. // ***** START: Watch *****
  895. watchedRepoIDs := make([]int64, 0, 10)
  896. if err = e.Table("watch").Cols("watch.repo_id").
  897. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  898. return fmt.Errorf("get all watches: %v", err)
  899. }
  900. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  901. return fmt.Errorf("decrease repository num_watches: %v", err)
  902. }
  903. // ***** END: Watch *****
  904. // ***** START: Star *****
  905. starredRepoIDs := make([]int64, 0, 10)
  906. if err = e.Table("star").Cols("star.repo_id").
  907. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  908. return fmt.Errorf("get all stars: %v", err)
  909. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  910. return fmt.Errorf("decrease repository num_stars: %v", err)
  911. }
  912. // ***** END: Star *****
  913. // ***** START: Follow *****
  914. followeeIDs := make([]int64, 0, 10)
  915. if err = e.Table("follow").Cols("follow.follow_id").
  916. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  917. return fmt.Errorf("get all followees: %v", err)
  918. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  919. return fmt.Errorf("decrease user num_followers: %v", err)
  920. }
  921. followerIDs := make([]int64, 0, 10)
  922. if err = e.Table("follow").Cols("follow.user_id").
  923. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  924. return fmt.Errorf("get all followers: %v", err)
  925. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  926. return fmt.Errorf("decrease user num_following: %v", err)
  927. }
  928. // ***** END: Follow *****
  929. if err = deleteBeans(e,
  930. &AccessToken{UID: u.ID},
  931. &Collaboration{UserID: u.ID},
  932. &Access{UserID: u.ID},
  933. &Watch{UserID: u.ID},
  934. &Star{UID: u.ID},
  935. &Follow{UserID: u.ID},
  936. &Follow{FollowID: u.ID},
  937. &Action{UserID: u.ID},
  938. &IssueUser{UID: u.ID},
  939. &EmailAddress{UID: u.ID},
  940. &UserOpenID{UID: u.ID},
  941. &Reaction{UserID: u.ID},
  942. &TeamUser{UID: u.ID},
  943. &Collaboration{UserID: u.ID},
  944. &Stopwatch{UserID: u.ID},
  945. ); err != nil {
  946. return fmt.Errorf("deleteBeans: %v", err)
  947. }
  948. // ***** START: PublicKey *****
  949. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  950. return fmt.Errorf("deletePublicKeys: %v", err)
  951. }
  952. err = rewriteAllPublicKeys(e)
  953. if err != nil {
  954. return err
  955. }
  956. // ***** END: PublicKey *****
  957. // ***** START: GPGPublicKey *****
  958. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  959. return fmt.Errorf("deleteGPGKeys: %v", err)
  960. }
  961. // ***** END: GPGPublicKey *****
  962. // Clear assignee.
  963. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  964. return fmt.Errorf("clear assignee: %v", err)
  965. }
  966. // ***** START: ExternalLoginUser *****
  967. if err = removeAllAccountLinks(e, u); err != nil {
  968. return fmt.Errorf("ExternalLoginUser: %v", err)
  969. }
  970. // ***** END: ExternalLoginUser *****
  971. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  972. return fmt.Errorf("Delete: %v", err)
  973. }
  974. // FIXME: system notice
  975. // Note: There are something just cannot be roll back,
  976. // so just keep error logs of those operations.
  977. path := UserPath(u.Name)
  978. if err := os.RemoveAll(path); err != nil {
  979. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  980. }
  981. if len(u.Avatar) > 0 {
  982. avatarPath := u.CustomAvatarPath()
  983. if com.IsExist(avatarPath) {
  984. if err := os.Remove(avatarPath); err != nil {
  985. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  986. }
  987. }
  988. }
  989. return nil
  990. }
  991. // DeleteUser completely and permanently deletes everything of a user,
  992. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  993. func DeleteUser(u *User) (err error) {
  994. sess := x.NewSession()
  995. defer sess.Close()
  996. if err = sess.Begin(); err != nil {
  997. return err
  998. }
  999. if err = deleteUser(sess, u); err != nil {
  1000. // Note: don't wrapper error here.
  1001. return err
  1002. }
  1003. return sess.Commit()
  1004. }
  1005. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  1006. func DeleteInactivateUsers() (err error) {
  1007. users := make([]*User, 0, 10)
  1008. if err = x.
  1009. Where("is_active = ?", false).
  1010. Find(&users); err != nil {
  1011. return fmt.Errorf("get all inactive users: %v", err)
  1012. }
  1013. // FIXME: should only update authorized_keys file once after all deletions.
  1014. for _, u := range users {
  1015. if err = DeleteUser(u); err != nil {
  1016. // Ignore users that were set inactive by admin.
  1017. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1018. continue
  1019. }
  1020. return err
  1021. }
  1022. }
  1023. _, err = x.
  1024. Where("is_activated = ?", false).
  1025. Delete(new(EmailAddress))
  1026. return err
  1027. }
  1028. // UserPath returns the path absolute path of user repositories.
  1029. func UserPath(userName string) string {
  1030. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1031. }
  1032. // GetUserByKeyID get user information by user's public key id
  1033. func GetUserByKeyID(keyID int64) (*User, error) {
  1034. var user User
  1035. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  1036. Where("`public_key`.id=?", keyID).
  1037. Get(&user)
  1038. if err != nil {
  1039. return nil, err
  1040. }
  1041. if !has {
  1042. return nil, ErrUserNotExist{0, "", keyID}
  1043. }
  1044. return &user, nil
  1045. }
  1046. func getUserByID(e Engine, id int64) (*User, error) {
  1047. u := new(User)
  1048. has, err := e.ID(id).Get(u)
  1049. if err != nil {
  1050. return nil, err
  1051. } else if !has {
  1052. return nil, ErrUserNotExist{id, "", 0}
  1053. }
  1054. return u, nil
  1055. }
  1056. // GetUserByID returns the user object by given ID if exists.
  1057. func GetUserByID(id int64) (*User, error) {
  1058. return getUserByID(x, id)
  1059. }
  1060. // GetUserByName returns user by given name.
  1061. func GetUserByName(name string) (*User, error) {
  1062. return getUserByName(x, name)
  1063. }
  1064. func getUserByName(e Engine, name string) (*User, error) {
  1065. if len(name) == 0 {
  1066. return nil, ErrUserNotExist{0, name, 0}
  1067. }
  1068. u := &User{LowerName: strings.ToLower(name)}
  1069. has, err := e.Get(u)
  1070. if err != nil {
  1071. return nil, err
  1072. } else if !has {
  1073. return nil, ErrUserNotExist{0, name, 0}
  1074. }
  1075. return u, nil
  1076. }
  1077. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  1078. func GetUserEmailsByNames(names []string) []string {
  1079. return getUserEmailsByNames(x, names)
  1080. }
  1081. func getUserEmailsByNames(e Engine, names []string) []string {
  1082. mails := make([]string, 0, len(names))
  1083. for _, name := range names {
  1084. u, err := getUserByName(e, name)
  1085. if err != nil {
  1086. continue
  1087. }
  1088. if u.IsMailable() {
  1089. mails = append(mails, u.Email)
  1090. }
  1091. }
  1092. return mails
  1093. }
  1094. // GetUsersByIDs returns all resolved users from a list of Ids.
  1095. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1096. ous := make([]*User, 0, len(ids))
  1097. if len(ids) == 0 {
  1098. return ous, nil
  1099. }
  1100. err := x.In("id", ids).
  1101. Asc("name").
  1102. Find(&ous)
  1103. return ous, err
  1104. }
  1105. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1106. func GetUserIDsByNames(names []string) []int64 {
  1107. ids := make([]int64, 0, len(names))
  1108. for _, name := range names {
  1109. u, err := GetUserByName(name)
  1110. if err != nil {
  1111. continue
  1112. }
  1113. ids = append(ids, u.ID)
  1114. }
  1115. return ids
  1116. }
  1117. // UserCommit represents a commit with validation of user.
  1118. type UserCommit struct {
  1119. User *User
  1120. *git.Commit
  1121. }
  1122. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1123. func ValidateCommitWithEmail(c *git.Commit) *User {
  1124. if c.Author == nil {
  1125. return nil
  1126. }
  1127. u, err := GetUserByEmail(c.Author.Email)
  1128. if err != nil {
  1129. return nil
  1130. }
  1131. return u
  1132. }
  1133. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1134. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1135. var (
  1136. u *User
  1137. emails = map[string]*User{}
  1138. newCommits = list.New()
  1139. e = oldCommits.Front()
  1140. )
  1141. for e != nil {
  1142. c := e.Value.(*git.Commit)
  1143. if c.Author != nil {
  1144. if v, ok := emails[c.Author.Email]; !ok {
  1145. u, _ = GetUserByEmail(c.Author.Email)
  1146. emails[c.Author.Email] = u
  1147. } else {
  1148. u = v
  1149. }
  1150. } else {
  1151. u = nil
  1152. }
  1153. newCommits.PushBack(UserCommit{
  1154. User: u,
  1155. Commit: c,
  1156. })
  1157. e = e.Next()
  1158. }
  1159. return newCommits
  1160. }
  1161. // GetUserByEmail returns the user object by given e-mail if exists.
  1162. func GetUserByEmail(email string) (*User, error) {
  1163. if len(email) == 0 {
  1164. return nil, ErrUserNotExist{0, email, 0}
  1165. }
  1166. email = strings.ToLower(email)
  1167. // First try to find the user by primary email
  1168. user := &User{Email: email}
  1169. has, err := x.Get(user)
  1170. if err != nil {
  1171. return nil, err
  1172. }
  1173. if has {
  1174. return user, nil
  1175. }
  1176. // Otherwise, check in alternative list for activated email addresses
  1177. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1178. has, err = x.Get(emailAddress)
  1179. if err != nil {
  1180. return nil, err
  1181. }
  1182. if has {
  1183. return GetUserByID(emailAddress.UID)
  1184. }
  1185. // Finally, if email address is the protected email address:
  1186. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1187. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1188. user := &User{LowerName: username}
  1189. has, err := x.Get(user)
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. if has {
  1194. return user, nil
  1195. }
  1196. }
  1197. return nil, ErrUserNotExist{0, email, 0}
  1198. }
  1199. // GetUser checks if a user already exists
  1200. func GetUser(user *User) (bool, error) {
  1201. return x.Get(user)
  1202. }
  1203. // SearchUserOptions contains the options for searching
  1204. type SearchUserOptions struct {
  1205. Keyword string
  1206. Type UserType
  1207. UID int64
  1208. OrderBy SearchOrderBy
  1209. Page int
  1210. Private bool // Include private orgs in search
  1211. OwnerID int64 // id of user for visibility calculation
  1212. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1213. IsActive util.OptionalBool
  1214. SearchByEmail bool // Search by email as well as username/full name
  1215. }
  1216. func (opts *SearchUserOptions) toConds() builder.Cond {
  1217. var cond = builder.NewCond()
  1218. cond = cond.And(builder.Eq{"type": opts.Type})
  1219. if len(opts.Keyword) > 0 {
  1220. lowerKeyword := strings.ToLower(opts.Keyword)
  1221. keywordCond := builder.Or(
  1222. builder.Like{"lower_name", lowerKeyword},
  1223. builder.Like{"LOWER(full_name)", lowerKeyword},
  1224. )
  1225. if opts.SearchByEmail {
  1226. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1227. }
  1228. cond = cond.And(keywordCond)
  1229. }
  1230. if !opts.Private {
  1231. // user not logged in and so they won't be allowed to see non-public orgs
  1232. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1233. }
  1234. if opts.OwnerID > 0 {
  1235. var exprCond builder.Cond
  1236. if DbCfg.Type == core.MYSQL {
  1237. exprCond = builder.Expr("org_user.org_id = user.id")
  1238. } else if DbCfg.Type == core.MSSQL {
  1239. exprCond = builder.Expr("org_user.org_id = [user].id")
  1240. } else {
  1241. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1242. }
  1243. accessCond := builder.Or(
  1244. builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.OwnerID}, builder.Eq{"visibility": structs.VisibleTypePrivate}))),
  1245. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1246. cond = cond.And(accessCond)
  1247. }
  1248. if opts.UID > 0 {
  1249. cond = cond.And(builder.Eq{"id": opts.UID})
  1250. }
  1251. if !opts.IsActive.IsNone() {
  1252. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1253. }
  1254. return cond
  1255. }
  1256. // SearchUsers takes options i.e. keyword and part of user name to search,
  1257. // it returns results in given range and number of total results.
  1258. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1259. cond := opts.toConds()
  1260. count, err := x.Where(cond).Count(new(User))
  1261. if err != nil {
  1262. return nil, 0, fmt.Errorf("Count: %v", err)
  1263. }
  1264. if opts.PageSize == 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1265. opts.PageSize = setting.UI.ExplorePagingNum
  1266. }
  1267. if opts.Page <= 0 {
  1268. opts.Page = 1
  1269. }
  1270. if len(opts.OrderBy) == 0 {
  1271. opts.OrderBy = SearchOrderByAlphabetically
  1272. }
  1273. sess := x.Where(cond)
  1274. if opts.PageSize > 0 {
  1275. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1276. }
  1277. if opts.PageSize == -1 {
  1278. opts.PageSize = int(count)
  1279. }
  1280. users = make([]*User, 0, opts.PageSize)
  1281. return users, count, sess.OrderBy(opts.OrderBy.String()).Find(&users)
  1282. }
  1283. // GetStarredRepos returns the repos starred by a particular user
  1284. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1285. sess := x.Where("star.uid=?", userID).
  1286. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1287. if !private {
  1288. sess = sess.And("is_private=?", false)
  1289. }
  1290. repos := make([]*Repository, 0, 10)
  1291. err := sess.Find(&repos)
  1292. if err != nil {
  1293. return nil, err
  1294. }
  1295. return repos, nil
  1296. }
  1297. // GetWatchedRepos returns the repos watched by a particular user
  1298. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1299. sess := x.Where("watch.user_id=?", userID).
  1300. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1301. if !private {
  1302. sess = sess.And("is_private=?", false)
  1303. }
  1304. repos := make([]*Repository, 0, 10)
  1305. err := sess.Find(&repos)
  1306. if err != nil {
  1307. return nil, err
  1308. }
  1309. return repos, nil
  1310. }
  1311. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1312. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1313. // Start session
  1314. sess := x.NewSession()
  1315. defer sess.Close()
  1316. if err := sess.Begin(); err != nil {
  1317. return false, err
  1318. }
  1319. // Delete keys marked for deletion
  1320. var sshKeysNeedUpdate bool
  1321. for _, KeyToDelete := range keys {
  1322. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1323. if err != nil {
  1324. log.Error("SearchPublicKeyByContent: %v", err)
  1325. continue
  1326. }
  1327. if err = deletePublicKeys(sess, key.ID); err != nil {
  1328. log.Error("deletePublicKeys: %v", err)
  1329. continue
  1330. }
  1331. sshKeysNeedUpdate = true
  1332. }
  1333. if err := sess.Commit(); err != nil {
  1334. return false, err
  1335. }
  1336. return sshKeysNeedUpdate, nil
  1337. }
  1338. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1339. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1340. var sshKeysNeedUpdate bool
  1341. for _, sshKey := range sshPublicKeys {
  1342. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1343. if err == nil {
  1344. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1345. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1346. if IsErrKeyAlreadyExist(err) {
  1347. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1348. } else {
  1349. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1350. }
  1351. } else {
  1352. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1353. sshKeysNeedUpdate = true
  1354. }
  1355. } else {
  1356. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1357. }
  1358. }
  1359. return sshKeysNeedUpdate
  1360. }
  1361. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1362. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1363. var sshKeysNeedUpdate bool
  1364. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1365. // Get Public Keys from DB with current LDAP source
  1366. var giteaKeys []string
  1367. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1368. if err != nil {
  1369. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1370. }
  1371. for _, v := range keys {
  1372. giteaKeys = append(giteaKeys, v.OmitEmail())
  1373. }
  1374. // Get Public Keys from LDAP and skip duplicate keys
  1375. var ldapKeys []string
  1376. for _, v := range sshPublicKeys {
  1377. sshKeySplit := strings.Split(v, " ")
  1378. if len(sshKeySplit) > 1 {
  1379. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1380. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1381. ldapKeys = append(ldapKeys, ldapKey)
  1382. }
  1383. }
  1384. }
  1385. // Check if Public Key sync is needed
  1386. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1387. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Keys are already in sync for %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1388. return false
  1389. }
  1390. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1391. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1392. var newLdapSSHKeys []string
  1393. for _, LDAPPublicSSHKey := range ldapKeys {
  1394. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1395. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1396. }
  1397. }
  1398. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1399. sshKeysNeedUpdate = true
  1400. }
  1401. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1402. var giteaKeysToDelete []string
  1403. for _, giteaKey := range giteaKeys {
  1404. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1405. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1406. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1407. }
  1408. }
  1409. // Delete LDAP keys from DB that doesn't exist in LDAP
  1410. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1411. if err != nil {
  1412. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1413. }
  1414. if needUpd {
  1415. sshKeysNeedUpdate = true
  1416. }
  1417. return sshKeysNeedUpdate
  1418. }
  1419. // SyncExternalUsers is used to synchronize users with external authorization source
  1420. func SyncExternalUsers() {
  1421. if !taskStatusTable.StartIfNotRunning(syncExternalUsers) {
  1422. return
  1423. }
  1424. defer taskStatusTable.Stop(syncExternalUsers)
  1425. log.Trace("Doing: SyncExternalUsers")
  1426. ls, err := LoginSources()
  1427. if err != nil {
  1428. log.Error("SyncExternalUsers: %v", err)
  1429. return
  1430. }
  1431. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1432. for _, s := range ls {
  1433. if !s.IsActived || !s.IsSyncEnabled {
  1434. continue
  1435. }
  1436. if s.IsLDAP() {
  1437. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1438. var existingUsers []int64
  1439. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1440. var sshKeysNeedUpdate bool
  1441. // Find all users with this login type
  1442. var users []*User
  1443. err = x.Where("login_type = ?", LoginLDAP).
  1444. And("login_source = ?", s.ID).
  1445. Find(&users)
  1446. if err != nil {
  1447. log.Error("SyncExternalUsers: %v", err)
  1448. return
  1449. }
  1450. sr := s.LDAP().SearchEntries()
  1451. for _, su := range sr {
  1452. if len(su.Username) == 0 {
  1453. continue
  1454. }
  1455. if len(su.Mail) == 0 {
  1456. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1457. }
  1458. var usr *User
  1459. // Search for existing user
  1460. for _, du := range users {
  1461. if du.LowerName == strings.ToLower(su.Username) {
  1462. usr = du
  1463. break
  1464. }
  1465. }
  1466. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1467. // If no existing user found, create one
  1468. if usr == nil {
  1469. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1470. usr = &User{
  1471. LowerName: strings.ToLower(su.Username),
  1472. Name: su.Username,
  1473. FullName: fullName,
  1474. LoginType: s.Type,
  1475. LoginSource: s.ID,
  1476. LoginName: su.Username,
  1477. Email: su.Mail,
  1478. IsAdmin: su.IsAdmin,
  1479. IsActive: true,
  1480. }
  1481. err = CreateUser(usr)
  1482. if err != nil {
  1483. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1484. } else if isAttributeSSHPublicKeySet {
  1485. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1486. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1487. sshKeysNeedUpdate = true
  1488. }
  1489. }
  1490. } else if updateExisting {
  1491. existingUsers = append(existingUsers, usr.ID)
  1492. // Synchronize SSH Public Key if that attribute is set
  1493. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1494. sshKeysNeedUpdate = true
  1495. }
  1496. // Check if user data has changed
  1497. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1498. !strings.EqualFold(usr.Email, su.Mail) ||
  1499. usr.FullName != fullName ||
  1500. !usr.IsActive {
  1501. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1502. usr.FullName = fullName
  1503. usr.Email = su.Mail
  1504. // Change existing admin flag only if AdminFilter option is set
  1505. if len(s.LDAP().AdminFilter) > 0 {
  1506. usr.IsAdmin = su.IsAdmin
  1507. }
  1508. usr.IsActive = true
  1509. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1510. if err != nil {
  1511. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1512. }
  1513. }
  1514. }
  1515. }
  1516. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1517. if sshKeysNeedUpdate {
  1518. err = RewriteAllPublicKeys()
  1519. if err != nil {
  1520. log.Error("RewriteAllPublicKeys: %v", err)
  1521. }
  1522. }
  1523. // Deactivate users not present in LDAP
  1524. if updateExisting {
  1525. for _, usr := range users {
  1526. found := false
  1527. for _, uid := range existingUsers {
  1528. if usr.ID == uid {
  1529. found = true
  1530. break
  1531. }
  1532. }
  1533. if !found {
  1534. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1535. usr.IsActive = false
  1536. err = UpdateUserCols(usr, "is_active")
  1537. if err != nil {
  1538. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1539. }
  1540. }
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }