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