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