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