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

672 lines
18 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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)
7 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)
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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)
7 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)
7 years ago
10 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)
7 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)
7 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)
7 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)
7 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)
7 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)
7 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)
7 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)
7 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)
7 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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)
7 years ago
8 years ago
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)
7 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)
7 years ago
8 years ago
7 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "crypto/tls"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net/smtp"
  11. "net/textproto"
  12. "strings"
  13. "github.com/Unknwon/com"
  14. "github.com/go-macaron/binding"
  15. "github.com/go-xorm/core"
  16. "github.com/go-xorm/xorm"
  17. "code.gitea.io/gitea/modules/auth/ldap"
  18. "code.gitea.io/gitea/modules/auth/oauth2"
  19. "code.gitea.io/gitea/modules/auth/pam"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/util"
  22. )
  23. // LoginType represents an login type.
  24. type LoginType int
  25. // Note: new type must append to the end of list to maintain compatibility.
  26. const (
  27. LoginNoType LoginType = iota
  28. LoginPlain // 1
  29. LoginLDAP // 2
  30. LoginSMTP // 3
  31. LoginPAM // 4
  32. LoginDLDAP // 5
  33. LoginOAuth2 // 6
  34. )
  35. // LoginNames contains the name of LoginType values.
  36. var LoginNames = map[LoginType]string{
  37. LoginLDAP: "LDAP (via BindDN)",
  38. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  39. LoginSMTP: "SMTP",
  40. LoginPAM: "PAM",
  41. LoginOAuth2: "OAuth2",
  42. }
  43. // SecurityProtocolNames contains the name of SecurityProtocol values.
  44. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  45. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  46. ldap.SecurityProtocolLDAPS: "LDAPS",
  47. ldap.SecurityProtocolStartTLS: "StartTLS",
  48. }
  49. // Ensure structs implemented interface.
  50. var (
  51. _ core.Conversion = &LDAPConfig{}
  52. _ core.Conversion = &SMTPConfig{}
  53. _ core.Conversion = &PAMConfig{}
  54. _ core.Conversion = &OAuth2Config{}
  55. )
  56. // LDAPConfig holds configuration for LDAP login source.
  57. type LDAPConfig struct {
  58. *ldap.Source
  59. }
  60. // FromDB fills up a LDAPConfig from serialized format.
  61. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  62. return json.Unmarshal(bs, &cfg)
  63. }
  64. // ToDB exports a LDAPConfig to a serialized format.
  65. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  66. return json.Marshal(cfg)
  67. }
  68. // SecurityProtocolName returns the name of configured security
  69. // protocol.
  70. func (cfg *LDAPConfig) SecurityProtocolName() string {
  71. return SecurityProtocolNames[cfg.SecurityProtocol]
  72. }
  73. // SMTPConfig holds configuration for the SMTP login source.
  74. type SMTPConfig struct {
  75. Auth string
  76. Host string
  77. Port int
  78. AllowedDomains string `xorm:"TEXT"`
  79. TLS bool
  80. SkipVerify bool
  81. }
  82. // FromDB fills up an SMTPConfig from serialized format.
  83. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  84. return json.Unmarshal(bs, cfg)
  85. }
  86. // ToDB exports an SMTPConfig to a serialized format.
  87. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  88. return json.Marshal(cfg)
  89. }
  90. // PAMConfig holds configuration for the PAM login source.
  91. type PAMConfig struct {
  92. ServiceName string // pam service (e.g. system-auth)
  93. }
  94. // FromDB fills up a PAMConfig from serialized format.
  95. func (cfg *PAMConfig) FromDB(bs []byte) error {
  96. return json.Unmarshal(bs, &cfg)
  97. }
  98. // ToDB exports a PAMConfig to a serialized format.
  99. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  100. return json.Marshal(cfg)
  101. }
  102. // OAuth2Config holds configuration for the OAuth2 login source.
  103. type OAuth2Config struct {
  104. Provider string
  105. ClientID string
  106. ClientSecret string
  107. OpenIDConnectAutoDiscoveryURL string
  108. CustomURLMapping *oauth2.CustomURLMapping
  109. }
  110. // FromDB fills up an OAuth2Config from serialized format.
  111. func (cfg *OAuth2Config) FromDB(bs []byte) error {
  112. return json.Unmarshal(bs, cfg)
  113. }
  114. // ToDB exports an SMTPConfig to a serialized format.
  115. func (cfg *OAuth2Config) ToDB() ([]byte, error) {
  116. return json.Marshal(cfg)
  117. }
  118. // LoginSource represents an external way for authorizing users.
  119. type LoginSource struct {
  120. ID int64 `xorm:"pk autoincr"`
  121. Type LoginType
  122. Name string `xorm:"UNIQUE"`
  123. IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
  124. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  125. Cfg core.Conversion `xorm:"TEXT"`
  126. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  127. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  128. }
  129. // Cell2Int64 converts a xorm.Cell type to int64,
  130. // and handles possible irregular cases.
  131. func Cell2Int64(val xorm.Cell) int64 {
  132. switch (*val).(type) {
  133. case []uint8:
  134. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  135. return com.StrTo(string((*val).([]uint8))).MustInt64()
  136. }
  137. return (*val).(int64)
  138. }
  139. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  140. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  141. switch colName {
  142. case "type":
  143. switch LoginType(Cell2Int64(val)) {
  144. case LoginLDAP, LoginDLDAP:
  145. source.Cfg = new(LDAPConfig)
  146. case LoginSMTP:
  147. source.Cfg = new(SMTPConfig)
  148. case LoginPAM:
  149. source.Cfg = new(PAMConfig)
  150. case LoginOAuth2:
  151. source.Cfg = new(OAuth2Config)
  152. default:
  153. panic("unrecognized login source type: " + com.ToStr(*val))
  154. }
  155. }
  156. }
  157. // TypeName return name of this login source type.
  158. func (source *LoginSource) TypeName() string {
  159. return LoginNames[source.Type]
  160. }
  161. // IsLDAP returns true of this source is of the LDAP type.
  162. func (source *LoginSource) IsLDAP() bool {
  163. return source.Type == LoginLDAP
  164. }
  165. // IsDLDAP returns true of this source is of the DLDAP type.
  166. func (source *LoginSource) IsDLDAP() bool {
  167. return source.Type == LoginDLDAP
  168. }
  169. // IsSMTP returns true of this source is of the SMTP type.
  170. func (source *LoginSource) IsSMTP() bool {
  171. return source.Type == LoginSMTP
  172. }
  173. // IsPAM returns true of this source is of the PAM type.
  174. func (source *LoginSource) IsPAM() bool {
  175. return source.Type == LoginPAM
  176. }
  177. // IsOAuth2 returns true of this source is of the OAuth2 type.
  178. func (source *LoginSource) IsOAuth2() bool {
  179. return source.Type == LoginOAuth2
  180. }
  181. // HasTLS returns true of this source supports TLS.
  182. func (source *LoginSource) HasTLS() bool {
  183. return ((source.IsLDAP() || source.IsDLDAP()) &&
  184. source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
  185. source.IsSMTP()
  186. }
  187. // UseTLS returns true of this source is configured to use TLS.
  188. func (source *LoginSource) UseTLS() bool {
  189. switch source.Type {
  190. case LoginLDAP, LoginDLDAP:
  191. return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
  192. case LoginSMTP:
  193. return source.SMTP().TLS
  194. }
  195. return false
  196. }
  197. // SkipVerify returns true if this source is configured to skip SSL
  198. // verification.
  199. func (source *LoginSource) SkipVerify() bool {
  200. switch source.Type {
  201. case LoginLDAP, LoginDLDAP:
  202. return source.LDAP().SkipVerify
  203. case LoginSMTP:
  204. return source.SMTP().SkipVerify
  205. }
  206. return false
  207. }
  208. // LDAP returns LDAPConfig for this source, if of LDAP type.
  209. func (source *LoginSource) LDAP() *LDAPConfig {
  210. return source.Cfg.(*LDAPConfig)
  211. }
  212. // SMTP returns SMTPConfig for this source, if of SMTP type.
  213. func (source *LoginSource) SMTP() *SMTPConfig {
  214. return source.Cfg.(*SMTPConfig)
  215. }
  216. // PAM returns PAMConfig for this source, if of PAM type.
  217. func (source *LoginSource) PAM() *PAMConfig {
  218. return source.Cfg.(*PAMConfig)
  219. }
  220. // OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
  221. func (source *LoginSource) OAuth2() *OAuth2Config {
  222. return source.Cfg.(*OAuth2Config)
  223. }
  224. // CreateLoginSource inserts a LoginSource in the DB if not already
  225. // existing with the given name.
  226. func CreateLoginSource(source *LoginSource) error {
  227. has, err := x.Get(&LoginSource{Name: source.Name})
  228. if err != nil {
  229. return err
  230. } else if has {
  231. return ErrLoginSourceAlreadyExist{source.Name}
  232. }
  233. // Synchronization is only aviable with LDAP for now
  234. if !source.IsLDAP() {
  235. source.IsSyncEnabled = false
  236. }
  237. _, err = x.Insert(source)
  238. if err == nil && source.IsOAuth2() && source.IsActived {
  239. oAuth2Config := source.OAuth2()
  240. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  241. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  242. if err != nil {
  243. // remove the LoginSource in case of errors while registering OAuth2 providers
  244. x.Delete(source)
  245. }
  246. }
  247. return err
  248. }
  249. // LoginSources returns a slice of all login sources found in DB.
  250. func LoginSources() ([]*LoginSource, error) {
  251. auths := make([]*LoginSource, 0, 6)
  252. return auths, x.Find(&auths)
  253. }
  254. // GetLoginSourceByID returns login source by given ID.
  255. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  256. source := new(LoginSource)
  257. has, err := x.ID(id).Get(source)
  258. if err != nil {
  259. return nil, err
  260. } else if !has {
  261. return nil, ErrLoginSourceNotExist{id}
  262. }
  263. return source, nil
  264. }
  265. // UpdateSource updates a LoginSource record in DB.
  266. func UpdateSource(source *LoginSource) error {
  267. var originalLoginSource *LoginSource
  268. if source.IsOAuth2() {
  269. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  270. var err error
  271. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  272. return err
  273. }
  274. }
  275. _, err := x.ID(source.ID).AllCols().Update(source)
  276. if err == nil && source.IsOAuth2() && source.IsActived {
  277. oAuth2Config := source.OAuth2()
  278. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  279. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  280. if err != nil {
  281. // restore original values since we cannot update the provider it self
  282. x.ID(source.ID).AllCols().Update(originalLoginSource)
  283. }
  284. }
  285. return err
  286. }
  287. // DeleteSource deletes a LoginSource record in DB.
  288. func DeleteSource(source *LoginSource) error {
  289. count, err := x.Count(&User{LoginSource: source.ID})
  290. if err != nil {
  291. return err
  292. } else if count > 0 {
  293. return ErrLoginSourceInUse{source.ID}
  294. }
  295. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  296. if err != nil {
  297. return err
  298. } else if count > 0 {
  299. return ErrLoginSourceInUse{source.ID}
  300. }
  301. if source.IsOAuth2() {
  302. oauth2.RemoveProvider(source.Name)
  303. }
  304. _, err = x.ID(source.ID).Delete(new(LoginSource))
  305. return err
  306. }
  307. // CountLoginSources returns number of login sources.
  308. func CountLoginSources() int64 {
  309. count, _ := x.Count(new(LoginSource))
  310. return count
  311. }
  312. // .____ ________ _____ __________
  313. // | | \______ \ / _ \\______ \
  314. // | | | | \ / /_\ \| ___/
  315. // | |___ | ` \/ | \ |
  316. // |_______ \/_______ /\____|__ /____|
  317. // \/ \/ \/
  318. func composeFullName(firstname, surname, username string) string {
  319. switch {
  320. case len(firstname) == 0 && len(surname) == 0:
  321. return username
  322. case len(firstname) == 0:
  323. return surname
  324. case len(surname) == 0:
  325. return firstname
  326. default:
  327. return firstname + " " + surname
  328. }
  329. }
  330. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  331. // and create a local user if success when enabled.
  332. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  333. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  334. if sr == nil {
  335. // User not in LDAP, do nothing
  336. return nil, ErrUserNotExist{0, login, 0}
  337. }
  338. if !autoRegister {
  339. return user, nil
  340. }
  341. // Fallback.
  342. if len(sr.Username) == 0 {
  343. sr.Username = login
  344. }
  345. // Validate username make sure it satisfies requirement.
  346. if binding.AlphaDashDotPattern.MatchString(sr.Username) {
  347. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
  348. }
  349. if len(sr.Mail) == 0 {
  350. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  351. }
  352. user = &User{
  353. LowerName: strings.ToLower(sr.Username),
  354. Name: sr.Username,
  355. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  356. Email: sr.Mail,
  357. LoginType: source.Type,
  358. LoginSource: source.ID,
  359. LoginName: login,
  360. IsActive: true,
  361. IsAdmin: sr.IsAdmin,
  362. }
  363. return user, CreateUser(user)
  364. }
  365. // _________ __________________________
  366. // / _____/ / \__ ___/\______ \
  367. // \_____ \ / \ / \| | | ___/
  368. // / \/ Y \ | | |
  369. // /_______ /\____|__ /____| |____|
  370. // \/ \/
  371. type smtpLoginAuth struct {
  372. username, password string
  373. }
  374. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  375. return "LOGIN", []byte(auth.username), nil
  376. }
  377. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  378. if more {
  379. switch string(fromServer) {
  380. case "Username:":
  381. return []byte(auth.username), nil
  382. case "Password:":
  383. return []byte(auth.password), nil
  384. }
  385. }
  386. return nil, nil
  387. }
  388. // SMTP authentication type names.
  389. const (
  390. SMTPPlain = "PLAIN"
  391. SMTPLogin = "LOGIN"
  392. )
  393. // SMTPAuths contains available SMTP authentication type names.
  394. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  395. // SMTPAuth performs an SMTP authentication.
  396. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  397. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  398. if err != nil {
  399. return err
  400. }
  401. defer c.Close()
  402. if err = c.Hello("gogs"); err != nil {
  403. return err
  404. }
  405. if cfg.TLS {
  406. if ok, _ := c.Extension("STARTTLS"); ok {
  407. if err = c.StartTLS(&tls.Config{
  408. InsecureSkipVerify: cfg.SkipVerify,
  409. ServerName: cfg.Host,
  410. }); err != nil {
  411. return err
  412. }
  413. } else {
  414. return errors.New("SMTP server unsupports TLS")
  415. }
  416. }
  417. if ok, _ := c.Extension("AUTH"); ok {
  418. return c.Auth(a)
  419. }
  420. return ErrUnsupportedLoginType
  421. }
  422. // LoginViaSMTP queries if login/password is valid against the SMTP,
  423. // and create a local user if success when enabled.
  424. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  425. // Verify allowed domains.
  426. if len(cfg.AllowedDomains) > 0 {
  427. idx := strings.Index(login, "@")
  428. if idx == -1 {
  429. return nil, ErrUserNotExist{0, login, 0}
  430. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  431. return nil, ErrUserNotExist{0, login, 0}
  432. }
  433. }
  434. var auth smtp.Auth
  435. if cfg.Auth == SMTPPlain {
  436. auth = smtp.PlainAuth("", login, password, cfg.Host)
  437. } else if cfg.Auth == SMTPLogin {
  438. auth = &smtpLoginAuth{login, password}
  439. } else {
  440. return nil, errors.New("Unsupported SMTP auth type")
  441. }
  442. if err := SMTPAuth(auth, cfg); err != nil {
  443. // Check standard error format first,
  444. // then fallback to worse case.
  445. tperr, ok := err.(*textproto.Error)
  446. if (ok && tperr.Code == 535) ||
  447. strings.Contains(err.Error(), "Username and Password not accepted") {
  448. return nil, ErrUserNotExist{0, login, 0}
  449. }
  450. return nil, err
  451. }
  452. if !autoRegister {
  453. return user, nil
  454. }
  455. username := login
  456. idx := strings.Index(login, "@")
  457. if idx > -1 {
  458. username = login[:idx]
  459. }
  460. user = &User{
  461. LowerName: strings.ToLower(username),
  462. Name: strings.ToLower(username),
  463. Email: login,
  464. Passwd: password,
  465. LoginType: LoginSMTP,
  466. LoginSource: sourceID,
  467. LoginName: login,
  468. IsActive: true,
  469. }
  470. return user, CreateUser(user)
  471. }
  472. // __________ _____ _____
  473. // \______ \/ _ \ / \
  474. // | ___/ /_\ \ / \ / \
  475. // | | / | \/ Y \
  476. // |____| \____|__ /\____|__ /
  477. // \/ \/
  478. // LoginViaPAM queries if login/password is valid against the PAM,
  479. // and create a local user if success when enabled.
  480. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  481. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  482. if strings.Contains(err.Error(), "Authentication failure") {
  483. return nil, ErrUserNotExist{0, login, 0}
  484. }
  485. return nil, err
  486. }
  487. if !autoRegister {
  488. return user, nil
  489. }
  490. user = &User{
  491. LowerName: strings.ToLower(login),
  492. Name: login,
  493. Email: login,
  494. Passwd: password,
  495. LoginType: LoginPAM,
  496. LoginSource: sourceID,
  497. LoginName: login,
  498. IsActive: true,
  499. }
  500. return user, CreateUser(user)
  501. }
  502. // ExternalUserLogin attempts a login using external source types.
  503. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  504. if !source.IsActived {
  505. return nil, ErrLoginSourceNotActived
  506. }
  507. switch source.Type {
  508. case LoginLDAP, LoginDLDAP:
  509. return LoginViaLDAP(user, login, password, source, autoRegister)
  510. case LoginSMTP:
  511. return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  512. case LoginPAM:
  513. return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  514. }
  515. return nil, ErrUnsupportedLoginType
  516. }
  517. // UserSignIn validates user name and password.
  518. func UserSignIn(username, password string) (*User, error) {
  519. var user *User
  520. if strings.Contains(username, "@") {
  521. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  522. // check same email
  523. cnt, err := x.Count(user)
  524. if err != nil {
  525. return nil, err
  526. }
  527. if cnt > 1 {
  528. return nil, ErrEmailAlreadyUsed{
  529. Email: user.Email,
  530. }
  531. }
  532. } else {
  533. trimmedUsername := strings.TrimSpace(username)
  534. if len(trimmedUsername) == 0 {
  535. return nil, ErrUserNotExist{0, username, 0}
  536. }
  537. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  538. }
  539. hasUser, err := x.Get(user)
  540. if err != nil {
  541. return nil, err
  542. }
  543. if hasUser {
  544. switch user.LoginType {
  545. case LoginNoType, LoginPlain, LoginOAuth2:
  546. if user.ValidatePassword(password) {
  547. return user, nil
  548. }
  549. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  550. default:
  551. var source LoginSource
  552. hasSource, err := x.ID(user.LoginSource).Get(&source)
  553. if err != nil {
  554. return nil, err
  555. } else if !hasSource {
  556. return nil, ErrLoginSourceNotExist{user.LoginSource}
  557. }
  558. return ExternalUserLogin(user, user.LoginName, password, &source, false)
  559. }
  560. }
  561. sources := make([]*LoginSource, 0, 5)
  562. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  563. return nil, err
  564. }
  565. for _, source := range sources {
  566. if source.IsOAuth2() {
  567. // don't try to authenticate against OAuth2 sources
  568. continue
  569. }
  570. authUser, err := ExternalUserLogin(nil, username, password, source, true)
  571. if err == nil {
  572. return authUser, nil
  573. }
  574. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  575. }
  576. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  577. }