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