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

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