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