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