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