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