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.

711 lines
19 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
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
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. "regexp"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. "github.com/go-xorm/xorm"
  16. "xorm.io/core"
  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. if colName == "type" {
  142. switch LoginType(Cell2Int64(val)) {
  143. case LoginLDAP, LoginDLDAP:
  144. source.Cfg = new(LDAPConfig)
  145. case LoginSMTP:
  146. source.Cfg = new(SMTPConfig)
  147. case LoginPAM:
  148. source.Cfg = new(PAMConfig)
  149. case LoginOAuth2:
  150. source.Cfg = new(OAuth2Config)
  151. default:
  152. panic("unrecognized login source type: " + com.ToStr(*val))
  153. }
  154. }
  155. }
  156. // TypeName return name of this login source type.
  157. func (source *LoginSource) TypeName() string {
  158. return LoginNames[source.Type]
  159. }
  160. // IsLDAP returns true of this source is of the LDAP type.
  161. func (source *LoginSource) IsLDAP() bool {
  162. return source.Type == LoginLDAP
  163. }
  164. // IsDLDAP returns true of this source is of the DLDAP type.
  165. func (source *LoginSource) IsDLDAP() bool {
  166. return source.Type == LoginDLDAP
  167. }
  168. // IsSMTP returns true of this source is of the SMTP type.
  169. func (source *LoginSource) IsSMTP() bool {
  170. return source.Type == LoginSMTP
  171. }
  172. // IsPAM returns true of this source is of the PAM type.
  173. func (source *LoginSource) IsPAM() bool {
  174. return source.Type == LoginPAM
  175. }
  176. // IsOAuth2 returns true of this source is of the OAuth2 type.
  177. func (source *LoginSource) IsOAuth2() bool {
  178. return source.Type == LoginOAuth2
  179. }
  180. // HasTLS returns true of this source supports TLS.
  181. func (source *LoginSource) HasTLS() bool {
  182. return ((source.IsLDAP() || source.IsDLDAP()) &&
  183. source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
  184. source.IsSMTP()
  185. }
  186. // UseTLS returns true of this source is configured to use TLS.
  187. func (source *LoginSource) UseTLS() bool {
  188. switch source.Type {
  189. case LoginLDAP, LoginDLDAP:
  190. return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
  191. case LoginSMTP:
  192. return source.SMTP().TLS
  193. }
  194. return false
  195. }
  196. // SkipVerify returns true if this source is configured to skip SSL
  197. // verification.
  198. func (source *LoginSource) SkipVerify() bool {
  199. switch source.Type {
  200. case LoginLDAP, LoginDLDAP:
  201. return source.LDAP().SkipVerify
  202. case LoginSMTP:
  203. return source.SMTP().SkipVerify
  204. }
  205. return false
  206. }
  207. // LDAP returns LDAPConfig for this source, if of LDAP type.
  208. func (source *LoginSource) LDAP() *LDAPConfig {
  209. return source.Cfg.(*LDAPConfig)
  210. }
  211. // SMTP returns SMTPConfig for this source, if of SMTP type.
  212. func (source *LoginSource) SMTP() *SMTPConfig {
  213. return source.Cfg.(*SMTPConfig)
  214. }
  215. // PAM returns PAMConfig for this source, if of PAM type.
  216. func (source *LoginSource) PAM() *PAMConfig {
  217. return source.Cfg.(*PAMConfig)
  218. }
  219. // OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
  220. func (source *LoginSource) OAuth2() *OAuth2Config {
  221. return source.Cfg.(*OAuth2Config)
  222. }
  223. // CreateLoginSource inserts a LoginSource in the DB if not already
  224. // existing with the given name.
  225. func CreateLoginSource(source *LoginSource) error {
  226. has, err := x.Get(&LoginSource{Name: source.Name})
  227. if err != nil {
  228. return err
  229. } else if has {
  230. return ErrLoginSourceAlreadyExist{source.Name}
  231. }
  232. // Synchronization is only aviable with LDAP for now
  233. if !source.IsLDAP() {
  234. source.IsSyncEnabled = false
  235. }
  236. _, err = x.Insert(source)
  237. if err == nil && source.IsOAuth2() && source.IsActived {
  238. oAuth2Config := source.OAuth2()
  239. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  240. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  241. if err != nil {
  242. // remove the LoginSource in case of errors while registering OAuth2 providers
  243. if _, err := x.Delete(source); err != nil {
  244. log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  245. }
  246. return err
  247. }
  248. }
  249. return err
  250. }
  251. // LoginSources returns a slice of all login sources found in DB.
  252. func LoginSources() ([]*LoginSource, error) {
  253. auths := make([]*LoginSource, 0, 6)
  254. return auths, x.Find(&auths)
  255. }
  256. // GetLoginSourceByID returns login source by given ID.
  257. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  258. source := new(LoginSource)
  259. has, err := x.ID(id).Get(source)
  260. if err != nil {
  261. return nil, err
  262. } else if !has {
  263. return nil, ErrLoginSourceNotExist{id}
  264. }
  265. return source, nil
  266. }
  267. // UpdateSource updates a LoginSource record in DB.
  268. func UpdateSource(source *LoginSource) error {
  269. var originalLoginSource *LoginSource
  270. if source.IsOAuth2() {
  271. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  272. var err error
  273. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  274. return err
  275. }
  276. }
  277. _, err := x.ID(source.ID).AllCols().Update(source)
  278. if err == nil && source.IsOAuth2() && source.IsActived {
  279. oAuth2Config := source.OAuth2()
  280. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  281. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  282. if err != nil {
  283. // restore original values since we cannot update the provider it self
  284. if _, err := x.ID(source.ID).AllCols().Update(originalLoginSource); err != nil {
  285. log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  286. }
  287. return err
  288. }
  289. }
  290. return err
  291. }
  292. // DeleteSource deletes a LoginSource record in DB.
  293. func DeleteSource(source *LoginSource) error {
  294. count, err := x.Count(&User{LoginSource: source.ID})
  295. if err != nil {
  296. return err
  297. } else if count > 0 {
  298. return ErrLoginSourceInUse{source.ID}
  299. }
  300. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  301. if err != nil {
  302. return err
  303. } else if count > 0 {
  304. return ErrLoginSourceInUse{source.ID}
  305. }
  306. if source.IsOAuth2() {
  307. oauth2.RemoveProvider(source.Name)
  308. }
  309. _, err = x.ID(source.ID).Delete(new(LoginSource))
  310. return err
  311. }
  312. // CountLoginSources returns number of login sources.
  313. func CountLoginSources() int64 {
  314. count, _ := x.Count(new(LoginSource))
  315. return count
  316. }
  317. // .____ ________ _____ __________
  318. // | | \______ \ / _ \\______ \
  319. // | | | | \ / /_\ \| ___/
  320. // | |___ | ` \/ | \ |
  321. // |_______ \/_______ /\____|__ /____|
  322. // \/ \/ \/
  323. func composeFullName(firstname, surname, username string) string {
  324. switch {
  325. case len(firstname) == 0 && len(surname) == 0:
  326. return username
  327. case len(firstname) == 0:
  328. return surname
  329. case len(surname) == 0:
  330. return firstname
  331. default:
  332. return firstname + " " + surname
  333. }
  334. }
  335. var (
  336. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  337. )
  338. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  339. // and create a local user if success when enabled.
  340. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  341. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  342. if sr == nil {
  343. // User not in LDAP, do nothing
  344. return nil, ErrUserNotExist{0, login, 0}
  345. }
  346. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
  347. if !autoRegister {
  348. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  349. return user, RewriteAllPublicKeys()
  350. }
  351. return user, nil
  352. }
  353. // Fallback.
  354. if len(sr.Username) == 0 {
  355. sr.Username = login
  356. }
  357. // Validate username make sure it satisfies requirement.
  358. if alphaDashDotPattern.MatchString(sr.Username) {
  359. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
  360. }
  361. if len(sr.Mail) == 0 {
  362. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  363. }
  364. user = &User{
  365. LowerName: strings.ToLower(sr.Username),
  366. Name: sr.Username,
  367. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  368. Email: sr.Mail,
  369. LoginType: source.Type,
  370. LoginSource: source.ID,
  371. LoginName: login,
  372. IsActive: true,
  373. IsAdmin: sr.IsAdmin,
  374. }
  375. err := CreateUser(user)
  376. if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  377. err = RewriteAllPublicKeys()
  378. }
  379. return user, err
  380. }
  381. // _________ __________________________
  382. // / _____/ / \__ ___/\______ \
  383. // \_____ \ / \ / \| | | ___/
  384. // / \/ Y \ | | |
  385. // /_______ /\____|__ /____| |____|
  386. // \/ \/
  387. type smtpLoginAuth struct {
  388. username, password string
  389. }
  390. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  391. return "LOGIN", []byte(auth.username), nil
  392. }
  393. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  394. if more {
  395. switch string(fromServer) {
  396. case "Username:":
  397. return []byte(auth.username), nil
  398. case "Password:":
  399. return []byte(auth.password), nil
  400. }
  401. }
  402. return nil, nil
  403. }
  404. // SMTP authentication type names.
  405. const (
  406. SMTPPlain = "PLAIN"
  407. SMTPLogin = "LOGIN"
  408. )
  409. // SMTPAuths contains available SMTP authentication type names.
  410. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  411. // SMTPAuth performs an SMTP authentication.
  412. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  413. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  414. if err != nil {
  415. return err
  416. }
  417. defer c.Close()
  418. if err = c.Hello("gogs"); err != nil {
  419. return err
  420. }
  421. if cfg.TLS {
  422. if ok, _ := c.Extension("STARTTLS"); ok {
  423. if err = c.StartTLS(&tls.Config{
  424. InsecureSkipVerify: cfg.SkipVerify,
  425. ServerName: cfg.Host,
  426. }); err != nil {
  427. return err
  428. }
  429. } else {
  430. return errors.New("SMTP server unsupports TLS")
  431. }
  432. }
  433. if ok, _ := c.Extension("AUTH"); ok {
  434. return c.Auth(a)
  435. }
  436. return ErrUnsupportedLoginType
  437. }
  438. // LoginViaSMTP queries if login/password is valid against the SMTP,
  439. // and create a local user if success when enabled.
  440. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  441. // Verify allowed domains.
  442. if len(cfg.AllowedDomains) > 0 {
  443. idx := strings.Index(login, "@")
  444. if idx == -1 {
  445. return nil, ErrUserNotExist{0, login, 0}
  446. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  447. return nil, ErrUserNotExist{0, login, 0}
  448. }
  449. }
  450. var auth smtp.Auth
  451. if cfg.Auth == SMTPPlain {
  452. auth = smtp.PlainAuth("", login, password, cfg.Host)
  453. } else if cfg.Auth == SMTPLogin {
  454. auth = &smtpLoginAuth{login, password}
  455. } else {
  456. return nil, errors.New("Unsupported SMTP auth type")
  457. }
  458. if err := SMTPAuth(auth, cfg); err != nil {
  459. // Check standard error format first,
  460. // then fallback to worse case.
  461. tperr, ok := err.(*textproto.Error)
  462. if (ok && tperr.Code == 535) ||
  463. strings.Contains(err.Error(), "Username and Password not accepted") {
  464. return nil, ErrUserNotExist{0, login, 0}
  465. }
  466. return nil, err
  467. }
  468. if !autoRegister {
  469. return user, nil
  470. }
  471. username := login
  472. idx := strings.Index(login, "@")
  473. if idx > -1 {
  474. username = login[:idx]
  475. }
  476. user = &User{
  477. LowerName: strings.ToLower(username),
  478. Name: strings.ToLower(username),
  479. Email: login,
  480. Passwd: password,
  481. LoginType: LoginSMTP,
  482. LoginSource: sourceID,
  483. LoginName: login,
  484. IsActive: true,
  485. }
  486. return user, CreateUser(user)
  487. }
  488. // __________ _____ _____
  489. // \______ \/ _ \ / \
  490. // | ___/ /_\ \ / \ / \
  491. // | | / | \/ Y \
  492. // |____| \____|__ /\____|__ /
  493. // \/ \/
  494. // LoginViaPAM queries if login/password is valid against the PAM,
  495. // and create a local user if success when enabled.
  496. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  497. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  498. if strings.Contains(err.Error(), "Authentication failure") {
  499. return nil, ErrUserNotExist{0, login, 0}
  500. }
  501. return nil, err
  502. }
  503. if !autoRegister {
  504. return user, nil
  505. }
  506. user = &User{
  507. LowerName: strings.ToLower(login),
  508. Name: login,
  509. Email: login,
  510. Passwd: password,
  511. LoginType: LoginPAM,
  512. LoginSource: sourceID,
  513. LoginName: login,
  514. IsActive: true,
  515. }
  516. return user, CreateUser(user)
  517. }
  518. // ExternalUserLogin attempts a login using external source types.
  519. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  520. if !source.IsActived {
  521. return nil, ErrLoginSourceNotActived
  522. }
  523. var err error
  524. switch source.Type {
  525. case LoginLDAP, LoginDLDAP:
  526. user, err = LoginViaLDAP(user, login, password, source, autoRegister)
  527. case LoginSMTP:
  528. user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  529. case LoginPAM:
  530. user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  531. default:
  532. return nil, ErrUnsupportedLoginType
  533. }
  534. if err != nil {
  535. return nil, err
  536. }
  537. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  538. // user could be hint to resend confirm email.
  539. if user.ProhibitLogin {
  540. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  541. }
  542. return user, nil
  543. }
  544. // UserSignIn validates user name and password.
  545. func UserSignIn(username, password string) (*User, error) {
  546. var user *User
  547. if strings.Contains(username, "@") {
  548. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  549. // check same email
  550. cnt, err := x.Count(user)
  551. if err != nil {
  552. return nil, err
  553. }
  554. if cnt > 1 {
  555. return nil, ErrEmailAlreadyUsed{
  556. Email: user.Email,
  557. }
  558. }
  559. } else {
  560. trimmedUsername := strings.TrimSpace(username)
  561. if len(trimmedUsername) == 0 {
  562. return nil, ErrUserNotExist{0, username, 0}
  563. }
  564. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  565. }
  566. hasUser, err := x.Get(user)
  567. if err != nil {
  568. return nil, err
  569. }
  570. if hasUser {
  571. switch user.LoginType {
  572. case LoginNoType, LoginPlain, LoginOAuth2:
  573. if user.IsPasswordSet() && user.ValidatePassword(password) {
  574. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  575. // user could be hint to resend confirm email.
  576. if user.ProhibitLogin {
  577. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  578. }
  579. return user, nil
  580. }
  581. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  582. default:
  583. var source LoginSource
  584. hasSource, err := x.ID(user.LoginSource).Get(&source)
  585. if err != nil {
  586. return nil, err
  587. } else if !hasSource {
  588. return nil, ErrLoginSourceNotExist{user.LoginSource}
  589. }
  590. return ExternalUserLogin(user, user.LoginName, password, &source, false)
  591. }
  592. }
  593. sources := make([]*LoginSource, 0, 5)
  594. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  595. return nil, err
  596. }
  597. for _, source := range sources {
  598. if source.IsOAuth2() {
  599. // don't try to authenticate against OAuth2 sources
  600. continue
  601. }
  602. authUser, err := ExternalUserLogin(nil, username, password, source, true)
  603. if err == nil {
  604. return authUser, nil
  605. }
  606. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  607. }
  608. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  609. }