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.

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