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 57 kB

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