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