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.

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