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.

1960 lines
54 KiB

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