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

user.go 55KB

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