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