You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 61 kB

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