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.

1899 lines
53 KiB

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