Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

login_source.go 18KB

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