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