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

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