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

user.go 50 kB

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