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

user.go 51KB

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