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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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. "code.gitea.io/gitea/modules/auth/ldap"
  15. "code.gitea.io/gitea/modules/auth/oauth2"
  16. "code.gitea.io/gitea/modules/auth/pam"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "github.com/unknwon/com"
  21. "xorm.io/core"
  22. "xorm.io/xorm"
  23. )
  24. // LoginType represents an login type.
  25. type LoginType int
  26. // Note: new type must append to the end of list to maintain compatibility.
  27. const (
  28. LoginNoType LoginType = iota
  29. LoginPlain // 1
  30. LoginLDAP // 2
  31. LoginSMTP // 3
  32. LoginPAM // 4
  33. LoginDLDAP // 5
  34. LoginOAuth2 // 6
  35. )
  36. // LoginNames contains the name of LoginType values.
  37. var LoginNames = map[LoginType]string{
  38. LoginLDAP: "LDAP (via BindDN)",
  39. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  40. LoginSMTP: "SMTP",
  41. LoginPAM: "PAM",
  42. LoginOAuth2: "OAuth2",
  43. }
  44. // SecurityProtocolNames contains the name of SecurityProtocol values.
  45. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  46. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  47. ldap.SecurityProtocolLDAPS: "LDAPS",
  48. ldap.SecurityProtocolStartTLS: "StartTLS",
  49. }
  50. // Ensure structs implemented interface.
  51. var (
  52. _ core.Conversion = &LDAPConfig{}
  53. _ core.Conversion = &SMTPConfig{}
  54. _ core.Conversion = &PAMConfig{}
  55. _ core.Conversion = &OAuth2Config{}
  56. )
  57. // LDAPConfig holds configuration for LDAP login source.
  58. type LDAPConfig struct {
  59. *ldap.Source
  60. }
  61. // FromDB fills up a LDAPConfig from serialized format.
  62. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  63. return json.Unmarshal(bs, &cfg)
  64. }
  65. // ToDB exports a LDAPConfig to a serialized format.
  66. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  67. return json.Marshal(cfg)
  68. }
  69. // SecurityProtocolName returns the name of configured security
  70. // protocol.
  71. func (cfg *LDAPConfig) SecurityProtocolName() string {
  72. return SecurityProtocolNames[cfg.SecurityProtocol]
  73. }
  74. // SMTPConfig holds configuration for the SMTP login source.
  75. type SMTPConfig struct {
  76. Auth string
  77. Host string
  78. Port int
  79. AllowedDomains string `xorm:"TEXT"`
  80. TLS bool
  81. SkipVerify bool
  82. }
  83. // FromDB fills up an SMTPConfig from serialized format.
  84. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  85. return json.Unmarshal(bs, cfg)
  86. }
  87. // ToDB exports an SMTPConfig to a serialized format.
  88. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  89. return json.Marshal(cfg)
  90. }
  91. // PAMConfig holds configuration for the PAM login source.
  92. type PAMConfig struct {
  93. ServiceName string // pam service (e.g. system-auth)
  94. }
  95. // FromDB fills up a PAMConfig from serialized format.
  96. func (cfg *PAMConfig) FromDB(bs []byte) error {
  97. return json.Unmarshal(bs, &cfg)
  98. }
  99. // ToDB exports a PAMConfig to a serialized format.
  100. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  101. return json.Marshal(cfg)
  102. }
  103. // OAuth2Config holds configuration for the OAuth2 login source.
  104. type OAuth2Config struct {
  105. Provider string
  106. ClientID string
  107. ClientSecret string
  108. OpenIDConnectAutoDiscoveryURL string
  109. CustomURLMapping *oauth2.CustomURLMapping
  110. }
  111. // FromDB fills up an OAuth2Config from serialized format.
  112. func (cfg *OAuth2Config) FromDB(bs []byte) error {
  113. return json.Unmarshal(bs, cfg)
  114. }
  115. // ToDB exports an SMTPConfig to a serialized format.
  116. func (cfg *OAuth2Config) ToDB() ([]byte, error) {
  117. return json.Marshal(cfg)
  118. }
  119. // LoginSource represents an external way for authorizing users.
  120. type LoginSource struct {
  121. ID int64 `xorm:"pk autoincr"`
  122. Type LoginType
  123. Name string `xorm:"UNIQUE"`
  124. IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
  125. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  126. Cfg core.Conversion `xorm:"TEXT"`
  127. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  128. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  129. }
  130. // Cell2Int64 converts a xorm.Cell type to int64,
  131. // and handles possible irregular cases.
  132. func Cell2Int64(val xorm.Cell) int64 {
  133. switch (*val).(type) {
  134. case []uint8:
  135. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  136. return com.StrTo(string((*val).([]uint8))).MustInt64()
  137. }
  138. return (*val).(int64)
  139. }
  140. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  141. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  142. if colName == "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. if _, err := x.Delete(source); err != nil {
  245. log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  246. }
  247. return err
  248. }
  249. }
  250. return err
  251. }
  252. // LoginSources returns a slice of all login sources found in DB.
  253. func LoginSources() ([]*LoginSource, error) {
  254. auths := make([]*LoginSource, 0, 6)
  255. return auths, x.Find(&auths)
  256. }
  257. // GetLoginSourceByID returns login source by given ID.
  258. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  259. source := new(LoginSource)
  260. has, err := x.ID(id).Get(source)
  261. if err != nil {
  262. return nil, err
  263. } else if !has {
  264. return nil, ErrLoginSourceNotExist{id}
  265. }
  266. return source, nil
  267. }
  268. // UpdateSource updates a LoginSource record in DB.
  269. func UpdateSource(source *LoginSource) error {
  270. var originalLoginSource *LoginSource
  271. if source.IsOAuth2() {
  272. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  273. var err error
  274. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  275. return err
  276. }
  277. }
  278. _, err := x.ID(source.ID).AllCols().Update(source)
  279. if err == nil && source.IsOAuth2() && source.IsActived {
  280. oAuth2Config := source.OAuth2()
  281. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  282. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  283. if err != nil {
  284. // restore original values since we cannot update the provider it self
  285. if _, err := x.ID(source.ID).AllCols().Update(originalLoginSource); err != nil {
  286. log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  287. }
  288. return err
  289. }
  290. }
  291. return err
  292. }
  293. // DeleteSource deletes a LoginSource record in DB.
  294. func DeleteSource(source *LoginSource) error {
  295. count, err := x.Count(&User{LoginSource: source.ID})
  296. if err != nil {
  297. return err
  298. } else if count > 0 {
  299. return ErrLoginSourceInUse{source.ID}
  300. }
  301. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  302. if err != nil {
  303. return err
  304. } else if count > 0 {
  305. return ErrLoginSourceInUse{source.ID}
  306. }
  307. if source.IsOAuth2() {
  308. oauth2.RemoveProvider(source.Name)
  309. }
  310. _, err = x.ID(source.ID).Delete(new(LoginSource))
  311. return err
  312. }
  313. // CountLoginSources returns number of login sources.
  314. func CountLoginSources() int64 {
  315. count, _ := x.Count(new(LoginSource))
  316. return count
  317. }
  318. // .____ ________ _____ __________
  319. // | | \______ \ / _ \\______ \
  320. // | | | | \ / /_\ \| ___/
  321. // | |___ | ` \/ | \ |
  322. // |_______ \/_______ /\____|__ /____|
  323. // \/ \/ \/
  324. func composeFullName(firstname, surname, username string) string {
  325. switch {
  326. case len(firstname) == 0 && len(surname) == 0:
  327. return username
  328. case len(firstname) == 0:
  329. return surname
  330. case len(surname) == 0:
  331. return firstname
  332. default:
  333. return firstname + " " + surname
  334. }
  335. }
  336. var (
  337. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  338. )
  339. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  340. // and create a local user if success when enabled.
  341. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  342. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  343. if sr == nil {
  344. // User not in LDAP, do nothing
  345. return nil, ErrUserNotExist{0, login, 0}
  346. }
  347. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
  348. if !autoRegister {
  349. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  350. return user, RewriteAllPublicKeys()
  351. }
  352. return user, nil
  353. }
  354. // Fallback.
  355. if len(sr.Username) == 0 {
  356. sr.Username = login
  357. }
  358. // Validate username make sure it satisfies requirement.
  359. if alphaDashDotPattern.MatchString(sr.Username) {
  360. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
  361. }
  362. if len(sr.Mail) == 0 {
  363. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  364. }
  365. user = &User{
  366. LowerName: strings.ToLower(sr.Username),
  367. Name: sr.Username,
  368. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  369. Email: sr.Mail,
  370. LoginType: source.Type,
  371. LoginSource: source.ID,
  372. LoginName: login,
  373. IsActive: true,
  374. IsAdmin: sr.IsAdmin,
  375. }
  376. err := CreateUser(user)
  377. if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  378. err = RewriteAllPublicKeys()
  379. }
  380. return user, err
  381. }
  382. // _________ __________________________
  383. // / _____/ / \__ ___/\______ \
  384. // \_____ \ / \ / \| | | ___/
  385. // / \/ Y \ | | |
  386. // /_______ /\____|__ /____| |____|
  387. // \/ \/
  388. type smtpLoginAuth struct {
  389. username, password string
  390. }
  391. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  392. return "LOGIN", []byte(auth.username), nil
  393. }
  394. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  395. if more {
  396. switch string(fromServer) {
  397. case "Username:":
  398. return []byte(auth.username), nil
  399. case "Password:":
  400. return []byte(auth.password), nil
  401. }
  402. }
  403. return nil, nil
  404. }
  405. // SMTP authentication type names.
  406. const (
  407. SMTPPlain = "PLAIN"
  408. SMTPLogin = "LOGIN"
  409. )
  410. // SMTPAuths contains available SMTP authentication type names.
  411. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  412. // SMTPAuth performs an SMTP authentication.
  413. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  414. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  415. if err != nil {
  416. return err
  417. }
  418. defer c.Close()
  419. if err = c.Hello("gogs"); err != nil {
  420. return err
  421. }
  422. if cfg.TLS {
  423. if ok, _ := c.Extension("STARTTLS"); ok {
  424. if err = c.StartTLS(&tls.Config{
  425. InsecureSkipVerify: cfg.SkipVerify,
  426. ServerName: cfg.Host,
  427. }); err != nil {
  428. return err
  429. }
  430. } else {
  431. return errors.New("SMTP server unsupports TLS")
  432. }
  433. }
  434. if ok, _ := c.Extension("AUTH"); ok {
  435. return c.Auth(a)
  436. }
  437. return ErrUnsupportedLoginType
  438. }
  439. // LoginViaSMTP queries if login/password is valid against the SMTP,
  440. // and create a local user if success when enabled.
  441. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  442. // Verify allowed domains.
  443. if len(cfg.AllowedDomains) > 0 {
  444. idx := strings.Index(login, "@")
  445. if idx == -1 {
  446. return nil, ErrUserNotExist{0, login, 0}
  447. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  448. return nil, ErrUserNotExist{0, login, 0}
  449. }
  450. }
  451. var auth smtp.Auth
  452. if cfg.Auth == SMTPPlain {
  453. auth = smtp.PlainAuth("", login, password, cfg.Host)
  454. } else if cfg.Auth == SMTPLogin {
  455. auth = &smtpLoginAuth{login, password}
  456. } else {
  457. return nil, errors.New("Unsupported SMTP auth type")
  458. }
  459. if err := SMTPAuth(auth, cfg); err != nil {
  460. // Check standard error format first,
  461. // then fallback to worse case.
  462. tperr, ok := err.(*textproto.Error)
  463. if (ok && tperr.Code == 535) ||
  464. strings.Contains(err.Error(), "Username and Password not accepted") {
  465. return nil, ErrUserNotExist{0, login, 0}
  466. }
  467. return nil, err
  468. }
  469. if !autoRegister {
  470. return user, nil
  471. }
  472. username := login
  473. idx := strings.Index(login, "@")
  474. if idx > -1 {
  475. username = login[:idx]
  476. }
  477. user = &User{
  478. LowerName: strings.ToLower(username),
  479. Name: strings.ToLower(username),
  480. Email: login,
  481. Passwd: password,
  482. LoginType: LoginSMTP,
  483. LoginSource: sourceID,
  484. LoginName: login,
  485. IsActive: true,
  486. }
  487. return user, CreateUser(user)
  488. }
  489. // __________ _____ _____
  490. // \______ \/ _ \ / \
  491. // | ___/ /_\ \ / \ / \
  492. // | | / | \/ Y \
  493. // |____| \____|__ /\____|__ /
  494. // \/ \/
  495. // LoginViaPAM queries if login/password is valid against the PAM,
  496. // and create a local user if success when enabled.
  497. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  498. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  499. if strings.Contains(err.Error(), "Authentication failure") {
  500. return nil, ErrUserNotExist{0, login, 0}
  501. }
  502. return nil, err
  503. }
  504. if !autoRegister {
  505. return user, nil
  506. }
  507. user = &User{
  508. LowerName: strings.ToLower(login),
  509. Name: login,
  510. Email: login,
  511. Passwd: password,
  512. LoginType: LoginPAM,
  513. LoginSource: sourceID,
  514. LoginName: login,
  515. IsActive: true,
  516. }
  517. return user, CreateUser(user)
  518. }
  519. // ExternalUserLogin attempts a login using external source types.
  520. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  521. if !source.IsActived {
  522. return nil, ErrLoginSourceNotActived
  523. }
  524. var err error
  525. switch source.Type {
  526. case LoginLDAP, LoginDLDAP:
  527. user, err = LoginViaLDAP(user, login, password, source, autoRegister)
  528. case LoginSMTP:
  529. user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  530. case LoginPAM:
  531. user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  532. default:
  533. return nil, ErrUnsupportedLoginType
  534. }
  535. if err != nil {
  536. return nil, err
  537. }
  538. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  539. // user could be hint to resend confirm email.
  540. if user.ProhibitLogin {
  541. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  542. }
  543. return user, nil
  544. }
  545. // UserSignIn validates user name and password.
  546. func UserSignIn(username, password string) (*User, error) {
  547. var user *User
  548. if strings.Contains(username, "@") {
  549. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  550. // check same email
  551. cnt, err := x.Count(user)
  552. if err != nil {
  553. return nil, err
  554. }
  555. if cnt > 1 {
  556. return nil, ErrEmailAlreadyUsed{
  557. Email: user.Email,
  558. }
  559. }
  560. } else {
  561. trimmedUsername := strings.TrimSpace(username)
  562. if len(trimmedUsername) == 0 {
  563. return nil, ErrUserNotExist{0, username, 0}
  564. }
  565. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  566. }
  567. hasUser, err := x.Get(user)
  568. if err != nil {
  569. return nil, err
  570. }
  571. if hasUser {
  572. switch user.LoginType {
  573. case LoginNoType, LoginPlain, LoginOAuth2:
  574. if user.IsPasswordSet() && user.ValidatePassword(password) {
  575. // Update password hash if server password hash algorithm have changed
  576. if user.PasswdHashAlgo != setting.PasswordHashAlgo {
  577. user.HashPassword(password)
  578. if err := UpdateUserCols(user, "passwd", "passwd_hash_algo"); err != nil {
  579. return nil, err
  580. }
  581. }
  582. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  583. // user could be hint to resend confirm email.
  584. if user.ProhibitLogin {
  585. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  586. }
  587. return user, nil
  588. }
  589. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  590. default:
  591. var source LoginSource
  592. hasSource, err := x.ID(user.LoginSource).Get(&source)
  593. if err != nil {
  594. return nil, err
  595. } else if !hasSource {
  596. return nil, ErrLoginSourceNotExist{user.LoginSource}
  597. }
  598. return ExternalUserLogin(user, user.LoginName, password, &source, false)
  599. }
  600. }
  601. sources := make([]*LoginSource, 0, 5)
  602. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  603. return nil, err
  604. }
  605. for _, source := range sources {
  606. if source.IsOAuth2() {
  607. // don't try to authenticate against OAuth2 sources
  608. continue
  609. }
  610. authUser, err := ExternalUserLogin(nil, username, password, source, true)
  611. if err == nil {
  612. return authUser, nil
  613. }
  614. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  615. }
  616. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  617. }