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

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