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

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