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

auth.go 65 kB

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