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