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.

login_source.go 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
  339. if !autoRegister {
  340. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  341. RewriteAllPublicKeys()
  342. }
  343. return user, nil
  344. }
  345. // Fallback.
  346. if len(sr.Username) == 0 {
  347. sr.Username = login
  348. }
  349. // Validate username make sure it satisfies requirement.
  350. if binding.AlphaDashDotPattern.MatchString(sr.Username) {
  351. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
  352. }
  353. if len(sr.Mail) == 0 {
  354. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  355. }
  356. user = &User{
  357. LowerName: strings.ToLower(sr.Username),
  358. Name: sr.Username,
  359. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  360. Email: sr.Mail,
  361. LoginType: source.Type,
  362. LoginSource: source.ID,
  363. LoginName: login,
  364. IsActive: true,
  365. IsAdmin: sr.IsAdmin,
  366. }
  367. err := CreateUser(user)
  368. if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  369. RewriteAllPublicKeys()
  370. }
  371. return user, err
  372. }
  373. // _________ __________________________
  374. // / _____/ / \__ ___/\______ \
  375. // \_____ \ / \ / \| | | ___/
  376. // / \/ Y \ | | |
  377. // /_______ /\____|__ /____| |____|
  378. // \/ \/
  379. type smtpLoginAuth struct {
  380. username, password string
  381. }
  382. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  383. return "LOGIN", []byte(auth.username), nil
  384. }
  385. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  386. if more {
  387. switch string(fromServer) {
  388. case "Username:":
  389. return []byte(auth.username), nil
  390. case "Password:":
  391. return []byte(auth.password), nil
  392. }
  393. }
  394. return nil, nil
  395. }
  396. // SMTP authentication type names.
  397. const (
  398. SMTPPlain = "PLAIN"
  399. SMTPLogin = "LOGIN"
  400. )
  401. // SMTPAuths contains available SMTP authentication type names.
  402. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  403. // SMTPAuth performs an SMTP authentication.
  404. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  405. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  406. if err != nil {
  407. return err
  408. }
  409. defer c.Close()
  410. if err = c.Hello("gogs"); err != nil {
  411. return err
  412. }
  413. if cfg.TLS {
  414. if ok, _ := c.Extension("STARTTLS"); ok {
  415. if err = c.StartTLS(&tls.Config{
  416. InsecureSkipVerify: cfg.SkipVerify,
  417. ServerName: cfg.Host,
  418. }); err != nil {
  419. return err
  420. }
  421. } else {
  422. return errors.New("SMTP server unsupports TLS")
  423. }
  424. }
  425. if ok, _ := c.Extension("AUTH"); ok {
  426. return c.Auth(a)
  427. }
  428. return ErrUnsupportedLoginType
  429. }
  430. // LoginViaSMTP queries if login/password is valid against the SMTP,
  431. // and create a local user if success when enabled.
  432. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  433. // Verify allowed domains.
  434. if len(cfg.AllowedDomains) > 0 {
  435. idx := strings.Index(login, "@")
  436. if idx == -1 {
  437. return nil, ErrUserNotExist{0, login, 0}
  438. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  439. return nil, ErrUserNotExist{0, login, 0}
  440. }
  441. }
  442. var auth smtp.Auth
  443. if cfg.Auth == SMTPPlain {
  444. auth = smtp.PlainAuth("", login, password, cfg.Host)
  445. } else if cfg.Auth == SMTPLogin {
  446. auth = &smtpLoginAuth{login, password}
  447. } else {
  448. return nil, errors.New("Unsupported SMTP auth type")
  449. }
  450. if err := SMTPAuth(auth, cfg); err != nil {
  451. // Check standard error format first,
  452. // then fallback to worse case.
  453. tperr, ok := err.(*textproto.Error)
  454. if (ok && tperr.Code == 535) ||
  455. strings.Contains(err.Error(), "Username and Password not accepted") {
  456. return nil, ErrUserNotExist{0, login, 0}
  457. }
  458. return nil, err
  459. }
  460. if !autoRegister {
  461. return user, nil
  462. }
  463. username := login
  464. idx := strings.Index(login, "@")
  465. if idx > -1 {
  466. username = login[:idx]
  467. }
  468. user = &User{
  469. LowerName: strings.ToLower(username),
  470. Name: strings.ToLower(username),
  471. Email: login,
  472. Passwd: password,
  473. LoginType: LoginSMTP,
  474. LoginSource: sourceID,
  475. LoginName: login,
  476. IsActive: true,
  477. }
  478. return user, CreateUser(user)
  479. }
  480. // __________ _____ _____
  481. // \______ \/ _ \ / \
  482. // | ___/ /_\ \ / \ / \
  483. // | | / | \/ Y \
  484. // |____| \____|__ /\____|__ /
  485. // \/ \/
  486. // LoginViaPAM queries if login/password is valid against the PAM,
  487. // and create a local user if success when enabled.
  488. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  489. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  490. if strings.Contains(err.Error(), "Authentication failure") {
  491. return nil, ErrUserNotExist{0, login, 0}
  492. }
  493. return nil, err
  494. }
  495. if !autoRegister {
  496. return user, nil
  497. }
  498. user = &User{
  499. LowerName: strings.ToLower(login),
  500. Name: login,
  501. Email: login,
  502. Passwd: password,
  503. LoginType: LoginPAM,
  504. LoginSource: sourceID,
  505. LoginName: login,
  506. IsActive: true,
  507. }
  508. return user, CreateUser(user)
  509. }
  510. // ExternalUserLogin attempts a login using external source types.
  511. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  512. if !source.IsActived {
  513. return nil, ErrLoginSourceNotActived
  514. }
  515. var err error
  516. switch source.Type {
  517. case LoginLDAP, LoginDLDAP:
  518. user, err = LoginViaLDAP(user, login, password, source, autoRegister)
  519. case LoginSMTP:
  520. user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  521. case LoginPAM:
  522. user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  523. default:
  524. return nil, ErrUnsupportedLoginType
  525. }
  526. if err != nil {
  527. return nil, err
  528. }
  529. if !user.IsActive {
  530. return nil, ErrUserInactive{user.ID, user.Name}
  531. } else if user.ProhibitLogin {
  532. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  533. }
  534. return user, nil
  535. }
  536. // UserSignIn validates user name and password.
  537. func UserSignIn(username, password string) (*User, error) {
  538. var user *User
  539. if strings.Contains(username, "@") {
  540. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  541. // check same email
  542. cnt, err := x.Count(user)
  543. if err != nil {
  544. return nil, err
  545. }
  546. if cnt > 1 {
  547. return nil, ErrEmailAlreadyUsed{
  548. Email: user.Email,
  549. }
  550. }
  551. } else {
  552. trimmedUsername := strings.TrimSpace(username)
  553. if len(trimmedUsername) == 0 {
  554. return nil, ErrUserNotExist{0, username, 0}
  555. }
  556. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  557. }
  558. hasUser, err := x.Get(user)
  559. if err != nil {
  560. return nil, err
  561. }
  562. if hasUser {
  563. switch user.LoginType {
  564. case LoginNoType, LoginPlain, LoginOAuth2:
  565. if user.IsPasswordSet() && user.ValidatePassword(password) {
  566. if !user.IsActive {
  567. return nil, ErrUserInactive{user.ID, user.Name}
  568. } else if user.ProhibitLogin {
  569. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  570. }
  571. return user, nil
  572. }
  573. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  574. default:
  575. var source LoginSource
  576. hasSource, err := x.ID(user.LoginSource).Get(&source)
  577. if err != nil {
  578. return nil, err
  579. } else if !hasSource {
  580. return nil, ErrLoginSourceNotExist{user.LoginSource}
  581. }
  582. return ExternalUserLogin(user, user.LoginName, password, &source, false)
  583. }
  584. }
  585. sources := make([]*LoginSource, 0, 5)
  586. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  587. return nil, err
  588. }
  589. for _, source := range sources {
  590. if source.IsOAuth2() {
  591. // don't try to authenticate against OAuth2 sources
  592. continue
  593. }
  594. authUser, err := ExternalUserLogin(nil, username, password, source, true)
  595. if err == nil {
  596. return authUser, nil
  597. }
  598. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  599. }
  600. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  601. }