You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 54 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 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>
5 years ago
11 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 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)
8 years ago
9 years ago
9 years ago
11 years ago
11 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
11 years ago
11 years ago
11 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)
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)
8 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
6 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
6 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
6 years ago
9 years ago
9 years ago
9 years ago
Adopt repositories (#12920) * Don't automatically delete repository files if they are present Prior to this PR Gitea would delete any repository files if they are present during creation or migration. This can in certain circumstances lead to data-loss and is slightly unpleasant. This PR provides a mechanism for Gitea to adopt repositories on creation and otherwise requires an explicit flag for deletion. PushCreate is slightly different - the create will cause adoption if that is allowed otherwise it will delete the data if that is allowed. Signed-off-by: Andrew Thornton <art27@cantab.net> * Update swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix tests and migrate overwrite Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @lunny Only offer to adopt or overwrite if the user can do that. Allow the site administrator to adopt or overwrite in all circumstances Signed-off-by: Andrew Thornton <art27@cantab.net> * Use setting.Repository.DefaultBranch for the default branch Signed-off-by: Andrew Thornton <art27@cantab.net> * Always set setting.Repository.DefaultBranch Signed-off-by: Andrew Thornton <art27@cantab.net> * update swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * update templates Signed-off-by: Andrew Thornton <art27@cantab.net> * ensure repo closed Signed-off-by: Andrew Thornton <art27@cantab.net> * Rewrite of adoption as per @6543 and @lunny Signed-off-by: Andrew Thornton <art27@cantab.net> * Apply suggestions from code review * update swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * missing not Signed-off-by: Andrew Thornton <art27@cantab.net> * add modals and flash reporting Signed-off-by: Andrew Thornton <art27@cantab.net> * Make the unadopted page searchable Signed-off-by: Andrew Thornton <art27@cantab.net> * Add API Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * fix swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * Handle empty and non-master branched repositories Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * remove commented out code Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
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>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
Add ssh certificate support (#12281) * Add ssh certificate support * Add ssh certificate support to builtin ssh * Write trusted-user-ca-keys.pem based on configuration * Update app.example.ini * Update templates/user/settings/keys_principal.tmpl Co-authored-by: silverwind <me@silverwind.io> * Remove unused locale string * Update options/locale/locale_en-US.ini Co-authored-by: silverwind <me@silverwind.io> * Update options/locale/locale_en-US.ini Co-authored-by: silverwind <me@silverwind.io> * Update models/ssh_key.go Co-authored-by: silverwind <me@silverwind.io> * Add missing creation of SSH.Rootpath * Update cheatsheet, example and locale strings * Update models/ssh_key.go Co-authored-by: zeripath <art27@cantab.net> * Update models/ssh_key.go Co-authored-by: zeripath <art27@cantab.net> * Update models/ssh_key.go Co-authored-by: zeripath <art27@cantab.net> * Update models/ssh_key.go Co-authored-by: zeripath <art27@cantab.net> * Update models/ssh_key.go * Optimizations based on feedback * Validate CA keys for external sshd * Add filename option and change default filename Add a SSH_TRUSTED_USER_CA_KEYS_FILENAME option which default is RUN_USER/.ssh/gitea-trusted-user-ca-keys.pem Do not write a file when SSH_TRUSTED_USER_CA_KEYS is empty. Add some more documentation. * Remove unneeded principalkey functions * Add blank line * Apply suggestions from code review Co-authored-by: zeripath <art27@cantab.net> * Add SSH_AUTHORIZED_PRINCIPALS_ALLOW option This adds a SSH_AUTHORIZED_PRINCIPALS_ALLOW which is default email,username this means that users only can add the principals that match their email or username. To allow anything the admin need to set the option anything. This allows for a safe default in gitea which protects against malicious users using other user's prinicipals. (before that user could set it). This commit also has some small other fixes from the last code review. * Rewrite principal keys file on user deletion * Use correct rewrite method * Set correct AuthorizedPrincipalsBackup default setting * Rewrite principalsfile when adding principals * Add update authorized_principals option to admin dashboard * Handle non-primary emails Signed-off-by: Andrew Thornton <art27@cantab.net> * Add the command actually to the dashboard template * Update models/ssh_key.go Co-authored-by: silverwind <me@silverwind.io> * By default do not show principal options unless there are CA keys set or they are explicitly set Signed-off-by: Andrew Thornton <art27@cantab.net> * allow settings when enabled * Fix typos in TrustedUserCAKeys path * Allow every CASignatureAlgorithms algorithm As this depends on the content of TrustedUserCAKeys we should allow all signature algorithms as admins can choose the specific algorithm on their signing CA * Update models/ssh_key.go Co-authored-by: Lauris BH <lauris@nix.lv> * Fix linting issue Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 years ago
9 years ago
11 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)
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)
8 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 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
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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)
8 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 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>
5 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>
5 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>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
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
6 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
6 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
6 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
6 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
6 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
6 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
6 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
6 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  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/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. _ "image/jpeg" // Needed for jpeg support
  15. "os"
  16. "path/filepath"
  17. "regexp"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/public"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/storage"
  28. "code.gitea.io/gitea/modules/structs"
  29. "code.gitea.io/gitea/modules/timeutil"
  30. "code.gitea.io/gitea/modules/util"
  31. "github.com/unknwon/com"
  32. "golang.org/x/crypto/argon2"
  33. "golang.org/x/crypto/bcrypt"
  34. "golang.org/x/crypto/pbkdf2"
  35. "golang.org/x/crypto/scrypt"
  36. "golang.org/x/crypto/ssh"
  37. "xorm.io/builder"
  38. "xorm.io/xorm"
  39. )
  40. // UserType defines the user type
  41. type UserType int
  42. const (
  43. // UserTypeIndividual defines an individual user
  44. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  45. // UserTypeOrganization defines an organization
  46. UserTypeOrganization
  47. )
  48. const (
  49. algoBcrypt = "bcrypt"
  50. algoScrypt = "scrypt"
  51. algoArgon2 = "argon2"
  52. algoPbkdf2 = "pbkdf2"
  53. // EmailNotificationsEnabled indicates that the user would like to receive all email notifications
  54. EmailNotificationsEnabled = "enabled"
  55. // EmailNotificationsOnMention indicates that the user would like to be notified via email when mentioned.
  56. EmailNotificationsOnMention = "onmention"
  57. // EmailNotificationsDisabled indicates that the user would not like to be notified via email.
  58. EmailNotificationsDisabled = "disabled"
  59. )
  60. var (
  61. // ErrUserNotKeyOwner user does not own this key error
  62. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  63. // ErrEmailNotExist e-mail does not exist error
  64. ErrEmailNotExist = errors.New("E-mail does not exist")
  65. // ErrEmailNotActivated e-mail address has not been activated error
  66. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  67. // ErrUserNameIllegal user name contains illegal characters error
  68. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  69. // ErrLoginSourceNotActived login source is not actived error
  70. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  71. // ErrUnsupportedLoginType login source is unknown error
  72. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  73. // Characters prohibited in a user name (anything except A-Za-z0-9_.-)
  74. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  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 'argon2'"`
  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. KeepActivityPrivate bool `xorm:"NOT NULL DEFAULT false"`
  140. }
  141. // SearchOrganizationsOptions options to filter organizations
  142. type SearchOrganizationsOptions struct {
  143. ListOptions
  144. All bool
  145. }
  146. // ColorFormat writes a colored string to identify this struct
  147. func (u *User) ColorFormat(s fmt.State) {
  148. log.ColorFprintf(s, "%d:%s",
  149. log.NewColoredIDValue(u.ID),
  150. log.NewColoredValue(u.Name))
  151. }
  152. // BeforeUpdate is invoked from XORM before updating this object.
  153. func (u *User) BeforeUpdate() {
  154. if u.MaxRepoCreation < -1 {
  155. u.MaxRepoCreation = -1
  156. }
  157. // Organization does not need email
  158. u.Email = strings.ToLower(u.Email)
  159. if !u.IsOrganization() {
  160. if len(u.AvatarEmail) == 0 {
  161. u.AvatarEmail = u.Email
  162. }
  163. }
  164. u.LowerName = strings.ToLower(u.Name)
  165. u.Location = base.TruncateString(u.Location, 255)
  166. u.Website = base.TruncateString(u.Website, 255)
  167. u.Description = base.TruncateString(u.Description, 255)
  168. }
  169. // AfterLoad is invoked from XORM after filling all the fields of this object.
  170. func (u *User) AfterLoad() {
  171. if u.Theme == "" {
  172. u.Theme = setting.UI.DefaultTheme
  173. }
  174. }
  175. // SetLastLogin set time to last login
  176. func (u *User) SetLastLogin() {
  177. u.LastLoginUnix = timeutil.TimeStampNow()
  178. }
  179. // UpdateDiffViewStyle updates the users diff view style
  180. func (u *User) UpdateDiffViewStyle(style string) error {
  181. u.DiffViewStyle = style
  182. return UpdateUserCols(u, "diff_view_style")
  183. }
  184. // UpdateTheme updates a users' theme irrespective of the site wide theme
  185. func (u *User) UpdateTheme(themeName string) error {
  186. u.Theme = themeName
  187. return UpdateUserCols(u, "theme")
  188. }
  189. // GetEmail returns an noreply email, if the user has set to keep his
  190. // email address private, otherwise the primary email address.
  191. func (u *User) GetEmail() string {
  192. if u.KeepEmailPrivate {
  193. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  194. }
  195. return u.Email
  196. }
  197. // GetAllUsers returns a slice of all users found in DB.
  198. func GetAllUsers() ([]*User, error) {
  199. users := make([]*User, 0)
  200. return users, x.OrderBy("id").Find(&users)
  201. }
  202. // IsLocal returns true if user login type is LoginPlain.
  203. func (u *User) IsLocal() bool {
  204. return u.LoginType <= LoginPlain
  205. }
  206. // IsOAuth2 returns true if user login type is LoginOAuth2.
  207. func (u *User) IsOAuth2() bool {
  208. return u.LoginType == LoginOAuth2
  209. }
  210. // HasForkedRepo checks if user has already forked a repository with given ID.
  211. func (u *User) HasForkedRepo(repoID int64) bool {
  212. _, has := HasForkedRepo(u.ID, repoID)
  213. return has
  214. }
  215. // MaxCreationLimit returns the number of repositories a user is allowed to create
  216. func (u *User) MaxCreationLimit() int {
  217. if u.MaxRepoCreation <= -1 {
  218. return setting.Repository.MaxCreationLimit
  219. }
  220. return u.MaxRepoCreation
  221. }
  222. // CanCreateRepo returns if user login can create a repository
  223. // NOTE: functions calling this assume a failure due to repository count limit; if new checks are added, those functions should be revised
  224. func (u *User) CanCreateRepo() bool {
  225. if u.IsAdmin {
  226. return true
  227. }
  228. if u.MaxRepoCreation <= -1 {
  229. if setting.Repository.MaxCreationLimit <= -1 {
  230. return true
  231. }
  232. return u.NumRepos < setting.Repository.MaxCreationLimit
  233. }
  234. return u.NumRepos < u.MaxRepoCreation
  235. }
  236. // CanCreateOrganization returns true if user can create organisation.
  237. func (u *User) CanCreateOrganization() bool {
  238. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  239. }
  240. // CanEditGitHook returns true if user can edit Git hooks.
  241. func (u *User) CanEditGitHook() bool {
  242. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  243. }
  244. // CanImportLocal returns true if user can migrate repository by local path.
  245. func (u *User) CanImportLocal() bool {
  246. if !setting.ImportLocalPaths {
  247. return false
  248. }
  249. return u.IsAdmin || u.AllowImportLocal
  250. }
  251. // DashboardLink returns the user dashboard page link.
  252. func (u *User) DashboardLink() string {
  253. if u.IsOrganization() {
  254. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  255. }
  256. return setting.AppSubURL + "/"
  257. }
  258. // HomeLink returns the user or organization home page link.
  259. func (u *User) HomeLink() string {
  260. return setting.AppSubURL + "/" + u.Name
  261. }
  262. // HTMLURL returns the user or organization's full link.
  263. func (u *User) HTMLURL() string {
  264. return setting.AppURL + u.Name
  265. }
  266. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  267. func (u *User) GenerateEmailActivateCode(email string) string {
  268. code := base.CreateTimeLimitCode(
  269. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  270. setting.Service.ActiveCodeLives, nil)
  271. // Add tail hex username
  272. code += hex.EncodeToString([]byte(u.LowerName))
  273. return code
  274. }
  275. // GenerateActivateCode generates an activate code based on user information.
  276. func (u *User) GenerateActivateCode() string {
  277. return u.GenerateEmailActivateCode(u.Email)
  278. }
  279. // GetFollowers returns range of user's followers.
  280. func (u *User) GetFollowers(listOptions ListOptions) ([]*User, error) {
  281. sess := x.
  282. Where("follow.follow_id=?", u.ID).
  283. Join("LEFT", "follow", "`user`.id=follow.user_id")
  284. if listOptions.Page != 0 {
  285. sess = listOptions.setSessionPagination(sess)
  286. users := make([]*User, 0, listOptions.PageSize)
  287. return users, sess.Find(&users)
  288. }
  289. users := make([]*User, 0, 8)
  290. return users, sess.Find(&users)
  291. }
  292. // IsFollowing returns true if user is following followID.
  293. func (u *User) IsFollowing(followID int64) bool {
  294. return IsFollowing(u.ID, followID)
  295. }
  296. // GetFollowing returns range of user's following.
  297. func (u *User) GetFollowing(listOptions ListOptions) ([]*User, error) {
  298. sess := x.
  299. Where("follow.user_id=?", u.ID).
  300. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  301. if listOptions.Page != 0 {
  302. sess = listOptions.setSessionPagination(sess)
  303. users := make([]*User, 0, listOptions.PageSize)
  304. return users, sess.Find(&users)
  305. }
  306. users := make([]*User, 0, 8)
  307. return users, sess.Find(&users)
  308. }
  309. // NewGitSig generates and returns the signature of given user.
  310. func (u *User) NewGitSig() *git.Signature {
  311. return &git.Signature{
  312. Name: u.GitName(),
  313. Email: u.GetEmail(),
  314. When: time.Now(),
  315. }
  316. }
  317. func hashPassword(passwd, salt, algo string) string {
  318. var tempPasswd []byte
  319. switch algo {
  320. case algoBcrypt:
  321. tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
  322. return string(tempPasswd)
  323. case algoScrypt:
  324. tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
  325. case algoArgon2:
  326. tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
  327. case algoPbkdf2:
  328. fallthrough
  329. default:
  330. tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  331. }
  332. return fmt.Sprintf("%x", tempPasswd)
  333. }
  334. // HashPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO.
  335. func (u *User) HashPassword(passwd string) {
  336. u.PasswdHashAlgo = setting.PasswordHashAlgo
  337. u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
  338. }
  339. // ValidatePassword checks if given password matches the one belongs to the user.
  340. func (u *User) ValidatePassword(passwd string) bool {
  341. tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
  342. if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
  343. return true
  344. }
  345. if u.PasswdHashAlgo == algoBcrypt && bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(passwd)) == nil {
  346. return true
  347. }
  348. return false
  349. }
  350. // IsPasswordSet checks if the password is set or left empty
  351. func (u *User) IsPasswordSet() bool {
  352. return !u.ValidatePassword("")
  353. }
  354. // IsOrganization returns true if user is actually a organization.
  355. func (u *User) IsOrganization() bool {
  356. return u.Type == UserTypeOrganization
  357. }
  358. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  359. func (u *User) IsUserOrgOwner(orgID int64) bool {
  360. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  361. if err != nil {
  362. log.Error("IsOrganizationOwner: %v", err)
  363. return false
  364. }
  365. return isOwner
  366. }
  367. // HasMemberWithUserID returns true if user with userID is part of the u organisation.
  368. func (u *User) HasMemberWithUserID(userID int64) bool {
  369. return u.hasMemberWithUserID(x, userID)
  370. }
  371. func (u *User) hasMemberWithUserID(e Engine, userID int64) bool {
  372. isMember, err := isOrganizationMember(e, u.ID, userID)
  373. if err != nil {
  374. log.Error("IsOrganizationMember: %v", err)
  375. return false
  376. }
  377. return isMember
  378. }
  379. // IsPublicMember returns true if user public his/her membership in given organization.
  380. func (u *User) IsPublicMember(orgID int64) bool {
  381. isMember, err := IsPublicMembership(orgID, u.ID)
  382. if err != nil {
  383. log.Error("IsPublicMembership: %v", err)
  384. return false
  385. }
  386. return isMember
  387. }
  388. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  389. return e.
  390. Where("uid=?", u.ID).
  391. Count(new(OrgUser))
  392. }
  393. // GetOrganizationCount returns count of membership of organization of user.
  394. func (u *User) GetOrganizationCount() (int64, error) {
  395. return u.getOrganizationCount(x)
  396. }
  397. // GetRepositories returns repositories that user owns, including private repositories.
  398. func (u *User) GetRepositories(listOpts ListOptions, names ...string) (err error) {
  399. u.Repos, _, err = GetUserRepositories(&SearchRepoOptions{Actor: u, Private: true, ListOptions: listOpts, LowerNames: names})
  400. return err
  401. }
  402. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  403. // Caller shall check that units is not globally disabled
  404. func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
  405. var ids []int64
  406. sess := x.Table("repository").Cols("repository.id")
  407. if len(units) > 0 {
  408. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  409. sess = sess.In("repo_unit.type", units)
  410. }
  411. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  412. }
  413. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  414. // Caller shall check that units is not globally disabled
  415. func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
  416. var ids []int64
  417. if err := x.Table("repository").
  418. Cols("repository.id").
  419. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  420. 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).
  421. Where("team_user.uid = ?", u.ID).
  422. GroupBy("repository.id").Find(&ids); err != nil {
  423. return nil, err
  424. }
  425. if len(units) > 0 {
  426. return FilterOutRepoIdsWithoutUnitAccess(u, ids, units...)
  427. }
  428. return ids, nil
  429. }
  430. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  431. // Caller shall check that units is not globally disabled
  432. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  433. ids, err := u.GetRepositoryIDs(units...)
  434. if err != nil {
  435. return nil, err
  436. }
  437. ids2, err := u.GetOrgRepositoryIDs(units...)
  438. if err != nil {
  439. return nil, err
  440. }
  441. return append(ids, ids2...), nil
  442. }
  443. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  444. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  445. return GetUserMirrorRepositories(u.ID)
  446. }
  447. // GetOwnedOrganizations returns all organizations that user owns.
  448. func (u *User) GetOwnedOrganizations() (err error) {
  449. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  450. return err
  451. }
  452. // GetOrganizations returns paginated organizations that user belongs to.
  453. func (u *User) GetOrganizations(opts *SearchOrganizationsOptions) error {
  454. sess := x.NewSession()
  455. defer sess.Close()
  456. schema, err := x.TableInfo(new(User))
  457. if err != nil {
  458. return err
  459. }
  460. groupByCols := &strings.Builder{}
  461. for _, col := range schema.Columns() {
  462. fmt.Fprintf(groupByCols, "`%s`.%s,", schema.Name, col.Name)
  463. }
  464. groupByStr := groupByCols.String()
  465. groupByStr = groupByStr[0 : len(groupByStr)-1]
  466. sess.Select("`user`.*, count(repo_id) as org_count").
  467. Table("user").
  468. Join("INNER", "org_user", "`org_user`.org_id=`user`.id").
  469. Join("LEFT", builder.
  470. Select("id as repo_id, owner_id as repo_owner_id").
  471. From("repository").
  472. Where(accessibleRepositoryCondition(u)), "`repository`.repo_owner_id = `org_user`.org_id").
  473. And("`org_user`.uid=?", u.ID).
  474. GroupBy(groupByStr)
  475. if opts.PageSize != 0 {
  476. sess = opts.setSessionPagination(sess)
  477. }
  478. type OrgCount struct {
  479. User `xorm:"extends"`
  480. OrgCount int
  481. }
  482. orgCounts := make([]*OrgCount, 0, 10)
  483. if err := sess.
  484. Asc("`user`.name").
  485. Find(&orgCounts); err != nil {
  486. return err
  487. }
  488. orgs := make([]*User, len(orgCounts))
  489. for i, orgCount := range orgCounts {
  490. orgCount.User.NumRepos = orgCount.OrgCount
  491. orgs[i] = &orgCount.User
  492. }
  493. u.Orgs = orgs
  494. return nil
  495. }
  496. // DisplayName returns full name if it's not empty,
  497. // returns username otherwise.
  498. func (u *User) DisplayName() string {
  499. trimmed := strings.TrimSpace(u.FullName)
  500. if len(trimmed) > 0 {
  501. return trimmed
  502. }
  503. return u.Name
  504. }
  505. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  506. // returns username otherwise.
  507. func (u *User) GetDisplayName() string {
  508. if setting.UI.DefaultShowFullName {
  509. trimmed := strings.TrimSpace(u.FullName)
  510. if len(trimmed) > 0 {
  511. return trimmed
  512. }
  513. }
  514. return u.Name
  515. }
  516. func gitSafeName(name string) string {
  517. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  518. }
  519. // GitName returns a git safe name
  520. func (u *User) GitName() string {
  521. gitName := gitSafeName(u.FullName)
  522. if len(gitName) > 0 {
  523. return gitName
  524. }
  525. // Although u.Name should be safe if created in our system
  526. // LDAP users may have bad names
  527. gitName = gitSafeName(u.Name)
  528. if len(gitName) > 0 {
  529. return gitName
  530. }
  531. // Totally pathological name so it's got to be:
  532. return fmt.Sprintf("user-%d", u.ID)
  533. }
  534. // ShortName ellipses username to length
  535. func (u *User) ShortName(length int) string {
  536. return base.EllipsisString(u.Name, length)
  537. }
  538. // IsMailable checks if a user is eligible
  539. // to receive emails.
  540. func (u *User) IsMailable() bool {
  541. return u.IsActive
  542. }
  543. // EmailNotifications returns the User's email notification preference
  544. func (u *User) EmailNotifications() string {
  545. return u.EmailNotificationsPreference
  546. }
  547. // SetEmailNotifications sets the user's email notification preference
  548. func (u *User) SetEmailNotifications(set string) error {
  549. u.EmailNotificationsPreference = set
  550. if err := UpdateUserCols(u, "email_notifications_preference"); err != nil {
  551. log.Error("SetEmailNotifications: %v", err)
  552. return err
  553. }
  554. return nil
  555. }
  556. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  557. if len(name) == 0 {
  558. return false, nil
  559. }
  560. return e.
  561. Where("id!=?", uid).
  562. Get(&User{LowerName: strings.ToLower(name)})
  563. }
  564. // IsUserExist checks if given user name exist,
  565. // the user name should be noncased unique.
  566. // If uid is presented, then check will rule out that one,
  567. // it is used when update a user name in settings page.
  568. func IsUserExist(uid int64, name string) (bool, error) {
  569. return isUserExist(x, uid, name)
  570. }
  571. // GetUserSalt returns a random user salt token.
  572. func GetUserSalt() (string, error) {
  573. return generate.GetRandomString(10)
  574. }
  575. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  576. func NewGhostUser() *User {
  577. return &User{
  578. ID: -1,
  579. Name: "Ghost",
  580. LowerName: "ghost",
  581. }
  582. }
  583. // NewReplaceUser creates and returns a fake user for external user
  584. func NewReplaceUser(name string) *User {
  585. return &User{
  586. ID: -1,
  587. Name: name,
  588. LowerName: strings.ToLower(name),
  589. }
  590. }
  591. // IsGhost check if user is fake user for a deleted account
  592. func (u *User) IsGhost() bool {
  593. if u == nil {
  594. return false
  595. }
  596. return u.ID == -1 && u.Name == "Ghost"
  597. }
  598. var (
  599. reservedUsernames = append([]string{
  600. ".",
  601. "..",
  602. ".well-known",
  603. "admin",
  604. "api",
  605. "assets",
  606. "attachments",
  607. "avatars",
  608. "commits",
  609. "debug",
  610. "error",
  611. "explore",
  612. "ghost",
  613. "help",
  614. "install",
  615. "issues",
  616. "less",
  617. "login",
  618. "manifest.json",
  619. "metrics",
  620. "milestones",
  621. "new",
  622. "notifications",
  623. "org",
  624. "plugins",
  625. "pulls",
  626. "raw",
  627. "repo",
  628. "robots.txt",
  629. "search",
  630. "stars",
  631. "template",
  632. "user",
  633. }, public.KnownPublicEntries...)
  634. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  635. )
  636. // isUsableName checks if name is reserved or pattern of name is not allowed
  637. // based on given reserved names and patterns.
  638. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  639. func isUsableName(names, patterns []string, name string) error {
  640. name = strings.TrimSpace(strings.ToLower(name))
  641. if utf8.RuneCountInString(name) == 0 {
  642. return ErrNameEmpty
  643. }
  644. for i := range names {
  645. if name == names[i] {
  646. return ErrNameReserved{name}
  647. }
  648. }
  649. for _, pat := range patterns {
  650. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  651. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  652. return ErrNamePatternNotAllowed{pat}
  653. }
  654. }
  655. return nil
  656. }
  657. // IsUsableUsername returns an error when a username is reserved
  658. func IsUsableUsername(name string) error {
  659. // Validate username make sure it satisfies requirement.
  660. if alphaDashDotPattern.MatchString(name) {
  661. // Note: usually this error is normally caught up earlier in the UI
  662. return ErrNameCharsNotAllowed{Name: name}
  663. }
  664. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  665. }
  666. // CreateUser creates record of a new user.
  667. func CreateUser(u *User) (err error) {
  668. if err = IsUsableUsername(u.Name); err != nil {
  669. return err
  670. }
  671. sess := x.NewSession()
  672. defer sess.Close()
  673. if err = sess.Begin(); err != nil {
  674. return err
  675. }
  676. isExist, err := isUserExist(sess, 0, u.Name)
  677. if err != nil {
  678. return err
  679. } else if isExist {
  680. return ErrUserAlreadyExist{u.Name}
  681. }
  682. u.Email = strings.ToLower(u.Email)
  683. isExist, err = sess.
  684. Where("email=?", u.Email).
  685. Get(new(User))
  686. if err != nil {
  687. return err
  688. } else if isExist {
  689. return ErrEmailAlreadyUsed{u.Email}
  690. }
  691. if err = ValidateEmail(u.Email); err != nil {
  692. return err
  693. }
  694. isExist, err = isEmailUsed(sess, u.Email)
  695. if err != nil {
  696. return err
  697. } else if isExist {
  698. return ErrEmailAlreadyUsed{u.Email}
  699. }
  700. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  701. u.LowerName = strings.ToLower(u.Name)
  702. u.AvatarEmail = u.Email
  703. if u.Rands, err = GetUserSalt(); err != nil {
  704. return err
  705. }
  706. if u.Salt, err = GetUserSalt(); err != nil {
  707. return err
  708. }
  709. u.HashPassword(u.Passwd)
  710. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  711. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  712. u.MaxRepoCreation = -1
  713. u.Theme = setting.UI.DefaultTheme
  714. if _, err = sess.Insert(u); err != nil {
  715. return err
  716. }
  717. return sess.Commit()
  718. }
  719. func countUsers(e Engine) int64 {
  720. count, _ := e.
  721. Where("type=0").
  722. Count(new(User))
  723. return count
  724. }
  725. // CountUsers returns number of users.
  726. func CountUsers() int64 {
  727. return countUsers(x)
  728. }
  729. // get user by verify code
  730. func getVerifyUser(code string) (user *User) {
  731. if len(code) <= base.TimeLimitCodeLength {
  732. return nil
  733. }
  734. // use tail hex username query user
  735. hexStr := code[base.TimeLimitCodeLength:]
  736. if b, err := hex.DecodeString(hexStr); err == nil {
  737. if user, err = GetUserByName(string(b)); user != nil {
  738. return user
  739. }
  740. log.Error("user.getVerifyUser: %v", err)
  741. }
  742. return nil
  743. }
  744. // VerifyUserActiveCode verifies active code when active account
  745. func VerifyUserActiveCode(code string) (user *User) {
  746. minutes := setting.Service.ActiveCodeLives
  747. if user = getVerifyUser(code); user != nil {
  748. // time limit code
  749. prefix := code[:base.TimeLimitCodeLength]
  750. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  751. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  752. return user
  753. }
  754. }
  755. return nil
  756. }
  757. // VerifyActiveEmailCode verifies active email code when active account
  758. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  759. minutes := setting.Service.ActiveCodeLives
  760. if user := getVerifyUser(code); user != nil {
  761. // time limit code
  762. prefix := code[:base.TimeLimitCodeLength]
  763. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  764. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  765. emailAddress := &EmailAddress{UID: user.ID, Email: email}
  766. if has, _ := x.Get(emailAddress); has {
  767. return emailAddress
  768. }
  769. }
  770. }
  771. return nil
  772. }
  773. // ChangeUserName changes all corresponding setting from old user name to new one.
  774. func ChangeUserName(u *User, newUserName string) (err error) {
  775. if err = IsUsableUsername(newUserName); err != nil {
  776. return err
  777. }
  778. isExist, err := IsUserExist(0, newUserName)
  779. if err != nil {
  780. return err
  781. } else if isExist {
  782. return ErrUserAlreadyExist{newUserName}
  783. }
  784. sess := x.NewSession()
  785. defer sess.Close()
  786. if err = sess.Begin(); err != nil {
  787. return err
  788. }
  789. if _, err = sess.Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, u.Name); err != nil {
  790. return fmt.Errorf("Change repo owner name: %v", err)
  791. }
  792. // Do not fail if directory does not exist
  793. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  794. return fmt.Errorf("Rename user directory: %v", err)
  795. }
  796. return sess.Commit()
  797. }
  798. // checkDupEmail checks whether there are the same email with the user
  799. func checkDupEmail(e Engine, u *User) error {
  800. u.Email = strings.ToLower(u.Email)
  801. has, err := e.
  802. Where("id!=?", u.ID).
  803. And("type=?", u.Type).
  804. And("email=?", u.Email).
  805. Get(new(User))
  806. if err != nil {
  807. return err
  808. } else if has {
  809. return ErrEmailAlreadyUsed{u.Email}
  810. }
  811. return nil
  812. }
  813. func updateUser(e Engine, u *User) (err error) {
  814. u.Email = strings.ToLower(u.Email)
  815. if err = ValidateEmail(u.Email); err != nil {
  816. return err
  817. }
  818. _, err = e.ID(u.ID).AllCols().Update(u)
  819. return err
  820. }
  821. // UpdateUser updates user's information.
  822. func UpdateUser(u *User) error {
  823. return updateUser(x, u)
  824. }
  825. // UpdateUserCols update user according special columns
  826. func UpdateUserCols(u *User, cols ...string) error {
  827. return updateUserCols(x, u, cols...)
  828. }
  829. func updateUserCols(e Engine, u *User, cols ...string) error {
  830. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  831. return err
  832. }
  833. // UpdateUserSetting updates user's settings.
  834. func UpdateUserSetting(u *User) (err error) {
  835. sess := x.NewSession()
  836. defer sess.Close()
  837. if err = sess.Begin(); err != nil {
  838. return err
  839. }
  840. if !u.IsOrganization() {
  841. if err = checkDupEmail(sess, u); err != nil {
  842. return err
  843. }
  844. }
  845. if err = updateUser(sess, u); err != nil {
  846. return err
  847. }
  848. return sess.Commit()
  849. }
  850. // deleteBeans deletes all given beans, beans should contain delete conditions.
  851. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  852. for i := range beans {
  853. if _, err = e.Delete(beans[i]); err != nil {
  854. return err
  855. }
  856. }
  857. return nil
  858. }
  859. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  860. func deleteUser(e *xorm.Session, u *User) error {
  861. // Note: A user owns any repository or belongs to any organization
  862. // cannot perform delete operation.
  863. // Check ownership of repository.
  864. count, err := getRepositoryCount(e, u)
  865. if err != nil {
  866. return fmt.Errorf("GetRepositoryCount: %v", err)
  867. } else if count > 0 {
  868. return ErrUserOwnRepos{UID: u.ID}
  869. }
  870. // Check membership of organization.
  871. count, err = u.getOrganizationCount(e)
  872. if err != nil {
  873. return fmt.Errorf("GetOrganizationCount: %v", err)
  874. } else if count > 0 {
  875. return ErrUserHasOrgs{UID: u.ID}
  876. }
  877. // ***** START: Watch *****
  878. watchedRepoIDs := make([]int64, 0, 10)
  879. if err = e.Table("watch").Cols("watch.repo_id").
  880. Where("watch.user_id = ?", u.ID).And("watch.mode <>?", RepoWatchModeDont).Find(&watchedRepoIDs); err != nil {
  881. return fmt.Errorf("get all watches: %v", err)
  882. }
  883. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  884. return fmt.Errorf("decrease repository num_watches: %v", err)
  885. }
  886. // ***** END: Watch *****
  887. // ***** START: Star *****
  888. starredRepoIDs := make([]int64, 0, 10)
  889. if err = e.Table("star").Cols("star.repo_id").
  890. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  891. return fmt.Errorf("get all stars: %v", err)
  892. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  893. return fmt.Errorf("decrease repository num_stars: %v", err)
  894. }
  895. // ***** END: Star *****
  896. // ***** START: Follow *****
  897. followeeIDs := make([]int64, 0, 10)
  898. if err = e.Table("follow").Cols("follow.follow_id").
  899. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  900. return fmt.Errorf("get all followees: %v", err)
  901. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  902. return fmt.Errorf("decrease user num_followers: %v", err)
  903. }
  904. followerIDs := make([]int64, 0, 10)
  905. if err = e.Table("follow").Cols("follow.user_id").
  906. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  907. return fmt.Errorf("get all followers: %v", err)
  908. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  909. return fmt.Errorf("decrease user num_following: %v", err)
  910. }
  911. // ***** END: Follow *****
  912. if err = deleteBeans(e,
  913. &AccessToken{UID: u.ID},
  914. &Collaboration{UserID: u.ID},
  915. &Access{UserID: u.ID},
  916. &Watch{UserID: u.ID},
  917. &Star{UID: u.ID},
  918. &Follow{UserID: u.ID},
  919. &Follow{FollowID: u.ID},
  920. &Action{UserID: u.ID},
  921. &IssueUser{UID: u.ID},
  922. &EmailAddress{UID: u.ID},
  923. &UserOpenID{UID: u.ID},
  924. &Reaction{UserID: u.ID},
  925. &TeamUser{UID: u.ID},
  926. &Collaboration{UserID: u.ID},
  927. &Stopwatch{UserID: u.ID},
  928. ); err != nil {
  929. return fmt.Errorf("deleteBeans: %v", err)
  930. }
  931. // ***** START: PublicKey *****
  932. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  933. return fmt.Errorf("deletePublicKeys: %v", err)
  934. }
  935. err = rewriteAllPublicKeys(e)
  936. if err != nil {
  937. return err
  938. }
  939. err = rewriteAllPrincipalKeys(e)
  940. if err != nil {
  941. return err
  942. }
  943. // ***** END: PublicKey *****
  944. // ***** START: GPGPublicKey *****
  945. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  946. return fmt.Errorf("deleteGPGKeys: %v", err)
  947. }
  948. // ***** END: GPGPublicKey *****
  949. // Clear assignee.
  950. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  951. return fmt.Errorf("clear assignee: %v", err)
  952. }
  953. // ***** START: ExternalLoginUser *****
  954. if err = removeAllAccountLinks(e, u); err != nil {
  955. return fmt.Errorf("ExternalLoginUser: %v", err)
  956. }
  957. // ***** END: ExternalLoginUser *****
  958. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  959. return fmt.Errorf("Delete: %v", err)
  960. }
  961. // FIXME: system notice
  962. // Note: There are something just cannot be roll back,
  963. // so just keep error logs of those operations.
  964. path := UserPath(u.Name)
  965. if err := util.RemoveAll(path); err != nil {
  966. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  967. }
  968. if len(u.Avatar) > 0 {
  969. avatarPath := u.CustomAvatarRelativePath()
  970. if err := storage.Avatars.Delete(avatarPath); err != nil {
  971. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  972. }
  973. }
  974. return nil
  975. }
  976. // DeleteUser completely and permanently deletes everything of a user,
  977. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  978. func DeleteUser(u *User) (err error) {
  979. if u.IsOrganization() {
  980. return fmt.Errorf("%s is an organization not a user", u.Name)
  981. }
  982. sess := x.NewSession()
  983. defer sess.Close()
  984. if err = sess.Begin(); err != nil {
  985. return err
  986. }
  987. if err = deleteUser(sess, u); err != nil {
  988. // Note: don't wrapper error here.
  989. return err
  990. }
  991. return sess.Commit()
  992. }
  993. // DeleteInactiveUsers deletes all inactive users and email addresses.
  994. func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err error) {
  995. users := make([]*User, 0, 10)
  996. if olderThan > 0 {
  997. if err = x.
  998. Where("is_active = ? and created_unix < ?", false, time.Now().Add(-olderThan).Unix()).
  999. Find(&users); err != nil {
  1000. return fmt.Errorf("get all inactive users: %v", err)
  1001. }
  1002. } else {
  1003. if err = x.
  1004. Where("is_active = ?", false).
  1005. Find(&users); err != nil {
  1006. return fmt.Errorf("get all inactive users: %v", err)
  1007. }
  1008. }
  1009. // FIXME: should only update authorized_keys file once after all deletions.
  1010. for _, u := range users {
  1011. select {
  1012. case <-ctx.Done():
  1013. return ErrCancelledf("Before delete inactive user %s", u.Name)
  1014. default:
  1015. }
  1016. if err = DeleteUser(u); err != nil {
  1017. // Ignore users that were set inactive by admin.
  1018. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1019. continue
  1020. }
  1021. return err
  1022. }
  1023. }
  1024. _, err = x.
  1025. Where("is_activated = ?", false).
  1026. Delete(new(EmailAddress))
  1027. return err
  1028. }
  1029. // UserPath returns the path absolute path of user repositories.
  1030. func UserPath(userName string) string {
  1031. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1032. }
  1033. func getUserByID(e Engine, id int64) (*User, error) {
  1034. u := new(User)
  1035. has, err := e.ID(id).Get(u)
  1036. if err != nil {
  1037. return nil, err
  1038. } else if !has {
  1039. return nil, ErrUserNotExist{id, "", 0}
  1040. }
  1041. return u, nil
  1042. }
  1043. // GetUserByID returns the user object by given ID if exists.
  1044. func GetUserByID(id int64) (*User, error) {
  1045. return getUserByID(x, id)
  1046. }
  1047. // GetUserByName returns user by given name.
  1048. func GetUserByName(name string) (*User, error) {
  1049. return getUserByName(x, name)
  1050. }
  1051. func getUserByName(e Engine, name string) (*User, error) {
  1052. if len(name) == 0 {
  1053. return nil, ErrUserNotExist{0, name, 0}
  1054. }
  1055. u := &User{LowerName: strings.ToLower(name)}
  1056. has, err := e.Get(u)
  1057. if err != nil {
  1058. return nil, err
  1059. } else if !has {
  1060. return nil, ErrUserNotExist{0, name, 0}
  1061. }
  1062. return u, nil
  1063. }
  1064. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1065. // that have their email notifications set to enabled or onmention.
  1066. func GetUserEmailsByNames(names []string) []string {
  1067. return getUserEmailsByNames(x, names)
  1068. }
  1069. func getUserEmailsByNames(e Engine, names []string) []string {
  1070. mails := make([]string, 0, len(names))
  1071. for _, name := range names {
  1072. u, err := getUserByName(e, name)
  1073. if err != nil {
  1074. continue
  1075. }
  1076. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1077. mails = append(mails, u.Email)
  1078. }
  1079. }
  1080. return mails
  1081. }
  1082. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  1083. func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
  1084. if len(ids) == 0 {
  1085. return nil, nil
  1086. }
  1087. ous := make([]*User, 0, len(ids))
  1088. if isMention {
  1089. return ous, x.In("id", ids).
  1090. Where("`type` = ?", UserTypeIndividual).
  1091. And("`prohibit_login` = ?", false).
  1092. And("`is_active` = ?", true).
  1093. And("`email_notifications_preference` IN ( ?, ?)", EmailNotificationsEnabled, EmailNotificationsOnMention).
  1094. Find(&ous)
  1095. }
  1096. return ous, x.In("id", ids).
  1097. Where("`type` = ?", UserTypeIndividual).
  1098. And("`prohibit_login` = ?", false).
  1099. And("`is_active` = ?", true).
  1100. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  1101. Find(&ous)
  1102. }
  1103. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  1104. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  1105. unames := make([]string, 0, len(ids))
  1106. err := x.In("id", ids).
  1107. Table("user").
  1108. Asc("name").
  1109. Cols("name").
  1110. Find(&unames)
  1111. return unames, err
  1112. }
  1113. // GetUsersByIDs returns all resolved users from a list of Ids.
  1114. func GetUsersByIDs(ids []int64) (UserList, error) {
  1115. ous := make([]*User, 0, len(ids))
  1116. if len(ids) == 0 {
  1117. return ous, nil
  1118. }
  1119. err := x.In("id", ids).
  1120. Asc("name").
  1121. Find(&ous)
  1122. return ous, err
  1123. }
  1124. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1125. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  1126. ids := make([]int64, 0, len(names))
  1127. for _, name := range names {
  1128. u, err := GetUserByName(name)
  1129. if err != nil {
  1130. if ignoreNonExistent {
  1131. continue
  1132. } else {
  1133. return nil, err
  1134. }
  1135. }
  1136. ids = append(ids, u.ID)
  1137. }
  1138. return ids, nil
  1139. }
  1140. // UserCommit represents a commit with validation of user.
  1141. type UserCommit struct {
  1142. User *User
  1143. *git.Commit
  1144. }
  1145. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1146. func ValidateCommitWithEmail(c *git.Commit) *User {
  1147. if c.Author == nil {
  1148. return nil
  1149. }
  1150. u, err := GetUserByEmail(c.Author.Email)
  1151. if err != nil {
  1152. return nil
  1153. }
  1154. return u
  1155. }
  1156. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1157. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1158. var (
  1159. u *User
  1160. emails = map[string]*User{}
  1161. newCommits = list.New()
  1162. e = oldCommits.Front()
  1163. )
  1164. for e != nil {
  1165. c := e.Value.(*git.Commit)
  1166. if c.Author != nil {
  1167. if v, ok := emails[c.Author.Email]; !ok {
  1168. u, _ = GetUserByEmail(c.Author.Email)
  1169. emails[c.Author.Email] = u
  1170. } else {
  1171. u = v
  1172. }
  1173. } else {
  1174. u = nil
  1175. }
  1176. newCommits.PushBack(UserCommit{
  1177. User: u,
  1178. Commit: c,
  1179. })
  1180. e = e.Next()
  1181. }
  1182. return newCommits
  1183. }
  1184. // GetUserByEmail returns the user object by given e-mail if exists.
  1185. func GetUserByEmail(email string) (*User, error) {
  1186. return GetUserByEmailContext(DefaultDBContext(), email)
  1187. }
  1188. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  1189. func GetUserByEmailContext(ctx DBContext, email string) (*User, error) {
  1190. if len(email) == 0 {
  1191. return nil, ErrUserNotExist{0, email, 0}
  1192. }
  1193. email = strings.ToLower(email)
  1194. // First try to find the user by primary email
  1195. user := &User{Email: email}
  1196. has, err := ctx.e.Get(user)
  1197. if err != nil {
  1198. return nil, err
  1199. }
  1200. if has {
  1201. return user, nil
  1202. }
  1203. // Otherwise, check in alternative list for activated email addresses
  1204. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1205. has, err = ctx.e.Get(emailAddress)
  1206. if err != nil {
  1207. return nil, err
  1208. }
  1209. if has {
  1210. return getUserByID(ctx.e, emailAddress.UID)
  1211. }
  1212. // Finally, if email address is the protected email address:
  1213. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1214. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1215. user := &User{}
  1216. has, err := ctx.e.Where("lower_name=?", username).Get(user)
  1217. if err != nil {
  1218. return nil, err
  1219. }
  1220. if has {
  1221. return user, nil
  1222. }
  1223. }
  1224. return nil, ErrUserNotExist{0, email, 0}
  1225. }
  1226. // GetUser checks if a user already exists
  1227. func GetUser(user *User) (bool, error) {
  1228. return x.Get(user)
  1229. }
  1230. // SearchUserOptions contains the options for searching
  1231. type SearchUserOptions struct {
  1232. ListOptions
  1233. Keyword string
  1234. Type UserType
  1235. UID int64
  1236. OrderBy SearchOrderBy
  1237. Visible []structs.VisibleType
  1238. Actor *User // The user doing the search
  1239. IsActive util.OptionalBool
  1240. SearchByEmail bool // Search by email as well as username/full name
  1241. }
  1242. func (opts *SearchUserOptions) toConds() builder.Cond {
  1243. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1244. if len(opts.Keyword) > 0 {
  1245. lowerKeyword := strings.ToLower(opts.Keyword)
  1246. keywordCond := builder.Or(
  1247. builder.Like{"lower_name", lowerKeyword},
  1248. builder.Like{"LOWER(full_name)", lowerKeyword},
  1249. )
  1250. if opts.SearchByEmail {
  1251. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1252. }
  1253. cond = cond.And(keywordCond)
  1254. }
  1255. if len(opts.Visible) > 0 {
  1256. cond = cond.And(builder.In("visibility", opts.Visible))
  1257. } else {
  1258. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1259. }
  1260. if opts.Actor != nil {
  1261. var exprCond builder.Cond
  1262. if setting.Database.UseMySQL {
  1263. exprCond = builder.Expr("org_user.org_id = user.id")
  1264. } else if setting.Database.UseMSSQL {
  1265. exprCond = builder.Expr("org_user.org_id = [user].id")
  1266. } else {
  1267. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1268. }
  1269. var accessCond = builder.NewCond()
  1270. if !opts.Actor.IsRestricted {
  1271. accessCond = builder.Or(
  1272. 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}))),
  1273. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1274. } else {
  1275. // restricted users only see orgs they are a member of
  1276. accessCond = builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID})))
  1277. }
  1278. cond = cond.And(accessCond)
  1279. }
  1280. if opts.UID > 0 {
  1281. cond = cond.And(builder.Eq{"id": opts.UID})
  1282. }
  1283. if !opts.IsActive.IsNone() {
  1284. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1285. }
  1286. return cond
  1287. }
  1288. // SearchUsers takes options i.e. keyword and part of user name to search,
  1289. // it returns results in given range and number of total results.
  1290. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1291. cond := opts.toConds()
  1292. count, err := x.Where(cond).Count(new(User))
  1293. if err != nil {
  1294. return nil, 0, fmt.Errorf("Count: %v", err)
  1295. }
  1296. if len(opts.OrderBy) == 0 {
  1297. opts.OrderBy = SearchOrderByAlphabetically
  1298. }
  1299. sess := x.Where(cond).OrderBy(opts.OrderBy.String())
  1300. if opts.Page != 0 {
  1301. sess = opts.setSessionPagination(sess)
  1302. }
  1303. users = make([]*User, 0, opts.PageSize)
  1304. return users, count, sess.Find(&users)
  1305. }
  1306. // GetStarredRepos returns the repos starred by a particular user
  1307. func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1308. sess := x.Where("star.uid=?", userID).
  1309. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1310. if !private {
  1311. sess = sess.And("is_private=?", false)
  1312. }
  1313. if listOptions.Page != 0 {
  1314. sess = listOptions.setSessionPagination(sess)
  1315. repos := make([]*Repository, 0, listOptions.PageSize)
  1316. return repos, sess.Find(&repos)
  1317. }
  1318. repos := make([]*Repository, 0, 10)
  1319. return repos, sess.Find(&repos)
  1320. }
  1321. // GetWatchedRepos returns the repos watched by a particular user
  1322. func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1323. sess := x.Where("watch.user_id=?", userID).
  1324. And("`watch`.mode<>?", RepoWatchModeDont).
  1325. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1326. if !private {
  1327. sess = sess.And("is_private=?", false)
  1328. }
  1329. if listOptions.Page != 0 {
  1330. sess = listOptions.setSessionPagination(sess)
  1331. repos := make([]*Repository, 0, listOptions.PageSize)
  1332. return repos, sess.Find(&repos)
  1333. }
  1334. repos := make([]*Repository, 0, 10)
  1335. return repos, sess.Find(&repos)
  1336. }
  1337. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1338. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1339. // Start session
  1340. sess := x.NewSession()
  1341. defer sess.Close()
  1342. if err := sess.Begin(); err != nil {
  1343. return false, err
  1344. }
  1345. // Delete keys marked for deletion
  1346. var sshKeysNeedUpdate bool
  1347. for _, KeyToDelete := range keys {
  1348. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1349. if err != nil {
  1350. log.Error("SearchPublicKeyByContent: %v", err)
  1351. continue
  1352. }
  1353. if err = deletePublicKeys(sess, key.ID); err != nil {
  1354. log.Error("deletePublicKeys: %v", err)
  1355. continue
  1356. }
  1357. sshKeysNeedUpdate = true
  1358. }
  1359. if err := sess.Commit(); err != nil {
  1360. return false, err
  1361. }
  1362. return sshKeysNeedUpdate, nil
  1363. }
  1364. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1365. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1366. var sshKeysNeedUpdate bool
  1367. for _, sshKey := range sshPublicKeys {
  1368. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1369. if err == nil {
  1370. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1371. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1372. if IsErrKeyAlreadyExist(err) {
  1373. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1374. } else {
  1375. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1376. }
  1377. } else {
  1378. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1379. sshKeysNeedUpdate = true
  1380. }
  1381. } else {
  1382. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1383. }
  1384. }
  1385. return sshKeysNeedUpdate
  1386. }
  1387. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1388. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1389. var sshKeysNeedUpdate bool
  1390. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1391. // Get Public Keys from DB with current LDAP source
  1392. var giteaKeys []string
  1393. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1394. if err != nil {
  1395. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1396. }
  1397. for _, v := range keys {
  1398. giteaKeys = append(giteaKeys, v.OmitEmail())
  1399. }
  1400. // Get Public Keys from LDAP and skip duplicate keys
  1401. var ldapKeys []string
  1402. for _, v := range sshPublicKeys {
  1403. sshKeySplit := strings.Split(v, " ")
  1404. if len(sshKeySplit) > 1 {
  1405. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1406. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1407. ldapKeys = append(ldapKeys, ldapKey)
  1408. }
  1409. }
  1410. }
  1411. // Check if Public Key sync is needed
  1412. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1413. 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))
  1414. return false
  1415. }
  1416. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1417. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1418. var newLdapSSHKeys []string
  1419. for _, LDAPPublicSSHKey := range ldapKeys {
  1420. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1421. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1422. }
  1423. }
  1424. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1425. sshKeysNeedUpdate = true
  1426. }
  1427. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1428. var giteaKeysToDelete []string
  1429. for _, giteaKey := range giteaKeys {
  1430. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1431. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1432. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1433. }
  1434. }
  1435. // Delete LDAP keys from DB that doesn't exist in LDAP
  1436. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1437. if err != nil {
  1438. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1439. }
  1440. if needUpd {
  1441. sshKeysNeedUpdate = true
  1442. }
  1443. return sshKeysNeedUpdate
  1444. }
  1445. // SyncExternalUsers is used to synchronize users with external authorization source
  1446. func SyncExternalUsers(ctx context.Context, updateExisting bool) error {
  1447. log.Trace("Doing: SyncExternalUsers")
  1448. ls, err := LoginSources()
  1449. if err != nil {
  1450. log.Error("SyncExternalUsers: %v", err)
  1451. return err
  1452. }
  1453. for _, s := range ls {
  1454. if !s.IsActived || !s.IsSyncEnabled {
  1455. continue
  1456. }
  1457. select {
  1458. case <-ctx.Done():
  1459. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1460. return ErrCancelledf("Before update of %s", s.Name)
  1461. default:
  1462. }
  1463. if s.IsLDAP() {
  1464. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1465. var existingUsers []int64
  1466. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1467. var sshKeysNeedUpdate bool
  1468. // Find all users with this login type
  1469. var users []*User
  1470. err = x.Where("login_type = ?", LoginLDAP).
  1471. And("login_source = ?", s.ID).
  1472. Find(&users)
  1473. if err != nil {
  1474. log.Error("SyncExternalUsers: %v", err)
  1475. return err
  1476. }
  1477. select {
  1478. case <-ctx.Done():
  1479. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1480. return ErrCancelledf("Before update of %s", s.Name)
  1481. default:
  1482. }
  1483. sr, err := s.LDAP().SearchEntries()
  1484. if err != nil {
  1485. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1486. continue
  1487. }
  1488. if len(sr) == 0 {
  1489. if !s.LDAP().AllowDeactivateAll {
  1490. log.Error("LDAP search found no entries but did not report an error. Refusing to deactivate all users")
  1491. continue
  1492. } else {
  1493. log.Warn("LDAP search found no entries but did not report an error. All users will be deactivated as per settings")
  1494. }
  1495. }
  1496. for _, su := range sr {
  1497. select {
  1498. case <-ctx.Done():
  1499. log.Warn("SyncExternalUsers: Cancelled at update of %s before completed update of users", s.Name)
  1500. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1501. if sshKeysNeedUpdate {
  1502. err = RewriteAllPublicKeys()
  1503. if err != nil {
  1504. log.Error("RewriteAllPublicKeys: %v", err)
  1505. }
  1506. }
  1507. return ErrCancelledf("During update of %s before completed update of users", s.Name)
  1508. default:
  1509. }
  1510. if len(su.Username) == 0 {
  1511. continue
  1512. }
  1513. if len(su.Mail) == 0 {
  1514. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1515. }
  1516. var usr *User
  1517. // Search for existing user
  1518. for _, du := range users {
  1519. if du.LowerName == strings.ToLower(su.Username) {
  1520. usr = du
  1521. break
  1522. }
  1523. }
  1524. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1525. // If no existing user found, create one
  1526. if usr == nil {
  1527. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1528. usr = &User{
  1529. LowerName: strings.ToLower(su.Username),
  1530. Name: su.Username,
  1531. FullName: fullName,
  1532. LoginType: s.Type,
  1533. LoginSource: s.ID,
  1534. LoginName: su.Username,
  1535. Email: su.Mail,
  1536. IsAdmin: su.IsAdmin,
  1537. IsRestricted: su.IsRestricted,
  1538. IsActive: true,
  1539. }
  1540. err = CreateUser(usr)
  1541. if err != nil {
  1542. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1543. } else if isAttributeSSHPublicKeySet {
  1544. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1545. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1546. sshKeysNeedUpdate = true
  1547. }
  1548. }
  1549. } else if updateExisting {
  1550. existingUsers = append(existingUsers, usr.ID)
  1551. // Synchronize SSH Public Key if that attribute is set
  1552. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1553. sshKeysNeedUpdate = true
  1554. }
  1555. // Check if user data has changed
  1556. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1557. (len(s.LDAP().RestrictedFilter) > 0 && usr.IsRestricted != su.IsRestricted) ||
  1558. !strings.EqualFold(usr.Email, su.Mail) ||
  1559. usr.FullName != fullName ||
  1560. !usr.IsActive {
  1561. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1562. usr.FullName = fullName
  1563. usr.Email = su.Mail
  1564. // Change existing admin flag only if AdminFilter option is set
  1565. if len(s.LDAP().AdminFilter) > 0 {
  1566. usr.IsAdmin = su.IsAdmin
  1567. }
  1568. // Change existing restricted flag only if RestrictedFilter option is set
  1569. if !usr.IsAdmin && len(s.LDAP().RestrictedFilter) > 0 {
  1570. usr.IsRestricted = su.IsRestricted
  1571. }
  1572. usr.IsActive = true
  1573. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_restricted", "is_active")
  1574. if err != nil {
  1575. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1576. }
  1577. }
  1578. }
  1579. }
  1580. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1581. if sshKeysNeedUpdate {
  1582. err = RewriteAllPublicKeys()
  1583. if err != nil {
  1584. log.Error("RewriteAllPublicKeys: %v", err)
  1585. }
  1586. }
  1587. select {
  1588. case <-ctx.Done():
  1589. log.Warn("SyncExternalUsers: Cancelled during update of %s before delete users", s.Name)
  1590. return ErrCancelledf("During update of %s before delete users", s.Name)
  1591. default:
  1592. }
  1593. // Deactivate users not present in LDAP
  1594. if updateExisting {
  1595. for _, usr := range users {
  1596. found := false
  1597. for _, uid := range existingUsers {
  1598. if usr.ID == uid {
  1599. found = true
  1600. break
  1601. }
  1602. }
  1603. if !found {
  1604. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1605. usr.IsActive = false
  1606. err = UpdateUserCols(usr, "is_active")
  1607. if err != nil {
  1608. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1609. }
  1610. }
  1611. }
  1612. }
  1613. }
  1614. }
  1615. return nil
  1616. }
  1617. // IterateUser iterate users
  1618. func IterateUser(f func(user *User) error) error {
  1619. var start int
  1620. var batchSize = setting.Database.IterateBufferSize
  1621. for {
  1622. var users = make([]*User, 0, batchSize)
  1623. if err := x.Limit(batchSize, start).Find(&users); err != nil {
  1624. return err
  1625. }
  1626. if len(users) == 0 {
  1627. return nil
  1628. }
  1629. start += len(users)
  1630. for _, user := range users {
  1631. if err := f(user); err != nil {
  1632. return err
  1633. }
  1634. }
  1635. }
  1636. }