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.

login_source.go 24 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that 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
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
11 years ago
11 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that 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
11 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that 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
11 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that 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
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
6 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 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 models
  6. import (
  7. "crypto/tls"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net/smtp"
  12. "net/textproto"
  13. "strings"
  14. "code.gitea.io/gitea/modules/auth/cloudbrain"
  15. "code.gitea.io/gitea/modules/auth/ldap"
  16. "code.gitea.io/gitea/modules/auth/oauth2"
  17. "code.gitea.io/gitea/modules/auth/pam"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/timeutil"
  21. gouuid "github.com/satori/go.uuid"
  22. "github.com/unknwon/com"
  23. "xorm.io/xorm"
  24. "xorm.io/xorm/convert"
  25. )
  26. // LoginType represents an login type.
  27. type LoginType int
  28. // Note: new type must append to the end of list to maintain compatibility.
  29. const (
  30. LoginNoType LoginType = iota
  31. LoginPlain // 1
  32. LoginLDAP // 2
  33. LoginSMTP // 3
  34. LoginPAM // 4
  35. LoginDLDAP // 5
  36. LoginOAuth2 // 6
  37. LoginSSPI // 7
  38. )
  39. // LoginNames contains the name of LoginType values.
  40. var LoginNames = map[LoginType]string{
  41. LoginLDAP: "LDAP (via BindDN)",
  42. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  43. LoginSMTP: "SMTP",
  44. LoginPAM: "PAM",
  45. LoginOAuth2: "OAuth2",
  46. LoginSSPI: "SPNEGO with SSPI",
  47. }
  48. // SecurityProtocolNames contains the name of SecurityProtocol values.
  49. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  50. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  51. ldap.SecurityProtocolLDAPS: "LDAPS",
  52. ldap.SecurityProtocolStartTLS: "StartTLS",
  53. }
  54. // Ensure structs implemented interface.
  55. var (
  56. _ convert.Conversion = &LDAPConfig{}
  57. _ convert.Conversion = &SMTPConfig{}
  58. _ convert.Conversion = &PAMConfig{}
  59. _ convert.Conversion = &OAuth2Config{}
  60. _ convert.Conversion = &SSPIConfig{}
  61. )
  62. // LDAPConfig holds configuration for LDAP login source.
  63. type LDAPConfig struct {
  64. *ldap.Source
  65. }
  66. // FromDB fills up a LDAPConfig from serialized format.
  67. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  68. return json.Unmarshal(bs, &cfg)
  69. }
  70. // ToDB exports a LDAPConfig to a serialized format.
  71. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  72. return json.Marshal(cfg)
  73. }
  74. // SecurityProtocolName returns the name of configured security
  75. // protocol.
  76. func (cfg *LDAPConfig) SecurityProtocolName() string {
  77. return SecurityProtocolNames[cfg.SecurityProtocol]
  78. }
  79. // SMTPConfig holds configuration for the SMTP login source.
  80. type SMTPConfig struct {
  81. Auth string
  82. Host string
  83. Port int
  84. AllowedDomains string `xorm:"TEXT"`
  85. TLS bool
  86. SkipVerify bool
  87. }
  88. // FromDB fills up an SMTPConfig from serialized format.
  89. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  90. return json.Unmarshal(bs, cfg)
  91. }
  92. // ToDB exports an SMTPConfig to a serialized format.
  93. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  94. return json.Marshal(cfg)
  95. }
  96. // PAMConfig holds configuration for the PAM login source.
  97. type PAMConfig struct {
  98. ServiceName string // pam service (e.g. system-auth)
  99. }
  100. // FromDB fills up a PAMConfig from serialized format.
  101. func (cfg *PAMConfig) FromDB(bs []byte) error {
  102. return json.Unmarshal(bs, &cfg)
  103. }
  104. // ToDB exports a PAMConfig to a serialized format.
  105. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  106. return json.Marshal(cfg)
  107. }
  108. // OAuth2Config holds configuration for the OAuth2 login source.
  109. type OAuth2Config struct {
  110. Provider string
  111. ClientID string
  112. ClientSecret string
  113. OpenIDConnectAutoDiscoveryURL string
  114. CustomURLMapping *oauth2.CustomURLMapping
  115. }
  116. // FromDB fills up an OAuth2Config from serialized format.
  117. func (cfg *OAuth2Config) FromDB(bs []byte) error {
  118. return json.Unmarshal(bs, cfg)
  119. }
  120. // ToDB exports an SMTPConfig to a serialized format.
  121. func (cfg *OAuth2Config) ToDB() ([]byte, error) {
  122. return json.Marshal(cfg)
  123. }
  124. // SSPIConfig holds configuration for SSPI single sign-on.
  125. type SSPIConfig struct {
  126. AutoCreateUsers bool
  127. AutoActivateUsers bool
  128. StripDomainNames bool
  129. SeparatorReplacement string
  130. DefaultLanguage string
  131. }
  132. // FromDB fills up an SSPIConfig from serialized format.
  133. func (cfg *SSPIConfig) FromDB(bs []byte) error {
  134. return json.Unmarshal(bs, cfg)
  135. }
  136. // ToDB exports an SSPIConfig to a serialized format.
  137. func (cfg *SSPIConfig) ToDB() ([]byte, error) {
  138. return json.Marshal(cfg)
  139. }
  140. // LoginSource represents an external way for authorizing users.
  141. type LoginSource struct {
  142. ID int64 `xorm:"pk autoincr"`
  143. Type LoginType
  144. Name string `xorm:"UNIQUE"`
  145. IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
  146. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  147. Cfg convert.Conversion `xorm:"TEXT"`
  148. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  149. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  150. }
  151. // Cell2Int64 converts a xorm.Cell type to int64,
  152. // and handles possible irregular cases.
  153. func Cell2Int64(val xorm.Cell) int64 {
  154. switch (*val).(type) {
  155. case []uint8:
  156. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  157. return com.StrTo(string((*val).([]uint8))).MustInt64()
  158. }
  159. return (*val).(int64)
  160. }
  161. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  162. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  163. if colName == "type" {
  164. switch LoginType(Cell2Int64(val)) {
  165. case LoginLDAP, LoginDLDAP:
  166. source.Cfg = new(LDAPConfig)
  167. case LoginSMTP:
  168. source.Cfg = new(SMTPConfig)
  169. case LoginPAM:
  170. source.Cfg = new(PAMConfig)
  171. case LoginOAuth2:
  172. source.Cfg = new(OAuth2Config)
  173. case LoginSSPI:
  174. source.Cfg = new(SSPIConfig)
  175. default:
  176. panic("unrecognized login source type: " + com.ToStr(*val))
  177. }
  178. }
  179. }
  180. // TypeName return name of this login source type.
  181. func (source *LoginSource) TypeName() string {
  182. return LoginNames[source.Type]
  183. }
  184. // IsLDAP returns true of this source is of the LDAP type.
  185. func (source *LoginSource) IsLDAP() bool {
  186. return source.Type == LoginLDAP
  187. }
  188. // IsDLDAP returns true of this source is of the DLDAP type.
  189. func (source *LoginSource) IsDLDAP() bool {
  190. return source.Type == LoginDLDAP
  191. }
  192. // IsSMTP returns true of this source is of the SMTP type.
  193. func (source *LoginSource) IsSMTP() bool {
  194. return source.Type == LoginSMTP
  195. }
  196. // IsPAM returns true of this source is of the PAM type.
  197. func (source *LoginSource) IsPAM() bool {
  198. return source.Type == LoginPAM
  199. }
  200. // IsOAuth2 returns true of this source is of the OAuth2 type.
  201. func (source *LoginSource) IsOAuth2() bool {
  202. return source.Type == LoginOAuth2
  203. }
  204. // IsSSPI returns true of this source is of the SSPI type.
  205. func (source *LoginSource) IsSSPI() bool {
  206. return source.Type == LoginSSPI
  207. }
  208. // HasTLS returns true of this source supports TLS.
  209. func (source *LoginSource) HasTLS() bool {
  210. return ((source.IsLDAP() || source.IsDLDAP()) &&
  211. source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
  212. source.IsSMTP()
  213. }
  214. // UseTLS returns true of this source is configured to use TLS.
  215. func (source *LoginSource) UseTLS() bool {
  216. switch source.Type {
  217. case LoginLDAP, LoginDLDAP:
  218. return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
  219. case LoginSMTP:
  220. return source.SMTP().TLS
  221. }
  222. return false
  223. }
  224. // SkipVerify returns true if this source is configured to skip SSL
  225. // verification.
  226. func (source *LoginSource) SkipVerify() bool {
  227. switch source.Type {
  228. case LoginLDAP, LoginDLDAP:
  229. return source.LDAP().SkipVerify
  230. case LoginSMTP:
  231. return source.SMTP().SkipVerify
  232. }
  233. return false
  234. }
  235. // LDAP returns LDAPConfig for this source, if of LDAP type.
  236. func (source *LoginSource) LDAP() *LDAPConfig {
  237. return source.Cfg.(*LDAPConfig)
  238. }
  239. // SMTP returns SMTPConfig for this source, if of SMTP type.
  240. func (source *LoginSource) SMTP() *SMTPConfig {
  241. return source.Cfg.(*SMTPConfig)
  242. }
  243. // PAM returns PAMConfig for this source, if of PAM type.
  244. func (source *LoginSource) PAM() *PAMConfig {
  245. return source.Cfg.(*PAMConfig)
  246. }
  247. // OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
  248. func (source *LoginSource) OAuth2() *OAuth2Config {
  249. return source.Cfg.(*OAuth2Config)
  250. }
  251. // SSPI returns SSPIConfig for this source, if of SSPI type.
  252. func (source *LoginSource) SSPI() *SSPIConfig {
  253. return source.Cfg.(*SSPIConfig)
  254. }
  255. // CreateLoginSource inserts a LoginSource in the DB if not already
  256. // existing with the given name.
  257. func CreateLoginSource(source *LoginSource) error {
  258. has, err := x.Get(&LoginSource{Name: source.Name})
  259. if err != nil {
  260. return err
  261. } else if has {
  262. return ErrLoginSourceAlreadyExist{source.Name}
  263. }
  264. // Synchronization is only aviable with LDAP for now
  265. if !source.IsLDAP() {
  266. source.IsSyncEnabled = false
  267. }
  268. _, err = x.Insert(source)
  269. if err == nil && source.IsOAuth2() && source.IsActived {
  270. oAuth2Config := source.OAuth2()
  271. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  272. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  273. if err != nil {
  274. // remove the LoginSource in case of errors while registering OAuth2 providers
  275. if _, err := x.Delete(source); err != nil {
  276. log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  277. }
  278. return err
  279. }
  280. }
  281. return err
  282. }
  283. // LoginSources returns a slice of all login sources found in DB.
  284. func LoginSources() ([]*LoginSource, error) {
  285. auths := make([]*LoginSource, 0, 6)
  286. return auths, x.Find(&auths)
  287. }
  288. // LoginSourcesByType returns all sources of the specified type
  289. func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) {
  290. sources := make([]*LoginSource, 0, 1)
  291. if err := x.Where("type = ?", loginType).Find(&sources); err != nil {
  292. return nil, err
  293. }
  294. return sources, nil
  295. }
  296. // ActiveLoginSources returns all active sources of the specified type
  297. func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) {
  298. sources := make([]*LoginSource, 0, 1)
  299. if err := x.Where("is_actived = ? and type = ?", true, loginType).Find(&sources); err != nil {
  300. return nil, err
  301. }
  302. return sources, nil
  303. }
  304. // IsSSPIEnabled returns true if there is at least one activated login
  305. // source of type LoginSSPI
  306. func IsSSPIEnabled() bool {
  307. if !HasEngine {
  308. return false
  309. }
  310. sources, err := ActiveLoginSources(LoginSSPI)
  311. if err != nil {
  312. log.Error("ActiveLoginSources: %v", err)
  313. return false
  314. }
  315. return len(sources) > 0
  316. }
  317. // GetLoginSourceByID returns login source by given ID.
  318. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  319. source := new(LoginSource)
  320. has, err := x.ID(id).Get(source)
  321. if err != nil {
  322. return nil, err
  323. } else if !has {
  324. return nil, ErrLoginSourceNotExist{id}
  325. }
  326. return source, nil
  327. }
  328. // UpdateSource updates a LoginSource record in DB.
  329. func UpdateSource(source *LoginSource) error {
  330. var originalLoginSource *LoginSource
  331. if source.IsOAuth2() {
  332. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  333. var err error
  334. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  335. return err
  336. }
  337. }
  338. _, err := x.ID(source.ID).AllCols().Update(source)
  339. if err == nil && source.IsOAuth2() && source.IsActived {
  340. oAuth2Config := source.OAuth2()
  341. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  342. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  343. if err != nil {
  344. // restore original values since we cannot update the provider it self
  345. if _, err := x.ID(source.ID).AllCols().Update(originalLoginSource); err != nil {
  346. log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  347. }
  348. return err
  349. }
  350. }
  351. return err
  352. }
  353. // DeleteSource deletes a LoginSource record in DB.
  354. func DeleteSource(source *LoginSource) error {
  355. count, err := x.Count(&User{LoginSource: source.ID})
  356. if err != nil {
  357. return err
  358. } else if count > 0 {
  359. return ErrLoginSourceInUse{source.ID}
  360. }
  361. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  362. if err != nil {
  363. return err
  364. } else if count > 0 {
  365. return ErrLoginSourceInUse{source.ID}
  366. }
  367. if source.IsOAuth2() {
  368. oauth2.RemoveProvider(source.Name)
  369. }
  370. _, err = x.ID(source.ID).Delete(new(LoginSource))
  371. return err
  372. }
  373. // CountLoginSources returns number of login sources.
  374. func CountLoginSources() int64 {
  375. count, _ := x.Count(new(LoginSource))
  376. return count
  377. }
  378. // .____ ________ _____ __________
  379. // | | \______ \ / _ \\______ \
  380. // | | | | \ / /_\ \| ___/
  381. // | |___ | ` \/ | \ |
  382. // |_______ \/_______ /\____|__ /____|
  383. // \/ \/ \/
  384. func composeFullName(firstname, surname, username string) string {
  385. switch {
  386. case len(firstname) == 0 && len(surname) == 0:
  387. return username
  388. case len(firstname) == 0:
  389. return surname
  390. case len(surname) == 0:
  391. return firstname
  392. default:
  393. return firstname + " " + surname
  394. }
  395. }
  396. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  397. // and create a local user if success when enabled.
  398. func LoginViaLDAP(user *User, login, password string, source *LoginSource) (*User, error) {
  399. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  400. if sr == nil {
  401. // User not in LDAP, do nothing
  402. return nil, ErrUserNotExist{0, login, 0}
  403. }
  404. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
  405. // Update User admin flag if exist
  406. if isExist, err := IsUserExist(0, sr.Username); err != nil {
  407. return nil, err
  408. } else if isExist {
  409. if user == nil {
  410. user, err = GetUserByName(sr.Username)
  411. if err != nil {
  412. return nil, err
  413. }
  414. }
  415. if user != nil && !user.ProhibitLogin {
  416. cols := make([]string, 0)
  417. if len(source.LDAP().AdminFilter) > 0 && user.IsAdmin != sr.IsAdmin {
  418. // Change existing admin flag only if AdminFilter option is set
  419. user.IsAdmin = sr.IsAdmin
  420. cols = append(cols, "is_admin")
  421. }
  422. if !user.IsAdmin && len(source.LDAP().RestrictedFilter) > 0 && user.IsRestricted != sr.IsRestricted {
  423. // Change existing restricted flag only if RestrictedFilter option is set
  424. user.IsRestricted = sr.IsRestricted
  425. cols = append(cols, "is_restricted")
  426. }
  427. if len(cols) > 0 {
  428. err = UpdateUserCols(user, cols...)
  429. if err != nil {
  430. return nil, err
  431. }
  432. }
  433. }
  434. }
  435. if user != nil {
  436. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  437. return user, RewriteAllPublicKeys()
  438. }
  439. return user, nil
  440. }
  441. // Fallback.
  442. if len(sr.Username) == 0 {
  443. sr.Username = login
  444. }
  445. if len(sr.Mail) == 0 {
  446. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  447. }
  448. user = &User{
  449. LowerName: strings.ToLower(sr.Username),
  450. Name: sr.Username,
  451. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  452. Email: sr.Mail,
  453. LoginType: source.Type,
  454. LoginSource: source.ID,
  455. LoginName: login,
  456. IsActive: true,
  457. IsAdmin: sr.IsAdmin,
  458. IsRestricted: sr.IsRestricted,
  459. }
  460. err := CreateUser(user)
  461. if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  462. err = RewriteAllPublicKeys()
  463. }
  464. return user, err
  465. }
  466. // _________ __________________________
  467. // / _____/ / \__ ___/\______ \
  468. // \_____ \ / \ / \| | | ___/
  469. // / \/ Y \ | | |
  470. // /_______ /\____|__ /____| |____|
  471. // \/ \/
  472. type smtpLoginAuth struct {
  473. username, password string
  474. }
  475. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  476. return "LOGIN", []byte(auth.username), nil
  477. }
  478. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  479. if more {
  480. switch string(fromServer) {
  481. case "Username:":
  482. return []byte(auth.username), nil
  483. case "Password:":
  484. return []byte(auth.password), nil
  485. }
  486. }
  487. return nil, nil
  488. }
  489. // SMTP authentication type names.
  490. const (
  491. SMTPPlain = "PLAIN"
  492. SMTPLogin = "LOGIN"
  493. )
  494. // SMTPAuths contains available SMTP authentication type names.
  495. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  496. // SMTPAuth performs an SMTP authentication.
  497. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  498. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  499. if err != nil {
  500. return err
  501. }
  502. defer c.Close()
  503. if err = c.Hello("gogs"); err != nil {
  504. return err
  505. }
  506. if cfg.TLS {
  507. if ok, _ := c.Extension("STARTTLS"); ok {
  508. if err = c.StartTLS(&tls.Config{
  509. InsecureSkipVerify: cfg.SkipVerify,
  510. ServerName: cfg.Host,
  511. }); err != nil {
  512. return err
  513. }
  514. } else {
  515. return errors.New("SMTP server unsupports TLS")
  516. }
  517. }
  518. if ok, _ := c.Extension("AUTH"); ok {
  519. return c.Auth(a)
  520. }
  521. return ErrUnsupportedLoginType
  522. }
  523. // LoginViaSMTP queries if login/password is valid against the SMTP,
  524. // and create a local user if success when enabled.
  525. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig) (*User, error) {
  526. // Verify allowed domains.
  527. if len(cfg.AllowedDomains) > 0 {
  528. idx := strings.Index(login, "@")
  529. if idx == -1 {
  530. return nil, ErrUserNotExist{0, login, 0}
  531. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  532. return nil, ErrUserNotExist{0, login, 0}
  533. }
  534. }
  535. var auth smtp.Auth
  536. if cfg.Auth == SMTPPlain {
  537. auth = smtp.PlainAuth("", login, password, cfg.Host)
  538. } else if cfg.Auth == SMTPLogin {
  539. auth = &smtpLoginAuth{login, password}
  540. } else {
  541. return nil, errors.New("Unsupported SMTP auth type")
  542. }
  543. if err := SMTPAuth(auth, cfg); err != nil {
  544. // Check standard error format first,
  545. // then fallback to worse case.
  546. tperr, ok := err.(*textproto.Error)
  547. if (ok && tperr.Code == 535) ||
  548. strings.Contains(err.Error(), "Username and Password not accepted") {
  549. return nil, ErrUserNotExist{0, login, 0}
  550. }
  551. return nil, err
  552. }
  553. if user != nil {
  554. return user, nil
  555. }
  556. username := login
  557. idx := strings.Index(login, "@")
  558. if idx > -1 {
  559. username = login[:idx]
  560. }
  561. user = &User{
  562. LowerName: strings.ToLower(username),
  563. Name: strings.ToLower(username),
  564. Email: login,
  565. Passwd: password,
  566. LoginType: LoginSMTP,
  567. LoginSource: sourceID,
  568. LoginName: login,
  569. IsActive: true,
  570. }
  571. return user, CreateUser(user)
  572. }
  573. // __________ _____ _____
  574. // \______ \/ _ \ / \
  575. // | ___/ /_\ \ / \ / \
  576. // | | / | \/ Y \
  577. // |____| \____|__ /\____|__ /
  578. // \/ \/
  579. // LoginViaPAM queries if login/password is valid against the PAM,
  580. // and create a local user if success when enabled.
  581. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig) (*User, error) {
  582. pamLogin, err := pam.Auth(cfg.ServiceName, login, password)
  583. if err != nil {
  584. if strings.Contains(err.Error(), "Authentication failure") {
  585. return nil, ErrUserNotExist{0, login, 0}
  586. }
  587. return nil, err
  588. }
  589. if user != nil {
  590. return user, nil
  591. }
  592. // Allow PAM sources with `@` in their name, like from Active Directory
  593. username := pamLogin
  594. idx := strings.Index(pamLogin, "@")
  595. if idx > -1 {
  596. username = pamLogin[:idx]
  597. }
  598. user = &User{
  599. LowerName: strings.ToLower(username),
  600. Name: username,
  601. Email: pamLogin,
  602. Passwd: password,
  603. LoginType: LoginPAM,
  604. LoginSource: sourceID,
  605. LoginName: login, // This is what the user typed in
  606. IsActive: true,
  607. }
  608. return user, CreateUser(user)
  609. }
  610. // ExternalUserLogin attempts a login using external source types.
  611. func ExternalUserLogin(user *User, login, password string, source *LoginSource) (*User, error) {
  612. if !source.IsActived {
  613. return nil, ErrLoginSourceNotActived
  614. }
  615. var err error
  616. switch source.Type {
  617. case LoginLDAP, LoginDLDAP:
  618. user, err = LoginViaLDAP(user, login, password, source)
  619. case LoginSMTP:
  620. user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig))
  621. case LoginPAM:
  622. user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig))
  623. default:
  624. return nil, ErrUnsupportedLoginType
  625. }
  626. if err != nil {
  627. return nil, err
  628. }
  629. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  630. // user could be hint to resend confirm email.
  631. if user.ProhibitLogin {
  632. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  633. }
  634. return user, nil
  635. }
  636. // UserSignIn validates user name and password.
  637. func UserSignIn(username, password string) (*User, error) {
  638. var user *User
  639. if strings.Contains(username, "@") {
  640. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  641. // check same email
  642. cnt, err := x.Count(user)
  643. if err != nil {
  644. return nil, err
  645. }
  646. if cnt > 1 {
  647. return nil, ErrEmailAlreadyUsed{
  648. Email: user.Email,
  649. }
  650. }
  651. } else {
  652. trimmedUsername := strings.TrimSpace(username)
  653. if len(trimmedUsername) == 0 {
  654. return nil, ErrUserNotExist{0, username, 0}
  655. }
  656. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  657. }
  658. hasUser, err := x.Get(user)
  659. if err != nil {
  660. return nil, err
  661. }
  662. if hasUser {
  663. if user.CloudBrainValidated {
  664. _, _, err := cloudbrain.UserValidate(username, password)
  665. if err != nil {
  666. log.Error("cloudbrain.UserValidate(%s) failed: %v", username, err)
  667. return nil, err
  668. } else {
  669. return user, nil
  670. }
  671. }
  672. switch user.LoginType {
  673. case LoginNoType, LoginPlain, LoginOAuth2:
  674. if user.IsPasswordSet() && user.ValidatePassword(password) {
  675. // Update password hash if server password hash algorithm have changed
  676. if user.PasswdHashAlgo != setting.PasswordHashAlgo {
  677. user.HashPassword(password)
  678. if err := UpdateUserCols(user, "passwd", "passwd_hash_algo"); err != nil {
  679. return nil, err
  680. }
  681. }
  682. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  683. // user could be hint to resend confirm email.
  684. if user.ProhibitLogin {
  685. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  686. }
  687. return user, nil
  688. }
  689. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  690. default:
  691. var source LoginSource
  692. hasSource, err := x.ID(user.LoginSource).Get(&source)
  693. if err != nil {
  694. return nil, err
  695. } else if !hasSource {
  696. return nil, ErrLoginSourceNotExist{user.LoginSource}
  697. }
  698. return ExternalUserLogin(user, user.LoginName, password, &source)
  699. }
  700. } else {
  701. email, token, err := cloudbrain.UserValidate(username, password)
  702. if err == nil {
  703. if email == "" {
  704. email = genRandEmail()
  705. }
  706. log.Info(email)
  707. u := &User{
  708. Name: username,
  709. Email: email,
  710. Passwd: password,
  711. IsActive: true,
  712. CloudBrainValidated: true,
  713. Token: token,
  714. }
  715. if err := CreateUser(u); err != nil {
  716. log.Error("CreateUser(%s) failed: %v", username, err)
  717. return nil, err
  718. }
  719. log.Info("Account created: %s", u.Name)
  720. return u, nil
  721. }
  722. log.Info("cloudbrain.UserValidate(%s) failed: %v", username, err)
  723. }
  724. sources := make([]*LoginSource, 0, 5)
  725. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  726. return nil, err
  727. }
  728. for _, source := range sources {
  729. if source.IsOAuth2() || source.IsSSPI() {
  730. // don't try to authenticate against OAuth2 and SSPI sources here
  731. continue
  732. }
  733. authUser, err := ExternalUserLogin(nil, username, password, source)
  734. if err == nil {
  735. return authUser, nil
  736. }
  737. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  738. }
  739. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  740. }
  741. func genRandEmail() string{
  742. return gouuid.NewV4().String() + "@cloudbrain.com"
  743. }