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

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