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 50KB

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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  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/go-xorm/xorm"
  33. "github.com/unknwon/com"
  34. "golang.org/x/crypto/argon2"
  35. "golang.org/x/crypto/bcrypt"
  36. "golang.org/x/crypto/pbkdf2"
  37. "golang.org/x/crypto/scrypt"
  38. "golang.org/x/crypto/ssh"
  39. "xorm.io/builder"
  40. )
  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. "search",
  710. }
  711. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  712. )
  713. // isUsableName checks if name is reserved or pattern of name is not allowed
  714. // based on given reserved names and patterns.
  715. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  716. func isUsableName(names, patterns []string, name string) error {
  717. name = strings.TrimSpace(strings.ToLower(name))
  718. if utf8.RuneCountInString(name) == 0 {
  719. return ErrNameEmpty
  720. }
  721. for i := range names {
  722. if name == names[i] {
  723. return ErrNameReserved{name}
  724. }
  725. }
  726. for _, pat := range patterns {
  727. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  728. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  729. return ErrNamePatternNotAllowed{pat}
  730. }
  731. }
  732. return nil
  733. }
  734. // IsUsableUsername returns an error when a username is reserved
  735. func IsUsableUsername(name string) error {
  736. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  737. }
  738. // CreateUser creates record of a new user.
  739. func CreateUser(u *User) (err error) {
  740. if err = IsUsableUsername(u.Name); err != nil {
  741. return err
  742. }
  743. sess := x.NewSession()
  744. defer sess.Close()
  745. if err = sess.Begin(); err != nil {
  746. return err
  747. }
  748. isExist, err := isUserExist(sess, 0, u.Name)
  749. if err != nil {
  750. return err
  751. } else if isExist {
  752. return ErrUserAlreadyExist{u.Name}
  753. }
  754. u.Email = strings.ToLower(u.Email)
  755. isExist, err = sess.
  756. Where("email=?", u.Email).
  757. Get(new(User))
  758. if err != nil {
  759. return err
  760. } else if isExist {
  761. return ErrEmailAlreadyUsed{u.Email}
  762. }
  763. isExist, err = isEmailUsed(sess, u.Email)
  764. if err != nil {
  765. return err
  766. } else if isExist {
  767. return ErrEmailAlreadyUsed{u.Email}
  768. }
  769. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  770. u.LowerName = strings.ToLower(u.Name)
  771. u.AvatarEmail = u.Email
  772. u.Avatar = base.HashEmail(u.AvatarEmail)
  773. if u.Rands, err = GetUserSalt(); err != nil {
  774. return err
  775. }
  776. if u.Salt, err = GetUserSalt(); err != nil {
  777. return err
  778. }
  779. u.HashPassword(u.Passwd)
  780. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  781. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  782. u.MaxRepoCreation = -1
  783. u.Theme = setting.UI.DefaultTheme
  784. if _, err = sess.Insert(u); err != nil {
  785. return err
  786. }
  787. return sess.Commit()
  788. }
  789. func countUsers(e Engine) int64 {
  790. count, _ := e.
  791. Where("type=0").
  792. Count(new(User))
  793. return count
  794. }
  795. // CountUsers returns number of users.
  796. func CountUsers() int64 {
  797. return countUsers(x)
  798. }
  799. // get user by verify code
  800. func getVerifyUser(code string) (user *User) {
  801. if len(code) <= base.TimeLimitCodeLength {
  802. return nil
  803. }
  804. // use tail hex username query user
  805. hexStr := code[base.TimeLimitCodeLength:]
  806. if b, err := hex.DecodeString(hexStr); err == nil {
  807. if user, err = GetUserByName(string(b)); user != nil {
  808. return user
  809. }
  810. log.Error("user.getVerifyUser: %v", err)
  811. }
  812. return nil
  813. }
  814. // VerifyUserActiveCode verifies active code when active account
  815. func VerifyUserActiveCode(code string) (user *User) {
  816. minutes := setting.Service.ActiveCodeLives
  817. if user = getVerifyUser(code); user != nil {
  818. // time limit code
  819. prefix := code[:base.TimeLimitCodeLength]
  820. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  821. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  822. return user
  823. }
  824. }
  825. return nil
  826. }
  827. // VerifyActiveEmailCode verifies active email code when active account
  828. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  829. minutes := setting.Service.ActiveCodeLives
  830. if user := getVerifyUser(code); user != nil {
  831. // time limit code
  832. prefix := code[:base.TimeLimitCodeLength]
  833. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  834. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  835. emailAddress := &EmailAddress{Email: email}
  836. if has, _ := x.Get(emailAddress); has {
  837. return emailAddress
  838. }
  839. }
  840. }
  841. return nil
  842. }
  843. // ChangeUserName changes all corresponding setting from old user name to new one.
  844. func ChangeUserName(u *User, newUserName string) (err error) {
  845. if err = IsUsableUsername(newUserName); err != nil {
  846. return err
  847. }
  848. isExist, err := IsUserExist(0, newUserName)
  849. if err != nil {
  850. return err
  851. } else if isExist {
  852. return ErrUserAlreadyExist{newUserName}
  853. }
  854. // Do not fail if directory does not exist
  855. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  856. return fmt.Errorf("Rename user directory: %v", err)
  857. }
  858. return nil
  859. }
  860. // checkDupEmail checks whether there are the same email with the user
  861. func checkDupEmail(e Engine, u *User) error {
  862. u.Email = strings.ToLower(u.Email)
  863. has, err := e.
  864. Where("id!=?", u.ID).
  865. And("type=?", u.Type).
  866. And("email=?", u.Email).
  867. Get(new(User))
  868. if err != nil {
  869. return err
  870. } else if has {
  871. return ErrEmailAlreadyUsed{u.Email}
  872. }
  873. return nil
  874. }
  875. func updateUser(e Engine, u *User) error {
  876. _, err := e.ID(u.ID).AllCols().Update(u)
  877. return err
  878. }
  879. // UpdateUser updates user's information.
  880. func UpdateUser(u *User) error {
  881. return updateUser(x, u)
  882. }
  883. // UpdateUserCols update user according special columns
  884. func UpdateUserCols(u *User, cols ...string) error {
  885. return updateUserCols(x, u, cols...)
  886. }
  887. func updateUserCols(e Engine, u *User, cols ...string) error {
  888. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  889. return err
  890. }
  891. // UpdateUserSetting updates user's settings.
  892. func UpdateUserSetting(u *User) error {
  893. if !u.IsOrganization() {
  894. if err := checkDupEmail(x, u); err != nil {
  895. return err
  896. }
  897. }
  898. return updateUser(x, u)
  899. }
  900. // deleteBeans deletes all given beans, beans should contain delete conditions.
  901. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  902. for i := range beans {
  903. if _, err = e.Delete(beans[i]); err != nil {
  904. return err
  905. }
  906. }
  907. return nil
  908. }
  909. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  910. func deleteUser(e *xorm.Session, u *User) error {
  911. // Note: A user owns any repository or belongs to any organization
  912. // cannot perform delete operation.
  913. // Check ownership of repository.
  914. count, err := getRepositoryCount(e, u)
  915. if err != nil {
  916. return fmt.Errorf("GetRepositoryCount: %v", err)
  917. } else if count > 0 {
  918. return ErrUserOwnRepos{UID: u.ID}
  919. }
  920. // Check membership of organization.
  921. count, err = u.getOrganizationCount(e)
  922. if err != nil {
  923. return fmt.Errorf("GetOrganizationCount: %v", err)
  924. } else if count > 0 {
  925. return ErrUserHasOrgs{UID: u.ID}
  926. }
  927. // ***** START: Watch *****
  928. watchedRepoIDs := make([]int64, 0, 10)
  929. if err = e.Table("watch").Cols("watch.repo_id").
  930. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  931. return fmt.Errorf("get all watches: %v", err)
  932. }
  933. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  934. return fmt.Errorf("decrease repository num_watches: %v", err)
  935. }
  936. // ***** END: Watch *****
  937. // ***** START: Star *****
  938. starredRepoIDs := make([]int64, 0, 10)
  939. if err = e.Table("star").Cols("star.repo_id").
  940. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  941. return fmt.Errorf("get all stars: %v", err)
  942. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  943. return fmt.Errorf("decrease repository num_stars: %v", err)
  944. }
  945. // ***** END: Star *****
  946. // ***** START: Follow *****
  947. followeeIDs := make([]int64, 0, 10)
  948. if err = e.Table("follow").Cols("follow.follow_id").
  949. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  950. return fmt.Errorf("get all followees: %v", err)
  951. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  952. return fmt.Errorf("decrease user num_followers: %v", err)
  953. }
  954. followerIDs := make([]int64, 0, 10)
  955. if err = e.Table("follow").Cols("follow.user_id").
  956. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  957. return fmt.Errorf("get all followers: %v", err)
  958. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  959. return fmt.Errorf("decrease user num_following: %v", err)
  960. }
  961. // ***** END: Follow *****
  962. if err = deleteBeans(e,
  963. &AccessToken{UID: u.ID},
  964. &Collaboration{UserID: u.ID},
  965. &Access{UserID: u.ID},
  966. &Watch{UserID: u.ID},
  967. &Star{UID: u.ID},
  968. &Follow{UserID: u.ID},
  969. &Follow{FollowID: u.ID},
  970. &Action{UserID: u.ID},
  971. &IssueUser{UID: u.ID},
  972. &EmailAddress{UID: u.ID},
  973. &UserOpenID{UID: u.ID},
  974. &Reaction{UserID: u.ID},
  975. &TeamUser{UID: u.ID},
  976. &Collaboration{UserID: u.ID},
  977. &Stopwatch{UserID: u.ID},
  978. ); err != nil {
  979. return fmt.Errorf("deleteBeans: %v", err)
  980. }
  981. // ***** START: PublicKey *****
  982. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  983. return fmt.Errorf("deletePublicKeys: %v", err)
  984. }
  985. err = rewriteAllPublicKeys(e)
  986. if err != nil {
  987. return err
  988. }
  989. // ***** END: PublicKey *****
  990. // ***** START: GPGPublicKey *****
  991. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  992. return fmt.Errorf("deleteGPGKeys: %v", err)
  993. }
  994. // ***** END: GPGPublicKey *****
  995. // Clear assignee.
  996. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  997. return fmt.Errorf("clear assignee: %v", err)
  998. }
  999. // ***** START: ExternalLoginUser *****
  1000. if err = removeAllAccountLinks(e, u); err != nil {
  1001. return fmt.Errorf("ExternalLoginUser: %v", err)
  1002. }
  1003. // ***** END: ExternalLoginUser *****
  1004. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  1005. return fmt.Errorf("Delete: %v", err)
  1006. }
  1007. // FIXME: system notice
  1008. // Note: There are something just cannot be roll back,
  1009. // so just keep error logs of those operations.
  1010. path := UserPath(u.Name)
  1011. if err := os.RemoveAll(path); err != nil {
  1012. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  1013. }
  1014. if len(u.Avatar) > 0 {
  1015. avatarPath := u.CustomAvatarPath()
  1016. if com.IsExist(avatarPath) {
  1017. if err := os.Remove(avatarPath); err != nil {
  1018. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1019. }
  1020. }
  1021. }
  1022. return nil
  1023. }
  1024. // DeleteUser completely and permanently deletes everything of a user,
  1025. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  1026. func DeleteUser(u *User) (err error) {
  1027. sess := x.NewSession()
  1028. defer sess.Close()
  1029. if err = sess.Begin(); err != nil {
  1030. return err
  1031. }
  1032. if err = deleteUser(sess, u); err != nil {
  1033. // Note: don't wrapper error here.
  1034. return err
  1035. }
  1036. return sess.Commit()
  1037. }
  1038. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  1039. func DeleteInactivateUsers() (err error) {
  1040. users := make([]*User, 0, 10)
  1041. if err = x.
  1042. Where("is_active = ?", false).
  1043. Find(&users); err != nil {
  1044. return fmt.Errorf("get all inactive users: %v", err)
  1045. }
  1046. // FIXME: should only update authorized_keys file once after all deletions.
  1047. for _, u := range users {
  1048. if err = DeleteUser(u); err != nil {
  1049. // Ignore users that were set inactive by admin.
  1050. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1051. continue
  1052. }
  1053. return err
  1054. }
  1055. }
  1056. _, err = x.
  1057. Where("is_activated = ?", false).
  1058. Delete(new(EmailAddress))
  1059. return err
  1060. }
  1061. // UserPath returns the path absolute path of user repositories.
  1062. func UserPath(userName string) string {
  1063. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1064. }
  1065. // GetUserByKeyID get user information by user's public key id
  1066. func GetUserByKeyID(keyID int64) (*User, error) {
  1067. var user User
  1068. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  1069. Where("`public_key`.id=?", keyID).
  1070. Get(&user)
  1071. if err != nil {
  1072. return nil, err
  1073. }
  1074. if !has {
  1075. return nil, ErrUserNotExist{0, "", keyID}
  1076. }
  1077. return &user, nil
  1078. }
  1079. func getUserByID(e Engine, id int64) (*User, error) {
  1080. u := new(User)
  1081. has, err := e.ID(id).Get(u)
  1082. if err != nil {
  1083. return nil, err
  1084. } else if !has {
  1085. return nil, ErrUserNotExist{id, "", 0}
  1086. }
  1087. return u, nil
  1088. }
  1089. // GetUserByID returns the user object by given ID if exists.
  1090. func GetUserByID(id int64) (*User, error) {
  1091. return getUserByID(x, id)
  1092. }
  1093. // GetUserByName returns user by given name.
  1094. func GetUserByName(name string) (*User, error) {
  1095. return getUserByName(x, name)
  1096. }
  1097. func getUserByName(e Engine, name string) (*User, error) {
  1098. if len(name) == 0 {
  1099. return nil, ErrUserNotExist{0, name, 0}
  1100. }
  1101. u := &User{LowerName: strings.ToLower(name)}
  1102. has, err := e.Get(u)
  1103. if err != nil {
  1104. return nil, err
  1105. } else if !has {
  1106. return nil, ErrUserNotExist{0, name, 0}
  1107. }
  1108. return u, nil
  1109. }
  1110. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1111. // that have their email notifications set to enabled or onmention.
  1112. func GetUserEmailsByNames(names []string) []string {
  1113. return getUserEmailsByNames(x, names)
  1114. }
  1115. func getUserEmailsByNames(e Engine, names []string) []string {
  1116. mails := make([]string, 0, len(names))
  1117. for _, name := range names {
  1118. u, err := getUserByName(e, name)
  1119. if err != nil {
  1120. continue
  1121. }
  1122. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1123. mails = append(mails, u.Email)
  1124. }
  1125. }
  1126. return mails
  1127. }
  1128. // GetUsersByIDs returns all resolved users from a list of Ids.
  1129. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1130. ous := make([]*User, 0, len(ids))
  1131. if len(ids) == 0 {
  1132. return ous, nil
  1133. }
  1134. err := x.In("id", ids).
  1135. Asc("name").
  1136. Find(&ous)
  1137. return ous, err
  1138. }
  1139. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1140. func GetUserIDsByNames(names []string) []int64 {
  1141. ids := make([]int64, 0, len(names))
  1142. for _, name := range names {
  1143. u, err := GetUserByName(name)
  1144. if err != nil {
  1145. continue
  1146. }
  1147. ids = append(ids, u.ID)
  1148. }
  1149. return ids
  1150. }
  1151. // UserCommit represents a commit with validation of user.
  1152. type UserCommit struct {
  1153. User *User
  1154. *git.Commit
  1155. }
  1156. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1157. func ValidateCommitWithEmail(c *git.Commit) *User {
  1158. if c.Author == nil {
  1159. return nil
  1160. }
  1161. u, err := GetUserByEmail(c.Author.Email)
  1162. if err != nil {
  1163. return nil
  1164. }
  1165. return u
  1166. }
  1167. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1168. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1169. var (
  1170. u *User
  1171. emails = map[string]*User{}
  1172. newCommits = list.New()
  1173. e = oldCommits.Front()
  1174. )
  1175. for e != nil {
  1176. c := e.Value.(*git.Commit)
  1177. if c.Author != nil {
  1178. if v, ok := emails[c.Author.Email]; !ok {
  1179. u, _ = GetUserByEmail(c.Author.Email)
  1180. emails[c.Author.Email] = u
  1181. } else {
  1182. u = v
  1183. }
  1184. } else {
  1185. u = nil
  1186. }
  1187. newCommits.PushBack(UserCommit{
  1188. User: u,
  1189. Commit: c,
  1190. })
  1191. e = e.Next()
  1192. }
  1193. return newCommits
  1194. }
  1195. // GetUserByEmail returns the user object by given e-mail if exists.
  1196. func GetUserByEmail(email string) (*User, error) {
  1197. if len(email) == 0 {
  1198. return nil, ErrUserNotExist{0, email, 0}
  1199. }
  1200. email = strings.ToLower(email)
  1201. // First try to find the user by primary email
  1202. user := &User{Email: email}
  1203. has, err := x.Get(user)
  1204. if err != nil {
  1205. return nil, err
  1206. }
  1207. if has {
  1208. return user, nil
  1209. }
  1210. // Otherwise, check in alternative list for activated email addresses
  1211. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1212. has, err = x.Get(emailAddress)
  1213. if err != nil {
  1214. return nil, err
  1215. }
  1216. if has {
  1217. return GetUserByID(emailAddress.UID)
  1218. }
  1219. // Finally, if email address is the protected email address:
  1220. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1221. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1222. user := &User{LowerName: username}
  1223. has, err := x.Get(user)
  1224. if err != nil {
  1225. return nil, err
  1226. }
  1227. if has {
  1228. return user, nil
  1229. }
  1230. }
  1231. return nil, ErrUserNotExist{0, email, 0}
  1232. }
  1233. // GetUser checks if a user already exists
  1234. func GetUser(user *User) (bool, error) {
  1235. return x.Get(user)
  1236. }
  1237. // SearchUserOptions contains the options for searching
  1238. type SearchUserOptions struct {
  1239. Keyword string
  1240. Type UserType
  1241. UID int64
  1242. OrderBy SearchOrderBy
  1243. Page int
  1244. Private bool // Include private orgs in search
  1245. OwnerID int64 // id of user for visibility calculation
  1246. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1247. IsActive util.OptionalBool
  1248. SearchByEmail bool // Search by email as well as username/full name
  1249. }
  1250. func (opts *SearchUserOptions) toConds() builder.Cond {
  1251. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1252. if len(opts.Keyword) > 0 {
  1253. lowerKeyword := strings.ToLower(opts.Keyword)
  1254. keywordCond := builder.Or(
  1255. builder.Like{"lower_name", lowerKeyword},
  1256. builder.Like{"LOWER(full_name)", lowerKeyword},
  1257. )
  1258. if opts.SearchByEmail {
  1259. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1260. }
  1261. cond = cond.And(keywordCond)
  1262. }
  1263. if !opts.Private {
  1264. // user not logged in and so they won't be allowed to see non-public orgs
  1265. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1266. }
  1267. if opts.OwnerID > 0 {
  1268. var exprCond builder.Cond
  1269. if setting.Database.UseMySQL {
  1270. exprCond = builder.Expr("org_user.org_id = user.id")
  1271. } else if setting.Database.UseMSSQL {
  1272. exprCond = builder.Expr("org_user.org_id = [user].id")
  1273. } else {
  1274. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1275. }
  1276. accessCond := builder.Or(
  1277. 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}))),
  1278. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1279. cond = cond.And(accessCond)
  1280. }
  1281. if opts.UID > 0 {
  1282. cond = cond.And(builder.Eq{"id": opts.UID})
  1283. }
  1284. if !opts.IsActive.IsNone() {
  1285. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1286. }
  1287. return cond
  1288. }
  1289. // SearchUsers takes options i.e. keyword and part of user name to search,
  1290. // it returns results in given range and number of total results.
  1291. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1292. cond := opts.toConds()
  1293. count, err := x.Where(cond).Count(new(User))
  1294. if err != nil {
  1295. return nil, 0, fmt.Errorf("Count: %v", err)
  1296. }
  1297. if opts.PageSize == 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1298. opts.PageSize = setting.UI.ExplorePagingNum
  1299. }
  1300. if opts.Page <= 0 {
  1301. opts.Page = 1
  1302. }
  1303. if len(opts.OrderBy) == 0 {
  1304. opts.OrderBy = SearchOrderByAlphabetically
  1305. }
  1306. sess := x.Where(cond)
  1307. if opts.PageSize > 0 {
  1308. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1309. }
  1310. if opts.PageSize == -1 {
  1311. opts.PageSize = int(count)
  1312. }
  1313. users = make([]*User, 0, opts.PageSize)
  1314. return users, count, sess.OrderBy(opts.OrderBy.String()).Find(&users)
  1315. }
  1316. // GetStarredRepos returns the repos starred by a particular user
  1317. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1318. sess := x.Where("star.uid=?", userID).
  1319. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1320. if !private {
  1321. sess = sess.And("is_private=?", false)
  1322. }
  1323. repos := make([]*Repository, 0, 10)
  1324. err := sess.Find(&repos)
  1325. if err != nil {
  1326. return nil, err
  1327. }
  1328. return repos, nil
  1329. }
  1330. // GetWatchedRepos returns the repos watched by a particular user
  1331. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1332. sess := x.Where("watch.user_id=?", userID).
  1333. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1334. if !private {
  1335. sess = sess.And("is_private=?", false)
  1336. }
  1337. repos := make([]*Repository, 0, 10)
  1338. err := sess.Find(&repos)
  1339. if err != nil {
  1340. return nil, err
  1341. }
  1342. return repos, nil
  1343. }
  1344. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1345. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1346. // Start session
  1347. sess := x.NewSession()
  1348. defer sess.Close()
  1349. if err := sess.Begin(); err != nil {
  1350. return false, err
  1351. }
  1352. // Delete keys marked for deletion
  1353. var sshKeysNeedUpdate bool
  1354. for _, KeyToDelete := range keys {
  1355. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1356. if err != nil {
  1357. log.Error("SearchPublicKeyByContent: %v", err)
  1358. continue
  1359. }
  1360. if err = deletePublicKeys(sess, key.ID); err != nil {
  1361. log.Error("deletePublicKeys: %v", err)
  1362. continue
  1363. }
  1364. sshKeysNeedUpdate = true
  1365. }
  1366. if err := sess.Commit(); err != nil {
  1367. return false, err
  1368. }
  1369. return sshKeysNeedUpdate, nil
  1370. }
  1371. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1372. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1373. var sshKeysNeedUpdate bool
  1374. for _, sshKey := range sshPublicKeys {
  1375. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1376. if err == nil {
  1377. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1378. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1379. if IsErrKeyAlreadyExist(err) {
  1380. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1381. } else {
  1382. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1383. }
  1384. } else {
  1385. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1386. sshKeysNeedUpdate = true
  1387. }
  1388. } else {
  1389. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1390. }
  1391. }
  1392. return sshKeysNeedUpdate
  1393. }
  1394. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1395. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1396. var sshKeysNeedUpdate bool
  1397. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1398. // Get Public Keys from DB with current LDAP source
  1399. var giteaKeys []string
  1400. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1401. if err != nil {
  1402. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1403. }
  1404. for _, v := range keys {
  1405. giteaKeys = append(giteaKeys, v.OmitEmail())
  1406. }
  1407. // Get Public Keys from LDAP and skip duplicate keys
  1408. var ldapKeys []string
  1409. for _, v := range sshPublicKeys {
  1410. sshKeySplit := strings.Split(v, " ")
  1411. if len(sshKeySplit) > 1 {
  1412. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1413. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1414. ldapKeys = append(ldapKeys, ldapKey)
  1415. }
  1416. }
  1417. }
  1418. // Check if Public Key sync is needed
  1419. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1420. 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))
  1421. return false
  1422. }
  1423. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1424. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1425. var newLdapSSHKeys []string
  1426. for _, LDAPPublicSSHKey := range ldapKeys {
  1427. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1428. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1429. }
  1430. }
  1431. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1432. sshKeysNeedUpdate = true
  1433. }
  1434. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1435. var giteaKeysToDelete []string
  1436. for _, giteaKey := range giteaKeys {
  1437. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1438. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1439. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1440. }
  1441. }
  1442. // Delete LDAP keys from DB that doesn't exist in LDAP
  1443. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1444. if err != nil {
  1445. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1446. }
  1447. if needUpd {
  1448. sshKeysNeedUpdate = true
  1449. }
  1450. return sshKeysNeedUpdate
  1451. }
  1452. // SyncExternalUsers is used to synchronize users with external authorization source
  1453. func SyncExternalUsers() {
  1454. log.Trace("Doing: SyncExternalUsers")
  1455. ls, err := LoginSources()
  1456. if err != nil {
  1457. log.Error("SyncExternalUsers: %v", err)
  1458. return
  1459. }
  1460. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1461. for _, s := range ls {
  1462. if !s.IsActived || !s.IsSyncEnabled {
  1463. continue
  1464. }
  1465. if s.IsLDAP() {
  1466. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1467. var existingUsers []int64
  1468. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1469. var sshKeysNeedUpdate bool
  1470. // Find all users with this login type
  1471. var users []*User
  1472. err = x.Where("login_type = ?", LoginLDAP).
  1473. And("login_source = ?", s.ID).
  1474. Find(&users)
  1475. if err != nil {
  1476. log.Error("SyncExternalUsers: %v", err)
  1477. return
  1478. }
  1479. sr, err := s.LDAP().SearchEntries()
  1480. if err != nil {
  1481. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1482. continue
  1483. }
  1484. for _, su := range sr {
  1485. if len(su.Username) == 0 {
  1486. continue
  1487. }
  1488. if len(su.Mail) == 0 {
  1489. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1490. }
  1491. var usr *User
  1492. // Search for existing user
  1493. for _, du := range users {
  1494. if du.LowerName == strings.ToLower(su.Username) {
  1495. usr = du
  1496. break
  1497. }
  1498. }
  1499. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1500. // If no existing user found, create one
  1501. if usr == nil {
  1502. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1503. usr = &User{
  1504. LowerName: strings.ToLower(su.Username),
  1505. Name: su.Username,
  1506. FullName: fullName,
  1507. LoginType: s.Type,
  1508. LoginSource: s.ID,
  1509. LoginName: su.Username,
  1510. Email: su.Mail,
  1511. IsAdmin: su.IsAdmin,
  1512. IsActive: true,
  1513. }
  1514. err = CreateUser(usr)
  1515. if err != nil {
  1516. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1517. } else if isAttributeSSHPublicKeySet {
  1518. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1519. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1520. sshKeysNeedUpdate = true
  1521. }
  1522. }
  1523. } else if updateExisting {
  1524. existingUsers = append(existingUsers, usr.ID)
  1525. // Synchronize SSH Public Key if that attribute is set
  1526. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1527. sshKeysNeedUpdate = true
  1528. }
  1529. // Check if user data has changed
  1530. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1531. !strings.EqualFold(usr.Email, su.Mail) ||
  1532. usr.FullName != fullName ||
  1533. !usr.IsActive {
  1534. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1535. usr.FullName = fullName
  1536. usr.Email = su.Mail
  1537. // Change existing admin flag only if AdminFilter option is set
  1538. if len(s.LDAP().AdminFilter) > 0 {
  1539. usr.IsAdmin = su.IsAdmin
  1540. }
  1541. usr.IsActive = true
  1542. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1543. if err != nil {
  1544. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1545. }
  1546. }
  1547. }
  1548. }
  1549. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1550. if sshKeysNeedUpdate {
  1551. err = RewriteAllPublicKeys()
  1552. if err != nil {
  1553. log.Error("RewriteAllPublicKeys: %v", err)
  1554. }
  1555. }
  1556. // Deactivate users not present in LDAP
  1557. if updateExisting {
  1558. for _, usr := range users {
  1559. found := false
  1560. for _, uid := range existingUsers {
  1561. if usr.ID == uid {
  1562. found = true
  1563. break
  1564. }
  1565. }
  1566. if !found {
  1567. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1568. usr.IsActive = false
  1569. err = UpdateUserCols(usr, "is_active")
  1570. if err != nil {
  1571. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1572. }
  1573. }
  1574. }
  1575. }
  1576. }
  1577. }
  1578. }