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

auth.go 64 kB

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