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