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