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 59 kB

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