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

auth.go 57 kB

3 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
3 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
3 years ago
3 years ago
3 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
3 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
3 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
3 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
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
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
3 years ago
3 years ago
4 years ago
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
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 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 user
  6. import (
  7. "errors"
  8. "fmt"
  9. "net/http"
  10. "strings"
  11. "code.gitea.io/gitea/modules/slideimage"
  12. phoneService "code.gitea.io/gitea/services/phone"
  13. "code.gitea.io/gitea/modules/labelmsg"
  14. "code.gitea.io/gitea/modules/phone"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/auth"
  17. "code.gitea.io/gitea/modules/auth/oauth2"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/eventsource"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/password"
  23. "code.gitea.io/gitea/modules/recaptcha"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/timeutil"
  26. "code.gitea.io/gitea/modules/util"
  27. "code.gitea.io/gitea/services/externalaccount"
  28. "code.gitea.io/gitea/services/mailer"
  29. "gitea.com/macaron/captcha"
  30. "github.com/markbates/goth"
  31. "github.com/tstranex/u2f"
  32. )
  33. const (
  34. // tplMustChangePassword template for updating a user's password
  35. tplMustChangePassword = "user/auth/change_passwd"
  36. // tplSignIn template for sign in page
  37. tplSignIn base.TplName = "user/auth/signin"
  38. // tplSignIn template for sign in page
  39. tplSignInCloudBrain base.TplName = "user/auth/signin_cloud_brain"
  40. tplSignInPhone base.TplName = "user/auth/signin_phone"
  41. // tplSignUp template path for sign up page
  42. tplSignUp base.TplName = "user/auth/signup"
  43. // TplActivate template path for activate user
  44. TplActivate base.TplName = "user/auth/activate"
  45. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  46. tplResetPassword base.TplName = "user/auth/reset_passwd"
  47. tplTwofa base.TplName = "user/auth/twofa"
  48. tplTwofaScratch base.TplName = "user/auth/twofa_scratch"
  49. tplLinkAccount base.TplName = "user/auth/link_account"
  50. tplU2F base.TplName = "user/auth/u2f"
  51. )
  52. // AutoSignIn reads cookie and try to auto-login.
  53. func AutoSignIn(ctx *context.Context) (bool, error) {
  54. if !models.HasEngine {
  55. return false, nil
  56. }
  57. uname := ctx.GetCookie(setting.CookieUserName)
  58. if len(uname) == 0 {
  59. return false, nil
  60. }
  61. isSucceed := false
  62. defer func() {
  63. if !isSucceed {
  64. log.Trace("auto-login cookie cleared: %s", uname)
  65. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  66. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  67. }
  68. }()
  69. u, err := models.GetUserByName(uname)
  70. if err != nil {
  71. if !models.IsErrUserNotExist(err) {
  72. return false, fmt.Errorf("GetUserByName: %v", err)
  73. }
  74. return false, nil
  75. }
  76. if val, ok := ctx.GetSuperSecureCookie(
  77. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); !ok || val != u.Name {
  78. return false, nil
  79. }
  80. isSucceed = true
  81. // Set session IDs
  82. if err := ctx.Session.Set("uid", u.ID); err != nil {
  83. return false, err
  84. }
  85. if err := ctx.Session.Set("uname", u.Name); err != nil {
  86. return false, err
  87. }
  88. if err := ctx.Session.Release(); err != nil {
  89. return false, err
  90. }
  91. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  92. return true, nil
  93. }
  94. func checkAutoLogin(ctx *context.Context) bool {
  95. // Check auto-login.
  96. isSucceed, err := AutoSignIn(ctx)
  97. if err != nil {
  98. ctx.ServerError("AutoSignIn", err)
  99. return true
  100. }
  101. redirectTo := ctx.Query("redirect_to")
  102. if len(redirectTo) > 0 {
  103. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  104. } else {
  105. redirectTo = ctx.GetCookie("redirect_to")
  106. }
  107. if isSucceed {
  108. isCourse := ctx.QueryBool("course")
  109. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  110. if redirectTo == "" && isCourse {
  111. redirectToCourse := setting.AppSubURL + "/" + setting.Course.OrgName
  112. ctx.RedirectToFirst(redirectToCourse)
  113. } else {
  114. ctx.RedirectToFirst(redirectTo, setting.AppSubURL+string(setting.LandingPageURL))
  115. }
  116. return true
  117. }
  118. return false
  119. }
  120. // SignIn render sign in page
  121. func SignIn(ctx *context.Context) {
  122. ctx.Data["Title"] = ctx.Tr("sign_in")
  123. // Check auto-login.
  124. if checkAutoLogin(ctx) {
  125. return
  126. }
  127. orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers()
  128. if err != nil {
  129. ctx.ServerError("UserSignIn", err)
  130. return
  131. }
  132. ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
  133. ctx.Data["OAuth2Providers"] = oauth2Providers
  134. ctx.Data["Title"] = ctx.Tr("sign_in")
  135. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  136. ctx.Data["PageIsSignIn"] = true
  137. ctx.Data["IsCourse"] = ctx.QueryBool("course")
  138. ctx.Data["PageIsLogin"] = true
  139. ctx.Data["EnableSSPI"] = models.IsSSPIEnabled()
  140. ctx.Data["EnableCloudBrain"] = true
  141. ctx.HTML(200, tplSignIn)
  142. }
  143. // SignInCloudBrain render sign in page
  144. func SignInCloudBrain(ctx *context.Context) {
  145. ctx.Data["Title"] = ctx.Tr("sign_in")
  146. // Check auto-login.
  147. if checkAutoLogin(ctx) {
  148. return
  149. }
  150. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  151. ctx.Data["PageIsSignIn"] = true
  152. ctx.Data["PageIsCloudBrainLogin"] = true
  153. ctx.Data["EnableCloudBrain"] = true
  154. ctx.HTML(200, tplSignInCloudBrain)
  155. }
  156. func SignInPhone(ctx *context.Context) {
  157. ctx.Data["Title"] = ctx.Tr("sign_in")
  158. // Check auto-login.
  159. if checkAutoLogin(ctx) {
  160. return
  161. }
  162. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  163. ctx.Data["PageIsSignIn"] = true
  164. ctx.Data["PageIsPhoneLogin"] = true
  165. ctx.HTML(200, tplSignInPhone)
  166. }
  167. func SignInPhonePost(ctx *context.Context, form auth.PhoneNumberCodeForm) {
  168. ctx.Data["Title"] = ctx.Tr("sign_in")
  169. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  170. ctx.Data["PageIsSignIn"] = true
  171. ctx.Data["PageIsLogin"] = true
  172. ctx.Data["EnablePhone"] = setting.PhoneService.Enabled
  173. ctx.Data["Title"] = ctx.Tr("sign_in")
  174. ctx.Data["IsCourse"] = ctx.QueryBool("course")
  175. if ctx.HasError() {
  176. ctx.HTML(200, tplSignInPhone)
  177. return
  178. }
  179. if !phoneService.IsVerifyCodeRight(strings.TrimSpace(form.PhoneNumber), strings.TrimSpace(form.VerifyCode)) {
  180. ctx.RenderWithErr(ctx.Tr("phone.verify_code_fail"), tplSignInPhone, &form)
  181. }
  182. u, err := models.GetUserByPhoneNumber(strings.TrimSpace(form.PhoneNumber))
  183. if err != nil {
  184. if models.IsErrUserNotExist(err) {
  185. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignInPhone, &form)
  186. log.Info("Failed authentication attempt for %s from %s", form.PhoneNumber, ctx.RemoteAddr())
  187. } else {
  188. ctx.ServerError("UserSignIn", err)
  189. }
  190. return
  191. }
  192. models.SaveLoginInfoToDb(ctx.Req.Request, u)
  193. handleSignIn(ctx, u, form.Remember)
  194. }
  195. // SignInPost response for sign in request
  196. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  197. ctx.Data["Title"] = ctx.Tr("sign_in")
  198. orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers()
  199. if err != nil {
  200. ctx.ServerError("UserSignIn", err)
  201. return
  202. }
  203. ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
  204. ctx.Data["OAuth2Providers"] = oauth2Providers
  205. ctx.Data["Title"] = ctx.Tr("sign_in")
  206. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  207. ctx.Data["PageIsSignIn"] = true
  208. ctx.Data["PageIsLogin"] = true
  209. ctx.Data["IsCourse"] = ctx.QueryBool("course")
  210. ctx.Data["EnableSSPI"] = models.IsSSPIEnabled()
  211. if ctx.HasError() {
  212. ctx.HTML(200, tplSignIn)
  213. return
  214. }
  215. u, err := models.UserSignIn(form.UserName, form.Password)
  216. if err != nil {
  217. if models.IsErrUserNotExist(err) {
  218. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  219. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  220. } else if models.IsErrEmailAlreadyUsed(err) {
  221. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form)
  222. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  223. } else if models.IsErrUserProhibitLogin(err) {
  224. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  225. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  226. ctx.HTML(200, "user/auth/prohibit_login")
  227. } else if models.IsErrUserInactive(err) {
  228. if setting.Service.RegisterEmailConfirm {
  229. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  230. ctx.HTML(200, TplActivate)
  231. } else {
  232. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  233. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  234. ctx.HTML(200, "user/auth/prohibit_login")
  235. }
  236. } else {
  237. ctx.ServerError("UserSignIn", err)
  238. }
  239. return
  240. }
  241. models.SaveLoginInfoToDb(ctx.Req.Request, u)
  242. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  243. // Instead, redirect them to the 2FA authentication page.
  244. _, err = models.GetTwoFactorByUID(u.ID)
  245. if err != nil {
  246. if models.IsErrTwoFactorNotEnrolled(err) {
  247. handleSignIn(ctx, u, form.Remember)
  248. } else {
  249. ctx.ServerError("UserSignIn", err)
  250. }
  251. return
  252. }
  253. // User needs to use 2FA, save data and redirect to 2FA page.
  254. if err := ctx.Session.Set("twofaUid", u.ID); err != nil {
  255. ctx.ServerError("UserSignIn: Unable to set twofaUid in session", err)
  256. return
  257. }
  258. if err := ctx.Session.Set("twofaRemember", form.Remember); err != nil {
  259. ctx.ServerError("UserSignIn: Unable to set twofaRemember in session", err)
  260. return
  261. }
  262. if err := ctx.Session.Release(); err != nil {
  263. ctx.ServerError("UserSignIn: Unable to save session", err)
  264. return
  265. }
  266. regs, err := models.GetU2FRegistrationsByUID(u.ID)
  267. if err == nil && len(regs) > 0 {
  268. ctx.Redirect(setting.AppSubURL + "/user/u2f")
  269. return
  270. }
  271. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  272. }
  273. // TwoFactor shows the user a two-factor authentication page.
  274. func TwoFactor(ctx *context.Context) {
  275. ctx.Data["Title"] = ctx.Tr("twofa")
  276. // Check auto-login.
  277. if checkAutoLogin(ctx) {
  278. return
  279. }
  280. // Ensure user is in a 2FA session.
  281. if ctx.Session.Get("twofaUid") == nil {
  282. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  283. return
  284. }
  285. ctx.HTML(200, tplTwofa)
  286. }
  287. // TwoFactorPost validates a user's two-factor authentication token.
  288. func TwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  289. ctx.Data["Title"] = ctx.Tr("twofa")
  290. // Ensure user is in a 2FA session.
  291. idSess := ctx.Session.Get("twofaUid")
  292. if idSess == nil {
  293. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  294. return
  295. }
  296. id := idSess.(int64)
  297. twofa, err := models.GetTwoFactorByUID(id)
  298. if err != nil {
  299. ctx.ServerError("UserSignIn", err)
  300. return
  301. }
  302. // Validate the passcode with the stored TOTP secret.
  303. ok, err := twofa.ValidateTOTP(form.Passcode)
  304. if err != nil {
  305. ctx.ServerError("UserSignIn", err)
  306. return
  307. }
  308. if ok && twofa.LastUsedPasscode != form.Passcode {
  309. remember := ctx.Session.Get("twofaRemember").(bool)
  310. u, err := models.GetUserByID(id)
  311. if err != nil {
  312. ctx.ServerError("UserSignIn", err)
  313. return
  314. }
  315. if ctx.Session.Get("linkAccount") != nil {
  316. gothUser := ctx.Session.Get("linkAccountGothUser")
  317. if gothUser == nil {
  318. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  319. return
  320. }
  321. err = externalaccount.LinkAccountToUser(u, gothUser.(goth.User))
  322. if err != nil {
  323. ctx.ServerError("UserSignIn", err)
  324. return
  325. }
  326. }
  327. twofa.LastUsedPasscode = form.Passcode
  328. if err = models.UpdateTwoFactor(twofa); err != nil {
  329. ctx.ServerError("UserSignIn", err)
  330. return
  331. }
  332. handleSignIn(ctx, u, remember)
  333. return
  334. }
  335. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  336. }
  337. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  338. func TwoFactorScratch(ctx *context.Context) {
  339. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  340. // Check auto-login.
  341. if checkAutoLogin(ctx) {
  342. return
  343. }
  344. // Ensure user is in a 2FA session.
  345. if ctx.Session.Get("twofaUid") == nil {
  346. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  347. return
  348. }
  349. ctx.HTML(200, tplTwofaScratch)
  350. }
  351. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  352. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  353. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  354. // Ensure user is in a 2FA session.
  355. idSess := ctx.Session.Get("twofaUid")
  356. if idSess == nil {
  357. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  358. return
  359. }
  360. id := idSess.(int64)
  361. twofa, err := models.GetTwoFactorByUID(id)
  362. if err != nil {
  363. ctx.ServerError("UserSignIn", err)
  364. return
  365. }
  366. // Validate the passcode with the stored TOTP secret.
  367. if twofa.VerifyScratchToken(form.Token) {
  368. // Invalidate the scratch token.
  369. _, err = twofa.GenerateScratchToken()
  370. if err != nil {
  371. ctx.ServerError("UserSignIn", err)
  372. return
  373. }
  374. if err = models.UpdateTwoFactor(twofa); err != nil {
  375. ctx.ServerError("UserSignIn", err)
  376. return
  377. }
  378. remember := ctx.Session.Get("twofaRemember").(bool)
  379. u, err := models.GetUserByID(id)
  380. if err != nil {
  381. ctx.ServerError("UserSignIn", err)
  382. return
  383. }
  384. handleSignInFull(ctx, u, remember, false)
  385. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  386. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  387. return
  388. }
  389. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  390. }
  391. // U2F shows the U2F login page
  392. func U2F(ctx *context.Context) {
  393. ctx.Data["Title"] = ctx.Tr("twofa")
  394. ctx.Data["RequireU2F"] = true
  395. // Check auto-login.
  396. if checkAutoLogin(ctx) {
  397. return
  398. }
  399. // Ensure user is in a 2FA session.
  400. if ctx.Session.Get("twofaUid") == nil {
  401. ctx.ServerError("UserSignIn", errors.New("not in U2F session"))
  402. return
  403. }
  404. ctx.HTML(200, tplU2F)
  405. }
  406. // U2FChallenge submits a sign challenge to the browser
  407. func U2FChallenge(ctx *context.Context) {
  408. // Ensure user is in a U2F session.
  409. idSess := ctx.Session.Get("twofaUid")
  410. if idSess == nil {
  411. ctx.ServerError("UserSignIn", errors.New("not in U2F session"))
  412. return
  413. }
  414. id := idSess.(int64)
  415. regs, err := models.GetU2FRegistrationsByUID(id)
  416. if err != nil {
  417. ctx.ServerError("UserSignIn", err)
  418. return
  419. }
  420. if len(regs) == 0 {
  421. ctx.ServerError("UserSignIn", errors.New("no device registered"))
  422. return
  423. }
  424. challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets)
  425. if err != nil {
  426. ctx.ServerError("u2f.NewChallenge", err)
  427. return
  428. }
  429. if err := ctx.Session.Set("u2fChallenge", challenge); err != nil {
  430. ctx.ServerError("UserSignIn: unable to set u2fChallenge in session", err)
  431. return
  432. }
  433. if err := ctx.Session.Release(); err != nil {
  434. ctx.ServerError("UserSignIn: unable to store session", err)
  435. }
  436. ctx.JSON(200, challenge.SignRequest(regs.ToRegistrations()))
  437. }
  438. // U2FSign authenticates the user by signResp
  439. func U2FSign(ctx *context.Context, signResp u2f.SignResponse) {
  440. challSess := ctx.Session.Get("u2fChallenge")
  441. idSess := ctx.Session.Get("twofaUid")
  442. if challSess == nil || idSess == nil {
  443. ctx.ServerError("UserSignIn", errors.New("not in U2F session"))
  444. return
  445. }
  446. challenge := challSess.(*u2f.Challenge)
  447. id := idSess.(int64)
  448. regs, err := models.GetU2FRegistrationsByUID(id)
  449. if err != nil {
  450. ctx.ServerError("UserSignIn", err)
  451. return
  452. }
  453. for _, reg := range regs {
  454. r, err := reg.Parse()
  455. if err != nil {
  456. log.Fatal("parsing u2f registration: %v", err)
  457. continue
  458. }
  459. newCounter, authErr := r.Authenticate(signResp, *challenge, reg.Counter)
  460. if authErr == nil {
  461. reg.Counter = newCounter
  462. user, err := models.GetUserByID(id)
  463. if err != nil {
  464. ctx.ServerError("UserSignIn", err)
  465. return
  466. }
  467. remember := ctx.Session.Get("twofaRemember").(bool)
  468. if err := reg.UpdateCounter(); err != nil {
  469. ctx.ServerError("UserSignIn", err)
  470. return
  471. }
  472. if ctx.Session.Get("linkAccount") != nil {
  473. gothUser := ctx.Session.Get("linkAccountGothUser")
  474. if gothUser == nil {
  475. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  476. return
  477. }
  478. err = externalaccount.LinkAccountToUser(user, gothUser.(goth.User))
  479. if err != nil {
  480. ctx.ServerError("UserSignIn", err)
  481. return
  482. }
  483. }
  484. redirect := handleSignInFull(ctx, user, remember, false)
  485. if redirect == "" {
  486. redirect = setting.AppSubURL + "/"
  487. }
  488. ctx.PlainText(200, []byte(redirect))
  489. return
  490. }
  491. }
  492. ctx.Error(401)
  493. }
  494. // This handles the final part of the sign-in process of the user.
  495. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  496. handleSignInFull(ctx, u, remember, true)
  497. }
  498. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) string {
  499. if remember {
  500. days := 86400 * setting.LogInRememberDays
  501. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  502. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  503. setting.CookieRememberName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  504. }
  505. _ = ctx.Session.Delete("openid_verified_uri")
  506. _ = ctx.Session.Delete("openid_signin_remember")
  507. _ = ctx.Session.Delete("openid_determined_email")
  508. _ = ctx.Session.Delete("openid_determined_username")
  509. _ = ctx.Session.Delete("twofaUid")
  510. _ = ctx.Session.Delete("twofaRemember")
  511. _ = ctx.Session.Delete("u2fChallenge")
  512. _ = ctx.Session.Delete("linkAccount")
  513. if err := ctx.Session.Set("uid", u.ID); err != nil {
  514. log.Error("Error setting uid %d in session: %v", u.ID, err)
  515. }
  516. if err := ctx.Session.Set("uname", u.Name); err != nil {
  517. log.Error("Error setting uname %s session: %v", u.Name, err)
  518. }
  519. if err := ctx.Session.Release(); err != nil {
  520. log.Error("Unable to store session: %v", err)
  521. }
  522. // If the user does not have a locale set, we save the current one.
  523. if len(u.Language) == 0 {
  524. if len(ctx.GetCookie("lang")) != 0 {
  525. u.Language = ctx.GetCookie("lang")
  526. } else {
  527. u.Language = ctx.Locale.Language()
  528. }
  529. if err := models.UpdateUserCols(u, "language"); err != nil {
  530. log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", u.ID, u.Language))
  531. return setting.AppSubURL + "/dashboard"
  532. }
  533. } else {
  534. // Language setting of the user use the one previously set
  535. if len(ctx.GetCookie("lang")) != 0 {
  536. u.Language = ctx.GetCookie("lang")
  537. }
  538. }
  539. ctx.SetCookie("lang", u.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  540. // Clear whatever CSRF has right now, force to generate a new one
  541. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  542. // Register last login
  543. u.SetLastLogin()
  544. if err := models.UpdateUserCols(u, "last_login_unix"); err != nil {
  545. ctx.ServerError("UpdateUserCols", err)
  546. return setting.AppSubURL + "/dashboard"
  547. }
  548. isCourse := ctx.QueryBool("course")
  549. if isCourse {
  550. redirectToCourse := setting.AppSubURL + "/" + setting.Course.OrgName
  551. ctx.RedirectToFirst(redirectToCourse)
  552. return redirectToCourse
  553. }
  554. if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !util.IsExternalURL(redirectTo) {
  555. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  556. if obeyRedirect {
  557. ctx.RedirectToFirst(redirectTo)
  558. }
  559. return redirectTo
  560. }
  561. if obeyRedirect {
  562. ctx.Redirect(setting.AppSubURL + "/dashboard")
  563. }
  564. return setting.AppSubURL + "/dashboard"
  565. }
  566. // SignInOAuth handles the OAuth2 login buttons
  567. func SignInOAuth(ctx *context.Context) {
  568. provider := ctx.Params(":provider")
  569. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  570. if err != nil {
  571. ctx.ServerError("SignIn", err)
  572. return
  573. }
  574. // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user
  575. user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  576. if err == nil && user != nil {
  577. // we got the user without going through the whole OAuth2 authentication flow again
  578. handleOAuth2SignIn(user, gothUser, ctx, err)
  579. return
  580. }
  581. err = oauth2.Auth(loginSource.Name, ctx.Req.Request, ctx.Resp)
  582. if err != nil {
  583. ctx.ServerError("SignIn", err)
  584. }
  585. // redirect is done in oauth2.Auth
  586. }
  587. // SignInOAuthCallback handles the callback from the given provider
  588. func SignInOAuthCallback(ctx *context.Context) {
  589. provider := ctx.Params(":provider")
  590. // first look if the provider is still active
  591. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  592. if err != nil {
  593. ctx.ServerError("SignIn", err)
  594. return
  595. }
  596. if loginSource == nil {
  597. ctx.ServerError("SignIn", errors.New("No valid provider found, check configured callback url in provider"))
  598. return
  599. }
  600. u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  601. handleOAuth2SignIn(u, gothUser, ctx, err)
  602. }
  603. func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context, err error) {
  604. if err != nil {
  605. ctx.ServerError("UserSignIn", err)
  606. return
  607. }
  608. if u == nil {
  609. // no existing user is found, request attach or new account
  610. if err := ctx.Session.Set("linkAccountGothUser", gothUser); err != nil {
  611. log.Error("Error setting linkAccountGothUser in session: %v", err)
  612. }
  613. if err := ctx.Session.Release(); err != nil {
  614. log.Error("Error storing session: %v", err)
  615. }
  616. ctx.Redirect(setting.AppSubURL + "/user/link_account")
  617. return
  618. }
  619. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  620. // Instead, redirect them to the 2FA authentication page.
  621. _, err = models.GetTwoFactorByUID(u.ID)
  622. if err != nil {
  623. if !models.IsErrTwoFactorNotEnrolled(err) {
  624. ctx.ServerError("UserSignIn", err)
  625. return
  626. }
  627. if err := ctx.Session.Set("uid", u.ID); err != nil {
  628. log.Error("Error setting uid in session: %v", err)
  629. }
  630. if err := ctx.Session.Set("uname", u.Name); err != nil {
  631. log.Error("Error setting uname in session: %v", err)
  632. }
  633. if err := ctx.Session.Release(); err != nil {
  634. log.Error("Error storing session: %v", err)
  635. }
  636. // Clear whatever CSRF has right now, force to generate a new one
  637. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  638. // Register last login
  639. u.SetLastLogin()
  640. if err := models.UpdateUserCols(u, "last_login_unix"); err != nil {
  641. ctx.ServerError("UpdateUserCols", err)
  642. return
  643. }
  644. // update external user information
  645. if err := models.UpdateExternalUser(u, gothUser); err != nil {
  646. log.Error("UpdateExternalUser failed: %v", err)
  647. }
  648. if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 {
  649. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  650. ctx.RedirectToFirst(redirectTo)
  651. return
  652. }
  653. ctx.Redirect(setting.AppSubURL + "/")
  654. return
  655. }
  656. // User needs to use 2FA, save data and redirect to 2FA page.
  657. if err := ctx.Session.Set("twofaUid", u.ID); err != nil {
  658. log.Error("Error setting twofaUid in session: %v", err)
  659. }
  660. if err := ctx.Session.Set("twofaRemember", false); err != nil {
  661. log.Error("Error setting twofaRemember in session: %v", err)
  662. }
  663. if err := ctx.Session.Release(); err != nil {
  664. log.Error("Error storing session: %v", err)
  665. }
  666. // If U2F is enrolled -> Redirect to U2F instead
  667. regs, err := models.GetU2FRegistrationsByUID(u.ID)
  668. if err == nil && len(regs) > 0 {
  669. ctx.Redirect(setting.AppSubURL + "/user/u2f")
  670. return
  671. }
  672. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  673. }
  674. // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
  675. // login the user
  676. func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
  677. gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response)
  678. if err != nil {
  679. if err.Error() == "securecookie: the value is too long" {
  680. log.Error("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", loginSource.Name, setting.OAuth2.MaxTokenLength)
  681. err = fmt.Errorf("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", loginSource.Name, setting.OAuth2.MaxTokenLength)
  682. }
  683. return nil, goth.User{}, err
  684. }
  685. user := &models.User{
  686. LoginName: gothUser.UserID,
  687. LoginType: models.LoginOAuth2,
  688. LoginSource: loginSource.ID,
  689. }
  690. hasUser, err := models.GetUser(user)
  691. if err != nil {
  692. return nil, goth.User{}, err
  693. }
  694. if hasUser {
  695. return user, gothUser, nil
  696. }
  697. // search in external linked users
  698. externalLoginUser := &models.ExternalLoginUser{
  699. ExternalID: gothUser.UserID,
  700. LoginSourceID: loginSource.ID,
  701. }
  702. hasUser, err = models.GetExternalLogin(externalLoginUser)
  703. if err != nil {
  704. return nil, goth.User{}, err
  705. }
  706. if hasUser {
  707. user, err = models.GetUserByID(externalLoginUser.UserID)
  708. return user, gothUser, err
  709. }
  710. // no user found to login
  711. return nil, gothUser, nil
  712. }
  713. // LinkAccount shows the page where the user can decide to login or create a new account
  714. func LinkAccount(ctx *context.Context) {
  715. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
  716. ctx.Data["Title"] = ctx.Tr("link_account")
  717. ctx.Data["LinkAccountMode"] = true
  718. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  719. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  720. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  721. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  722. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  723. ctx.Data["ShowRegistrationButton"] = false
  724. // use this to set the right link into the signIn and signUp templates in the link_account template
  725. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  726. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  727. gothUser := ctx.Session.Get("linkAccountGothUser")
  728. if gothUser == nil {
  729. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  730. return
  731. }
  732. uname := gothUser.(goth.User).NickName
  733. email := gothUser.(goth.User).Email
  734. ctx.Data["user_name"] = uname
  735. ctx.Data["email"] = email
  736. if len(email) != 0 {
  737. u, err := models.GetUserByEmail(email)
  738. if err != nil && !models.IsErrUserNotExist(err) {
  739. ctx.ServerError("UserSignIn", err)
  740. return
  741. }
  742. if u != nil {
  743. ctx.Data["user_exists"] = true
  744. }
  745. } else if len(uname) != 0 {
  746. u, err := models.GetUserByName(uname)
  747. if err != nil && !models.IsErrUserNotExist(err) {
  748. ctx.ServerError("UserSignIn", err)
  749. return
  750. }
  751. if u != nil {
  752. ctx.Data["user_exists"] = true
  753. }
  754. }
  755. ctx.HTML(200, tplLinkAccount)
  756. }
  757. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  758. func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) {
  759. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
  760. ctx.Data["Title"] = ctx.Tr("link_account")
  761. ctx.Data["LinkAccountMode"] = true
  762. ctx.Data["LinkAccountModeSignIn"] = true
  763. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  764. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  765. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  766. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  767. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  768. ctx.Data["ShowRegistrationButton"] = false
  769. // use this to set the right link into the signIn and signUp templates in the link_account template
  770. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  771. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  772. gothUser := ctx.Session.Get("linkAccountGothUser")
  773. if gothUser == nil {
  774. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  775. return
  776. }
  777. if ctx.HasError() {
  778. ctx.HTML(200, tplLinkAccount)
  779. return
  780. }
  781. u, err := models.UserSignIn(signInForm.UserName, signInForm.Password)
  782. if err != nil {
  783. if models.IsErrUserNotExist(err) {
  784. ctx.Data["user_exists"] = true
  785. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm)
  786. } else {
  787. ctx.ServerError("UserLinkAccount", err)
  788. }
  789. return
  790. }
  791. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  792. // Instead, redirect them to the 2FA authentication page.
  793. _, err = models.GetTwoFactorByUID(u.ID)
  794. if err != nil {
  795. if !models.IsErrTwoFactorNotEnrolled(err) {
  796. ctx.ServerError("UserLinkAccount", err)
  797. return
  798. }
  799. err = externalaccount.LinkAccountToUser(u, gothUser.(goth.User))
  800. if err != nil {
  801. ctx.ServerError("UserLinkAccount", err)
  802. return
  803. }
  804. handleSignIn(ctx, u, signInForm.Remember)
  805. return
  806. }
  807. // User needs to use 2FA, save data and redirect to 2FA page.
  808. if err := ctx.Session.Set("twofaUid", u.ID); err != nil {
  809. log.Error("Error setting twofaUid in session: %v", err)
  810. }
  811. if err := ctx.Session.Set("twofaRemember", signInForm.Remember); err != nil {
  812. log.Error("Error setting twofaRemember in session: %v", err)
  813. }
  814. if err := ctx.Session.Set("linkAccount", true); err != nil {
  815. log.Error("Error setting linkAccount in session: %v", err)
  816. }
  817. if err := ctx.Session.Release(); err != nil {
  818. log.Error("Error storing session: %v", err)
  819. }
  820. // If U2F is enrolled -> Redirect to U2F instead
  821. regs, err := models.GetU2FRegistrationsByUID(u.ID)
  822. if err == nil && len(regs) > 0 {
  823. ctx.Redirect(setting.AppSubURL + "/user/u2f")
  824. return
  825. }
  826. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  827. }
  828. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  829. func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  830. // TODO Make insecure passwords optional for local accounts also,
  831. // once email-based Second-Factor Auth is available
  832. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
  833. ctx.Data["Title"] = ctx.Tr("link_account")
  834. ctx.Data["LinkAccountMode"] = true
  835. ctx.Data["LinkAccountModeRegister"] = true
  836. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  837. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  838. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  839. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  840. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  841. ctx.Data["ShowRegistrationButton"] = false
  842. // use this to set the right link into the signIn and signUp templates in the link_account template
  843. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  844. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  845. gothUser := ctx.Session.Get("linkAccountGothUser")
  846. if gothUser == nil {
  847. ctx.ServerError("UserSignUp", errors.New("not in LinkAccount session"))
  848. return
  849. }
  850. if ctx.HasError() {
  851. ctx.HTML(200, tplLinkAccount)
  852. return
  853. }
  854. if setting.Service.DisableRegistration {
  855. ctx.Error(403)
  856. return
  857. }
  858. if setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha {
  859. var valid bool
  860. switch setting.Service.CaptchaType {
  861. case setting.ImageCaptcha:
  862. valid = cpt.VerifyReq(ctx.Req)
  863. case setting.ReCaptcha:
  864. valid, _ = recaptcha.Verify(form.GRecaptchaResponse)
  865. default:
  866. ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType))
  867. return
  868. }
  869. if !valid {
  870. ctx.Data["Err_Captcha"] = true
  871. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form)
  872. return
  873. }
  874. }
  875. if setting.Service.AllowOnlyExternalRegistration || !setting.Service.RequireExternalRegistrationPassword {
  876. // In models.User an empty password is classed as not set, so we set form.Password to empty.
  877. // Eventually the database should be changed to indicate "Second Factor"-enabled accounts
  878. // (accounts that do not introduce the security vulnerabilities of a password).
  879. // If a user decides to circumvent second-factor security, and purposefully create a password,
  880. // they can still do so using the "Recover Account" option.
  881. form.Password = ""
  882. } else {
  883. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  884. ctx.Data["Err_Password"] = true
  885. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  886. return
  887. }
  888. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  889. ctx.Data["Err_Password"] = true
  890. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  891. return
  892. }
  893. }
  894. loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.(goth.User).Provider)
  895. if err != nil {
  896. ctx.ServerError("CreateUser", err)
  897. }
  898. u := &models.User{
  899. Name: form.UserName,
  900. Email: form.Email,
  901. Passwd: form.Password,
  902. IsActive: !setting.Service.RegisterEmailConfirm,
  903. LoginType: models.LoginOAuth2,
  904. LoginSource: loginSource.ID,
  905. LoginName: gothUser.(goth.User).UserID,
  906. }
  907. //nolint: dupl
  908. if err := models.CreateUser(u); err != nil {
  909. switch {
  910. case models.IsErrUserAlreadyExist(err):
  911. ctx.Data["Err_UserName"] = true
  912. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplLinkAccount, &form)
  913. case models.IsErrEmailAlreadyUsed(err):
  914. ctx.Data["Err_Email"] = true
  915. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplLinkAccount, &form)
  916. case models.IsErrNameReserved(err):
  917. ctx.Data["Err_UserName"] = true
  918. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplLinkAccount, &form)
  919. case models.IsErrNamePatternNotAllowed(err):
  920. ctx.Data["Err_UserName"] = true
  921. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplLinkAccount, &form)
  922. case models.IsErrNameCharsNotAllowed(err):
  923. ctx.Data["Err_UserName"] = true
  924. ctx.RenderWithErr(ctx.Tr("user.form.name_chars_not_allowed", err.(models.ErrNameCharsNotAllowed).Name), tplLinkAccount, &form)
  925. default:
  926. ctx.ServerError("CreateUser", err)
  927. }
  928. return
  929. }
  930. log.Trace("Account created: %s", u.Name)
  931. // Auto-set admin for the only user.
  932. if models.CountUsers() == 1 {
  933. u.IsAdmin = true
  934. u.IsActive = true
  935. u.SetLastLogin()
  936. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  937. ctx.ServerError("UpdateUser", err)
  938. return
  939. }
  940. }
  941. // update external user information
  942. if err := models.UpdateExternalUser(u, gothUser.(goth.User)); err != nil {
  943. log.Error("UpdateExternalUser failed: %v", err)
  944. }
  945. // Send confirmation email
  946. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  947. mailer.SendActivateAccountMail(ctx.Locale, u)
  948. ctx.Data["IsSendRegisterMail"] = true
  949. ctx.Data["Email"] = u.Email
  950. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  951. ctx.HTML(200, TplActivate)
  952. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  953. log.Error("Set cache(MailResendLimit) fail: %v", err)
  954. }
  955. return
  956. }
  957. ctx.Redirect(setting.AppSubURL + "/user/login")
  958. }
  959. // HandleSignOut resets the session and sets the cookies
  960. func HandleSignOut(ctx *context.Context) {
  961. _ = ctx.Session.Flush()
  962. _ = ctx.Session.Destroy(ctx.Context)
  963. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  964. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  965. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  966. ctx.SetCookie("lang", "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) // Setting the lang cookie will trigger the middleware to reset the language ot previous state.
  967. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL) // logout default should set redirect to to default
  968. }
  969. // SignOut sign out from login status
  970. func SignOut(ctx *context.Context) {
  971. if ctx.User != nil {
  972. eventsource.GetManager().SendMessageBlocking(ctx.User.ID, &eventsource.Event{
  973. Name: "logout",
  974. Data: ctx.Session.ID(),
  975. })
  976. }
  977. HandleSignOut(ctx)
  978. ctx.Redirect(setting.AppSubURL + "/")
  979. }
  980. // SignUp render the register page
  981. func SignUp(ctx *context.Context) {
  982. ctx.Data["Title"] = ctx.Tr("sign_up")
  983. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  984. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  985. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  986. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  987. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  988. ctx.Data["PageIsSignUp"] = true
  989. //Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true
  990. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration
  991. ctx.HTML(200, tplSignUp)
  992. }
  993. // SignUpPost response for sign up information submission
  994. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  995. ctx.Data["Title"] = ctx.Tr("sign_up")
  996. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  997. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  998. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  999. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  1000. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  1001. ctx.Data["PageIsSignUp"] = true
  1002. //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true
  1003. if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration {
  1004. ctx.Error(403)
  1005. return
  1006. }
  1007. if ctx.HasError() {
  1008. ctx.HTML(200, tplSignUp)
  1009. return
  1010. }
  1011. if setting.Service.EnableCaptcha {
  1012. var valid bool
  1013. switch setting.Service.CaptchaType {
  1014. case setting.ImageCaptcha:
  1015. valid = cpt.VerifyReq(ctx.Req)
  1016. case setting.ReCaptcha:
  1017. valid, _ = recaptcha.Verify(form.GRecaptchaResponse)
  1018. default:
  1019. ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType))
  1020. return
  1021. }
  1022. if !valid {
  1023. ctx.Data["Err_Captcha"] = true
  1024. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  1025. return
  1026. }
  1027. }
  1028. if !form.IsEmailDomainWhitelisted() {
  1029. ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplSignUp, &form)
  1030. return
  1031. }
  1032. if form.Password != form.Retype {
  1033. ctx.Data["Err_Password"] = true
  1034. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  1035. return
  1036. }
  1037. if len(form.Password) < setting.MinPasswordLength {
  1038. ctx.Data["Err_Password"] = true
  1039. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  1040. return
  1041. }
  1042. if !password.IsComplexEnough(form.Password) {
  1043. ctx.Data["Err_Password"] = true
  1044. ctx.RenderWithErr(password.BuildComplexityError(ctx), tplSignUp, &form)
  1045. return
  1046. }
  1047. if setting.PhoneService.Enabled {
  1048. phoneNumber := strings.TrimSpace(form.PhoneNumber)
  1049. verifyCode := strings.TrimSpace(form.VerifyCode)
  1050. if !phoneService.IsVerifyCodeRight(phoneNumber, verifyCode) {
  1051. ctx.RenderWithErr(ctx.Tr("phone.verify_code_fail"), tplSignUp, &form)
  1052. return
  1053. }
  1054. }
  1055. u := &models.User{
  1056. Name: form.UserName,
  1057. Email: form.Email,
  1058. Passwd: form.Password,
  1059. PhoneNumber: strings.TrimSpace(form.PhoneNumber),
  1060. IsActive: !setting.Service.RegisterEmailConfirm,
  1061. }
  1062. if err := models.CreateUser(u); err != nil {
  1063. switch {
  1064. case models.IsErrUserAlreadyExist(err):
  1065. ctx.Data["Err_UserName"] = true
  1066. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  1067. case models.IsErrEmailAlreadyUsed(err):
  1068. ctx.Data["Err_Email"] = true
  1069. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  1070. case models.IsErrNameReserved(err):
  1071. ctx.Data["Err_UserName"] = true
  1072. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  1073. case models.IsErrNamePatternNotAllowed(err):
  1074. ctx.Data["Err_UserName"] = true
  1075. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  1076. default:
  1077. ctx.ServerError("CreateUser", err)
  1078. }
  1079. return
  1080. }
  1081. log.Trace("Account created: %s", u.Name, ctx.Data["MsgID"])
  1082. err := models.AddEmailAddress(&models.EmailAddress{
  1083. UID: u.ID,
  1084. Email: form.Email,
  1085. IsActivated: !setting.Service.RegisterEmailConfirm,
  1086. })
  1087. if err != nil {
  1088. log.Error("AddEmailAddress failed:%v", err.Error(), ctx.Data["MsgID"])
  1089. ctx.ServerError("AddEmailAddress", err)
  1090. return
  1091. }
  1092. // Auto-set admin for the only user.
  1093. if models.CountUsers() == 1 {
  1094. u.IsAdmin = true
  1095. u.IsActive = true
  1096. u.SetLastLogin()
  1097. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  1098. ctx.ServerError("UpdateUser", err)
  1099. return
  1100. }
  1101. }
  1102. // Send confirmation email, no need for social account.
  1103. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  1104. mailer.SendActivateAccountMail(ctx.Locale, u)
  1105. ctx.Data["IsSendRegisterMail"] = true
  1106. ctx.Data["Email"] = u.Email
  1107. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  1108. ctx.HTML(200, TplActivate)
  1109. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  1110. log.Error("Set cache(MailResendLimit) fail: %v", err)
  1111. }
  1112. return
  1113. }
  1114. ctx.Flash.Success(ctx.Tr("auth.sign_up_successful"))
  1115. handleSignInFull(ctx, u, false, true)
  1116. }
  1117. // Activate render activate user page
  1118. func Activate(ctx *context.Context) {
  1119. code := ctx.Query("code")
  1120. if len(code) == 0 {
  1121. ctx.Data["IsActivatePage"] = true
  1122. if ctx.User.IsActive {
  1123. ctx.Error(404)
  1124. return
  1125. }
  1126. // Resend confirmation email.
  1127. if setting.Service.RegisterEmailConfirm {
  1128. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  1129. ctx.Data["ResendLimited"] = true
  1130. } else {
  1131. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  1132. mailer.SendActivateAccountMail(ctx.Locale, ctx.User)
  1133. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  1134. log.Error("Set cache(MailResendLimit) fail: %v", err)
  1135. }
  1136. }
  1137. } else {
  1138. ctx.Data["ServiceNotEnabled"] = true
  1139. }
  1140. ctx.HTML(200, TplActivate)
  1141. return
  1142. }
  1143. // Verify code.
  1144. if user := models.VerifyUserActiveCode(code); user != nil {
  1145. user.IsActive = true
  1146. var err error
  1147. if user.Rands, err = models.GetUserSalt(); err != nil {
  1148. ctx.ServerError("UpdateUser", err)
  1149. return
  1150. }
  1151. if err := models.UpdateUserCols(user, "is_active", "rands"); err != nil {
  1152. if models.IsErrUserNotExist(err) {
  1153. ctx.Error(404)
  1154. } else {
  1155. ctx.ServerError("UpdateUser", err)
  1156. }
  1157. return
  1158. }
  1159. log.Trace("User activated: %s", user.Name)
  1160. if err := ctx.Session.Set("uid", user.ID); err != nil {
  1161. log.Error(fmt.Sprintf("Error setting uid in session: %v", err))
  1162. }
  1163. if err := ctx.Session.Set("uname", user.Name); err != nil {
  1164. log.Error(fmt.Sprintf("Error setting uname in session: %v", err))
  1165. }
  1166. if err := ctx.Session.Release(); err != nil {
  1167. log.Error("Error storing session: %v", err)
  1168. }
  1169. email, err := models.GetEmailAddressByIDAndEmail(user.ID, user.Email)
  1170. if err != nil || email == nil {
  1171. log.Error("GetEmailAddressByIDAndEmail failed", ctx.Data["MsgID"])
  1172. } else {
  1173. if err := email.Activate(); err != nil {
  1174. log.Error("Activate failed: %v", err, ctx.Data["MsgID"])
  1175. }
  1176. }
  1177. ctx.Flash.Success(ctx.Tr("auth.account_activated"))
  1178. ctx.Redirect(setting.AppSubURL + "/")
  1179. return
  1180. }
  1181. ctx.Data["IsActivateFailed"] = true
  1182. ctx.HTML(200, TplActivate)
  1183. }
  1184. // ActivateEmail render the activate email page
  1185. func ActivateEmail(ctx *context.Context) {
  1186. code := ctx.Query("code")
  1187. emailStr := ctx.Query("email")
  1188. // Verify code.
  1189. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  1190. if err := email.Activate(); err != nil {
  1191. ctx.ServerError("ActivateEmail", err)
  1192. }
  1193. log.Trace("Email activated: %s", email.Email)
  1194. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  1195. if u, err := models.GetUserByID(email.UID); err != nil {
  1196. log.Warn("GetUserByID: %d", email.UID)
  1197. } else {
  1198. // Allow user to validate more emails
  1199. _ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName)
  1200. }
  1201. }
  1202. // FIXME: e-mail verification does not require the user to be logged in,
  1203. // so this could be redirecting to the login page.
  1204. // Should users be logged in automatically here? (consider 2FA requirements, etc.)
  1205. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  1206. }
  1207. // ForgotPasswd render the forget pasword page
  1208. func ForgotPasswd(ctx *context.Context) {
  1209. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  1210. if setting.MailService == nil {
  1211. ctx.Data["IsResetDisable"] = true
  1212. ctx.HTML(200, tplForgotPassword)
  1213. return
  1214. }
  1215. email := ctx.Query("email")
  1216. ctx.Data["Email"] = email
  1217. ctx.Data["IsResetRequest"] = true
  1218. ctx.HTML(200, tplForgotPassword)
  1219. }
  1220. // ForgotPasswdPost response for forget password request
  1221. func ForgotPasswdPost(ctx *context.Context) {
  1222. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  1223. if setting.MailService == nil {
  1224. ctx.NotFound("ForgotPasswdPost", nil)
  1225. return
  1226. }
  1227. ctx.Data["IsResetRequest"] = true
  1228. email := ctx.Query("email")
  1229. ctx.Data["Email"] = email
  1230. u, err := models.GetUserByMainEmail(email)
  1231. if err != nil {
  1232. if models.IsErrUserNotExist(err) {
  1233. ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
  1234. ctx.Data["IsResetSent"] = false
  1235. if used, _ := models.IsEmailUsed(email); used {
  1236. ctx.RenderWithErr(ctx.Tr("auth.email_not_main"), tplForgotPassword, nil)
  1237. } else {
  1238. ctx.RenderWithErr(ctx.Tr("auth.email_not_right"), tplForgotPassword, nil)
  1239. }
  1240. return
  1241. }
  1242. ctx.ServerError("user.ResetPasswd(check existence)", err)
  1243. return
  1244. }
  1245. if !u.IsLocal() && !u.IsOAuth2() {
  1246. ctx.Data["Err_Email"] = true
  1247. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  1248. return
  1249. }
  1250. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  1251. ctx.Data["ResendLimited"] = true
  1252. ctx.HTML(200, tplForgotPassword)
  1253. return
  1254. }
  1255. mailer.SendResetPasswordMail(ctx.Locale, u)
  1256. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  1257. log.Error("Set cache(MailResendLimit) fail: %v", err)
  1258. }
  1259. ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
  1260. ctx.Data["IsResetSent"] = true
  1261. ctx.HTML(200, tplForgotPassword)
  1262. }
  1263. func commonResetPassword(ctx *context.Context) (*models.User, *models.TwoFactor) {
  1264. code := ctx.Query("code")
  1265. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  1266. ctx.Data["Code"] = code
  1267. if nil != ctx.User {
  1268. ctx.Data["user_signed_in"] = true
  1269. }
  1270. if len(code) == 0 {
  1271. ctx.Flash.Error(ctx.Tr("auth.invalid_code"))
  1272. return nil, nil
  1273. }
  1274. // Fail early, don't frustrate the user
  1275. u := models.VerifyUserActiveCode(code)
  1276. if u == nil {
  1277. ctx.Flash.Error(ctx.Tr("auth.invalid_code"))
  1278. return nil, nil
  1279. }
  1280. twofa, err := models.GetTwoFactorByUID(u.ID)
  1281. if err != nil {
  1282. if !models.IsErrTwoFactorNotEnrolled(err) {
  1283. ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error())
  1284. return nil, nil
  1285. }
  1286. } else {
  1287. ctx.Data["has_two_factor"] = true
  1288. ctx.Data["scratch_code"] = ctx.QueryBool("scratch_code")
  1289. }
  1290. // Show the user that they are affecting the account that they intended to
  1291. ctx.Data["user_email"] = u.Email
  1292. if nil != ctx.User && u.ID != ctx.User.ID {
  1293. ctx.Flash.Error(ctx.Tr("auth.reset_password_wrong_user", ctx.User.Email, u.Email))
  1294. return nil, nil
  1295. }
  1296. return u, twofa
  1297. }
  1298. // ResetPasswd render the account recovery page
  1299. func ResetPasswd(ctx *context.Context) {
  1300. ctx.Data["IsResetForm"] = true
  1301. commonResetPassword(ctx)
  1302. if ctx.Written() {
  1303. return
  1304. }
  1305. ctx.HTML(200, tplResetPassword)
  1306. }
  1307. // ResetPasswdPost response from account recovery request
  1308. func ResetPasswdPost(ctx *context.Context) {
  1309. u, twofa := commonResetPassword(ctx)
  1310. if ctx.Written() {
  1311. return
  1312. }
  1313. if u == nil {
  1314. // Flash error has been set
  1315. ctx.HTML(200, tplResetPassword)
  1316. return
  1317. }
  1318. // Validate password length.
  1319. passwd := ctx.Query("password")
  1320. if len(passwd) < setting.MinPasswordLength {
  1321. ctx.Data["IsResetForm"] = true
  1322. ctx.Data["Err_Password"] = true
  1323. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  1324. return
  1325. } else if !password.IsComplexEnough(passwd) {
  1326. ctx.Data["IsResetForm"] = true
  1327. ctx.Data["Err_Password"] = true
  1328. ctx.RenderWithErr(password.BuildComplexityError(ctx), tplResetPassword, nil)
  1329. return
  1330. }
  1331. // Handle two-factor
  1332. regenerateScratchToken := false
  1333. if twofa != nil {
  1334. if ctx.QueryBool("scratch_code") {
  1335. if !twofa.VerifyScratchToken(ctx.Query("token")) {
  1336. ctx.Data["IsResetForm"] = true
  1337. ctx.Data["Err_Token"] = true
  1338. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplResetPassword, nil)
  1339. return
  1340. }
  1341. regenerateScratchToken = true
  1342. } else {
  1343. passcode := ctx.Query("passcode")
  1344. ok, err := twofa.ValidateTOTP(passcode)
  1345. if err != nil {
  1346. ctx.Error(http.StatusInternalServerError, "ValidateTOTP", err.Error())
  1347. return
  1348. }
  1349. if !ok || twofa.LastUsedPasscode == passcode {
  1350. ctx.Data["IsResetForm"] = true
  1351. ctx.Data["Err_Passcode"] = true
  1352. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplResetPassword, nil)
  1353. return
  1354. }
  1355. twofa.LastUsedPasscode = passcode
  1356. if err = models.UpdateTwoFactor(twofa); err != nil {
  1357. ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err)
  1358. return
  1359. }
  1360. }
  1361. }
  1362. var err error
  1363. if u.Rands, err = models.GetUserSalt(); err != nil {
  1364. ctx.ServerError("UpdateUser", err)
  1365. return
  1366. }
  1367. if u.Salt, err = models.GetUserSalt(); err != nil {
  1368. ctx.ServerError("UpdateUser", err)
  1369. return
  1370. }
  1371. u.HashPassword(passwd)
  1372. u.MustChangePassword = false
  1373. if err := models.UpdateUserCols(u, "must_change_password", "passwd", "rands", "salt"); err != nil {
  1374. ctx.ServerError("UpdateUser", err)
  1375. return
  1376. }
  1377. log.Trace("User password reset: %s", u.Name)
  1378. ctx.Data["IsResetFailed"] = true
  1379. remember := len(ctx.Query("remember")) != 0
  1380. if regenerateScratchToken {
  1381. // Invalidate the scratch token.
  1382. _, err = twofa.GenerateScratchToken()
  1383. if err != nil {
  1384. ctx.ServerError("UserSignIn", err)
  1385. return
  1386. }
  1387. if err = models.UpdateTwoFactor(twofa); err != nil {
  1388. ctx.ServerError("UserSignIn", err)
  1389. return
  1390. }
  1391. handleSignInFull(ctx, u, remember, false)
  1392. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  1393. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  1394. return
  1395. }
  1396. handleSignInFull(ctx, u, remember, true)
  1397. }
  1398. // MustChangePassword renders the page to change a user's password
  1399. func MustChangePassword(ctx *context.Context) {
  1400. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  1401. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
  1402. ctx.HTML(200, tplMustChangePassword)
  1403. }
  1404. // MustChangePasswordPost response for updating a user's password after his/her
  1405. // account was created by an admin
  1406. func MustChangePasswordPost(ctx *context.Context, cpt *captcha.Captcha, form auth.MustChangePasswordForm) {
  1407. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  1408. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
  1409. if ctx.HasError() {
  1410. ctx.HTML(200, tplMustChangePassword)
  1411. return
  1412. }
  1413. u := ctx.User
  1414. // Make sure only requests for users who are eligible to change their password via
  1415. // this method passes through
  1416. if !u.MustChangePassword {
  1417. ctx.ServerError("MustUpdatePassword", errors.New("cannot update password.. Please visit the settings page"))
  1418. return
  1419. }
  1420. if form.Password != form.Retype {
  1421. ctx.Data["Err_Password"] = true
  1422. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplMustChangePassword, &form)
  1423. return
  1424. }
  1425. if len(form.Password) < setting.MinPasswordLength {
  1426. ctx.Data["Err_Password"] = true
  1427. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplMustChangePassword, &form)
  1428. return
  1429. }
  1430. var err error
  1431. if u.Salt, err = models.GetUserSalt(); err != nil {
  1432. ctx.ServerError("UpdateUser", err)
  1433. return
  1434. }
  1435. u.HashPassword(form.Password)
  1436. u.MustChangePassword = false
  1437. if err := models.UpdateUserCols(u, "must_change_password", "passwd", "salt"); err != nil {
  1438. ctx.ServerError("UpdateUser", err)
  1439. return
  1440. }
  1441. ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
  1442. log.Trace("User updated password: %s", u.Name)
  1443. if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !util.IsExternalURL(redirectTo) {
  1444. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  1445. ctx.RedirectToFirst(redirectTo)
  1446. return
  1447. }
  1448. ctx.Redirect(setting.AppSubURL + "/")
  1449. }
  1450. func CreateSlideImageInfo(ctx *context.Context, slideImage *slideimage.SlideImage) {
  1451. id, _, _ := slideImage.CreateCode()
  1452. ctx.JSON(http.StatusOK, models.BaseMessage{0, id})
  1453. }
  1454. func VerifySlideImage(ctx *context.Context, slideImage *slideimage.SlideImage, form auth.SlideImageForm) {
  1455. if slideImage.Verify(form.SlideID, form.X) {
  1456. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  1457. } else {
  1458. ctx.JSON(http.StatusOK, models.BaseErrorMessage(""))
  1459. }
  1460. }
  1461. func BindPhone(ctx *context.Context, form auth.PhoneNumberCodeForm) {
  1462. if strings.TrimSpace(form.PhoneNumber) != "" && strings.TrimSpace(form.VerifyCode) != "" && phoneService.IsVerifyCodeRight(strings.TrimSpace(form.PhoneNumber), strings.TrimSpace(form.VerifyCode)) {
  1463. ctx.User.PhoneNumber = strings.TrimSpace(form.PhoneNumber)
  1464. if err := models.UpdateUserSetting(ctx.User); err != nil {
  1465. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.bind_phone_fail")))
  1466. return
  1467. }
  1468. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  1469. return
  1470. }
  1471. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.verify_code_fail")))
  1472. }
  1473. func SendVerifyCode(ctx *context.Context, slideImage *slideimage.SlideImage, form auth.PhoneNumberForm) {
  1474. phoneNumber := strings.TrimSpace(form.PhoneNumber)
  1475. if !phone.IsValidPhoneNumber(phoneNumber) {
  1476. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.format_err")))
  1477. return
  1478. }
  1479. hasManual, err := slideImage.VerifyManual(form.SlideID)
  1480. if err != nil {
  1481. log.Warn("redis err", err)
  1482. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1483. return
  1484. }
  1485. if !hasManual {
  1486. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1487. return
  1488. }
  1489. if !ctx.IsSigned {
  1490. has, err := models.IsUserByPhoneNumberExist(phoneNumber)
  1491. if err != nil {
  1492. log.Warn("sql err", err)
  1493. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1494. return
  1495. }
  1496. if form.IsSignUp { //注册
  1497. if has {
  1498. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.already_register")))
  1499. return
  1500. }
  1501. } else { //手机号验证码登录
  1502. if !has {
  1503. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.not_register")))
  1504. return
  1505. }
  1506. }
  1507. } else { //修改手机号
  1508. u, err := models.GetUserByPhoneNumber(phoneNumber)
  1509. if err != nil && !models.IsErrUserNotExist(err) {
  1510. log.Warn("sql err", err)
  1511. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1512. return
  1513. }
  1514. if u != nil {
  1515. if u.ID == ctx.User.ID { //没有修改手机号
  1516. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.not_modify")))
  1517. return
  1518. } else { //修改的手机已经被别的用户注册
  1519. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.already_register")))
  1520. return
  1521. }
  1522. }
  1523. }
  1524. redisConn := labelmsg.Get()
  1525. defer redisConn.Close()
  1526. sendTimes, err := phoneService.GetPhoneNumberSendTimes(redisConn, phoneNumber)
  1527. if err != nil {
  1528. log.Warn("redis err", err)
  1529. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1530. return
  1531. }
  1532. if sendTimes >= setting.PhoneService.MaxRetryTimes {
  1533. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.max_times", setting.PhoneService.MaxRetryTimes)))
  1534. return
  1535. }
  1536. ttl, err := phoneService.GetPhoneCodeTTL(redisConn, phoneNumber)
  1537. if err != nil {
  1538. log.Warn("redis err", err)
  1539. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1540. return
  1541. }
  1542. if setting.PhoneService.CodeTimeout-ttl < setting.PhoneService.RetryInterval {
  1543. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.too_fast")))
  1544. return
  1545. }
  1546. err = phoneService.SendVerifyCode(redisConn, phoneNumber)
  1547. if err != nil {
  1548. log.Warn("send code or redis err", err)
  1549. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("phone.query_err")))
  1550. return
  1551. }
  1552. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  1553. }