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

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