login_source.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. "fmt"
  9. "net/smtp"
  10. "net/textproto"
  11. "os"
  12. "path"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/Unknwon/com"
  17. "github.com/go-macaron/binding"
  18. "github.com/go-xorm/core"
  19. "github.com/go-xorm/xorm"
  20. log "gopkg.in/clog.v1"
  21. "gopkg.in/ini.v1"
  22. "github.com/gogits/gogs/models/errors"
  23. "github.com/gogits/gogs/pkg/auth/ldap"
  24. "github.com/gogits/gogs/pkg/auth/pam"
  25. "github.com/gogits/gogs/pkg/setting"
  26. )
  27. type LoginType int
  28. // Note: new type must append to the end of list to maintain compatibility.
  29. const (
  30. LOGIN_NOTYPE LoginType = iota
  31. LOGIN_PLAIN // 1
  32. LOGIN_LDAP // 2
  33. LOGIN_SMTP // 3
  34. LOGIN_PAM // 4
  35. LOGIN_DLDAP // 5
  36. )
  37. var LoginNames = map[LoginType]string{
  38. LOGIN_LDAP: "LDAP (via BindDN)",
  39. LOGIN_DLDAP: "LDAP (simple auth)", // Via direct bind
  40. LOGIN_SMTP: "SMTP",
  41. LOGIN_PAM: "PAM",
  42. }
  43. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  44. ldap.SECURITY_PROTOCOL_UNENCRYPTED: "Unencrypted",
  45. ldap.SECURITY_PROTOCOL_LDAPS: "LDAPS",
  46. ldap.SECURITY_PROTOCOL_START_TLS: "StartTLS",
  47. }
  48. // Ensure structs implemented interface.
  49. var (
  50. _ core.Conversion = &LDAPConfig{}
  51. _ core.Conversion = &SMTPConfig{}
  52. _ core.Conversion = &PAMConfig{}
  53. )
  54. type LDAPConfig struct {
  55. *ldap.Source `ini:"config"`
  56. }
  57. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  58. return json.Unmarshal(bs, &cfg)
  59. }
  60. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  61. return json.Marshal(cfg)
  62. }
  63. func (cfg *LDAPConfig) SecurityProtocolName() string {
  64. return SecurityProtocolNames[cfg.SecurityProtocol]
  65. }
  66. type SMTPConfig struct {
  67. Auth string
  68. Host string
  69. Port int
  70. AllowedDomains string `xorm:"TEXT"`
  71. TLS bool `ini:"tls"`
  72. SkipVerify bool
  73. }
  74. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  75. return json.Unmarshal(bs, cfg)
  76. }
  77. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  78. return json.Marshal(cfg)
  79. }
  80. type PAMConfig struct {
  81. ServiceName string // PAM service (e.g. system-auth)
  82. }
  83. func (cfg *PAMConfig) FromDB(bs []byte) error {
  84. return json.Unmarshal(bs, &cfg)
  85. }
  86. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  87. return json.Marshal(cfg)
  88. }
  89. // AuthSourceFile contains information of an authentication source file.
  90. type AuthSourceFile struct {
  91. abspath string
  92. file *ini.File
  93. }
  94. // SetGeneral sets new value to the given key in the general (default) section.
  95. func (f *AuthSourceFile) SetGeneral(name, value string) {
  96. f.file.Section("").Key(name).SetValue(value)
  97. }
  98. // SetConfig sets new values to the "config" section.
  99. func (f *AuthSourceFile) SetConfig(cfg core.Conversion) error {
  100. return f.file.Section("config").ReflectFrom(cfg)
  101. }
  102. // Save writes updates into file system.
  103. func (f *AuthSourceFile) Save() error {
  104. return f.file.SaveTo(f.abspath)
  105. }
  106. // LoginSource represents an external way for authorizing users.
  107. type LoginSource struct {
  108. ID int64
  109. Type LoginType
  110. Name string `xorm:"UNIQUE"`
  111. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  112. Cfg core.Conversion `xorm:"TEXT"`
  113. Created time.Time `xorm:"-"`
  114. CreatedUnix int64
  115. Updated time.Time `xorm:"-"`
  116. UpdatedUnix int64
  117. LocalFile *AuthSourceFile `xorm:"-"`
  118. }
  119. func (s *LoginSource) BeforeInsert() {
  120. s.CreatedUnix = time.Now().Unix()
  121. s.UpdatedUnix = s.CreatedUnix
  122. }
  123. func (s *LoginSource) BeforeUpdate() {
  124. s.UpdatedUnix = time.Now().Unix()
  125. }
  126. // Cell2Int64 converts a xorm.Cell type to int64,
  127. // and handles possible irregular cases.
  128. func Cell2Int64(val xorm.Cell) int64 {
  129. switch (*val).(type) {
  130. case []uint8:
  131. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  132. return com.StrTo(string((*val).([]uint8))).MustInt64()
  133. }
  134. return (*val).(int64)
  135. }
  136. func (s *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  137. switch colName {
  138. case "type":
  139. switch LoginType(Cell2Int64(val)) {
  140. case LOGIN_LDAP, LOGIN_DLDAP:
  141. s.Cfg = new(LDAPConfig)
  142. case LOGIN_SMTP:
  143. s.Cfg = new(SMTPConfig)
  144. case LOGIN_PAM:
  145. s.Cfg = new(PAMConfig)
  146. default:
  147. panic("unrecognized login source type: " + com.ToStr(*val))
  148. }
  149. }
  150. }
  151. func (s *LoginSource) AfterSet(colName string, _ xorm.Cell) {
  152. switch colName {
  153. case "created_unix":
  154. s.Created = time.Unix(s.CreatedUnix, 0).Local()
  155. case "updated_unix":
  156. s.Updated = time.Unix(s.UpdatedUnix, 0).Local()
  157. }
  158. }
  159. func (s *LoginSource) TypeName() string {
  160. return LoginNames[s.Type]
  161. }
  162. func (s *LoginSource) IsLDAP() bool {
  163. return s.Type == LOGIN_LDAP
  164. }
  165. func (s *LoginSource) IsDLDAP() bool {
  166. return s.Type == LOGIN_DLDAP
  167. }
  168. func (s *LoginSource) IsSMTP() bool {
  169. return s.Type == LOGIN_SMTP
  170. }
  171. func (s *LoginSource) IsPAM() bool {
  172. return s.Type == LOGIN_PAM
  173. }
  174. func (s *LoginSource) HasTLS() bool {
  175. return ((s.IsLDAP() || s.IsDLDAP()) &&
  176. s.LDAP().SecurityProtocol > ldap.SECURITY_PROTOCOL_UNENCRYPTED) ||
  177. s.IsSMTP()
  178. }
  179. func (s *LoginSource) UseTLS() bool {
  180. switch s.Type {
  181. case LOGIN_LDAP, LOGIN_DLDAP:
  182. return s.LDAP().SecurityProtocol != ldap.SECURITY_PROTOCOL_UNENCRYPTED
  183. case LOGIN_SMTP:
  184. return s.SMTP().TLS
  185. }
  186. return false
  187. }
  188. func (s *LoginSource) SkipVerify() bool {
  189. switch s.Type {
  190. case LOGIN_LDAP, LOGIN_DLDAP:
  191. return s.LDAP().SkipVerify
  192. case LOGIN_SMTP:
  193. return s.SMTP().SkipVerify
  194. }
  195. return false
  196. }
  197. func (s *LoginSource) LDAP() *LDAPConfig {
  198. return s.Cfg.(*LDAPConfig)
  199. }
  200. func (s *LoginSource) SMTP() *SMTPConfig {
  201. return s.Cfg.(*SMTPConfig)
  202. }
  203. func (s *LoginSource) PAM() *PAMConfig {
  204. return s.Cfg.(*PAMConfig)
  205. }
  206. func CreateLoginSource(source *LoginSource) error {
  207. has, err := x.Get(&LoginSource{Name: source.Name})
  208. if err != nil {
  209. return err
  210. } else if has {
  211. return ErrLoginSourceAlreadyExist{source.Name}
  212. }
  213. _, err = x.Insert(source)
  214. return err
  215. }
  216. // LoginSources returns all login sources defined.
  217. func LoginSources() ([]*LoginSource, error) {
  218. sources := make([]*LoginSource, 0, 2)
  219. if err := x.Find(&sources); err != nil {
  220. return nil, err
  221. }
  222. return append(sources, localLoginSources.List()...), nil
  223. }
  224. // ActivatedLoginSources returns login sources that are currently activated.
  225. func ActivatedLoginSources() ([]*LoginSource, error) {
  226. sources := make([]*LoginSource, 0, 2)
  227. if err := x.Where("is_actived = ?", true).Find(&sources); err != nil {
  228. return nil, fmt.Errorf("find activated login sources: %v", err)
  229. }
  230. return append(sources, localLoginSources.ActivatedList()...), nil
  231. }
  232. // GetLoginSourceByID returns login source by given ID.
  233. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  234. source := new(LoginSource)
  235. has, err := x.Id(id).Get(source)
  236. if err != nil {
  237. return nil, err
  238. } else if !has {
  239. return localLoginSources.GetLoginSourceByID(id)
  240. }
  241. return source, nil
  242. }
  243. // UpdateLoginSource updates information of login source to database or local file.
  244. func UpdateLoginSource(source *LoginSource) error {
  245. if source.LocalFile == nil {
  246. _, err := x.Id(source.ID).AllCols().Update(source)
  247. return err
  248. }
  249. source.LocalFile.SetGeneral("name", source.Name)
  250. source.LocalFile.SetGeneral("is_activated", com.ToStr(source.IsActived))
  251. if err := source.LocalFile.SetConfig(source.Cfg); err != nil {
  252. return fmt.Errorf("LocalFile.SetConfig: %v", err)
  253. } else if err = source.LocalFile.Save(); err != nil {
  254. return fmt.Errorf("LocalFile.Save: %v", err)
  255. }
  256. localLoginSources.UpdateLoginSource(source)
  257. return nil
  258. }
  259. func DeleteSource(source *LoginSource) error {
  260. count, err := x.Count(&User{LoginSource: source.ID})
  261. if err != nil {
  262. return err
  263. } else if count > 0 {
  264. return ErrLoginSourceInUse{source.ID}
  265. }
  266. _, err = x.Id(source.ID).Delete(new(LoginSource))
  267. return err
  268. }
  269. // CountLoginSources returns total number of login sources.
  270. func CountLoginSources() int64 {
  271. count, _ := x.Count(new(LoginSource))
  272. return count + int64(localLoginSources.Len())
  273. }
  274. // LocalLoginSources contains authentication sources configured and loaded from local files.
  275. // Calling its methods is thread-safe; otherwise, please maintain the mutex accordingly.
  276. type LocalLoginSources struct {
  277. sync.RWMutex
  278. sources []*LoginSource
  279. }
  280. func (s *LocalLoginSources) Len() int {
  281. return len(s.sources)
  282. }
  283. // List returns full clone of login sources.
  284. func (s *LocalLoginSources) List() []*LoginSource {
  285. s.RLock()
  286. defer s.RUnlock()
  287. list := make([]*LoginSource, s.Len())
  288. for i := range s.sources {
  289. list[i] = &LoginSource{}
  290. *list[i] = *s.sources[i]
  291. }
  292. return list
  293. }
  294. // ActivatedList returns clone of activated login sources.
  295. func (s *LocalLoginSources) ActivatedList() []*LoginSource {
  296. s.RLock()
  297. defer s.RUnlock()
  298. list := make([]*LoginSource, 0, 2)
  299. for i := range s.sources {
  300. if !s.sources[i].IsActived {
  301. continue
  302. }
  303. source := &LoginSource{}
  304. *source = *s.sources[i]
  305. list = append(list, source)
  306. }
  307. return list
  308. }
  309. // GetLoginSourceByID returns a clone of login source by given ID.
  310. func (s *LocalLoginSources) GetLoginSourceByID(id int64) (*LoginSource, error) {
  311. s.RLock()
  312. defer s.RUnlock()
  313. for i := range s.sources {
  314. if s.sources[i].ID == id {
  315. source := &LoginSource{}
  316. *source = *s.sources[i]
  317. return source, nil
  318. }
  319. }
  320. return nil, errors.LoginSourceNotExist{id}
  321. }
  322. // UpdateLoginSource updates in-memory copy of the authentication source.
  323. func (s *LocalLoginSources) UpdateLoginSource(source *LoginSource) {
  324. s.Lock()
  325. defer s.Unlock()
  326. source.Updated = time.Now()
  327. for i := range s.sources {
  328. if s.sources[i].ID == source.ID {
  329. *s.sources[i] = *source
  330. break
  331. }
  332. }
  333. }
  334. var localLoginSources = &LocalLoginSources{}
  335. // LoadAuthSources loads authentication sources from local files
  336. // and converts them into login sources.
  337. func LoadAuthSources() {
  338. authdPath := path.Join(setting.CustomPath, "conf/auth.d")
  339. if !com.IsDir(authdPath) {
  340. return
  341. }
  342. paths, err := com.GetFileListBySuffix(authdPath, ".conf")
  343. if err != nil {
  344. log.Fatal(2, "Failed to list authentication sources: %v", err)
  345. }
  346. localLoginSources.sources = make([]*LoginSource, 0, len(paths))
  347. for _, fpath := range paths {
  348. authSource, err := ini.Load(fpath)
  349. if err != nil {
  350. log.Fatal(2, "Failed to load authentication source: %v", err)
  351. }
  352. authSource.NameMapper = ini.TitleUnderscore
  353. // Set general attributes
  354. s := authSource.Section("")
  355. loginSource := &LoginSource{
  356. ID: s.Key("id").MustInt64(),
  357. Name: s.Key("name").String(),
  358. IsActived: s.Key("is_activated").MustBool(),
  359. LocalFile: &AuthSourceFile{
  360. abspath: fpath,
  361. file: authSource,
  362. },
  363. }
  364. fi, err := os.Stat(fpath)
  365. if err != nil {
  366. log.Fatal(2, "Failed to load authentication source: %v", err)
  367. }
  368. loginSource.Updated = fi.ModTime()
  369. // Parse authentication source file
  370. authType := s.Key("type").String()
  371. switch authType {
  372. case "ldap_bind_dn":
  373. loginSource.Type = LOGIN_LDAP
  374. loginSource.Cfg = &LDAPConfig{}
  375. case "ldap_simple_auth":
  376. loginSource.Type = LOGIN_DLDAP
  377. loginSource.Cfg = &LDAPConfig{}
  378. case "smtp":
  379. loginSource.Type = LOGIN_SMTP
  380. loginSource.Cfg = &SMTPConfig{}
  381. case "pam":
  382. loginSource.Type = LOGIN_PAM
  383. loginSource.Cfg = &PAMConfig{}
  384. default:
  385. log.Fatal(2, "Failed to load authentication source: unknown type '%s'", authType)
  386. }
  387. if err = authSource.Section("config").MapTo(loginSource.Cfg); err != nil {
  388. log.Fatal(2, "Failed to parse authentication source 'config': %v", err)
  389. }
  390. localLoginSources.sources = append(localLoginSources.sources, loginSource)
  391. }
  392. }
  393. // .____ ________ _____ __________
  394. // | | \______ \ / _ \\______ \
  395. // | | | | \ / /_\ \| ___/
  396. // | |___ | ` \/ | \ |
  397. // |_______ \/_______ /\____|__ /____|
  398. // \/ \/ \/
  399. func composeFullName(firstname, surname, username string) string {
  400. switch {
  401. case len(firstname) == 0 && len(surname) == 0:
  402. return username
  403. case len(firstname) == 0:
  404. return surname
  405. case len(surname) == 0:
  406. return firstname
  407. default:
  408. return firstname + " " + surname
  409. }
  410. }
  411. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  412. // and create a local user if success when enabled.
  413. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  414. username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LOGIN_DLDAP)
  415. if !succeed {
  416. // User not in LDAP, do nothing
  417. return nil, errors.UserNotExist{0, login}
  418. }
  419. if !autoRegister {
  420. return user, nil
  421. }
  422. // Fallback.
  423. if len(username) == 0 {
  424. username = login
  425. }
  426. // Validate username make sure it satisfies requirement.
  427. if binding.AlphaDashDotPattern.MatchString(username) {
  428. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", username)
  429. }
  430. if len(mail) == 0 {
  431. mail = fmt.Sprintf("%s@localhost", username)
  432. }
  433. user = &User{
  434. LowerName: strings.ToLower(username),
  435. Name: username,
  436. FullName: composeFullName(fn, sn, username),
  437. Email: mail,
  438. LoginType: source.Type,
  439. LoginSource: source.ID,
  440. LoginName: login,
  441. IsActive: true,
  442. IsAdmin: isAdmin,
  443. }
  444. ok, err := IsUserExist(0, user.Name)
  445. if err != nil {
  446. return user, err
  447. }
  448. if ok {
  449. return user, UpdateUser(user)
  450. }
  451. return user, CreateUser(user)
  452. }
  453. // _________ __________________________
  454. // / _____/ / \__ ___/\______ \
  455. // \_____ \ / \ / \| | | ___/
  456. // / \/ Y \ | | |
  457. // /_______ /\____|__ /____| |____|
  458. // \/ \/
  459. type smtpLoginAuth struct {
  460. username, password string
  461. }
  462. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  463. return "LOGIN", []byte(auth.username), nil
  464. }
  465. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  466. if more {
  467. switch string(fromServer) {
  468. case "Username:":
  469. return []byte(auth.username), nil
  470. case "Password:":
  471. return []byte(auth.password), nil
  472. }
  473. }
  474. return nil, nil
  475. }
  476. const (
  477. SMTP_PLAIN = "PLAIN"
  478. SMTP_LOGIN = "LOGIN"
  479. )
  480. var SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  481. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  482. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  483. if err != nil {
  484. return err
  485. }
  486. defer c.Close()
  487. if err = c.Hello("gogs"); err != nil {
  488. return err
  489. }
  490. if cfg.TLS {
  491. if ok, _ := c.Extension("STARTTLS"); ok {
  492. if err = c.StartTLS(&tls.Config{
  493. InsecureSkipVerify: cfg.SkipVerify,
  494. ServerName: cfg.Host,
  495. }); err != nil {
  496. return err
  497. }
  498. } else {
  499. return errors.New("SMTP server unsupports TLS")
  500. }
  501. }
  502. if ok, _ := c.Extension("AUTH"); ok {
  503. if err = c.Auth(a); err != nil {
  504. return err
  505. }
  506. return nil
  507. }
  508. return errors.New("Unsupported SMTP authentication method")
  509. }
  510. // LoginViaSMTP queries if login/password is valid against the SMTP,
  511. // and create a local user if success when enabled.
  512. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  513. // Verify allowed domains.
  514. if len(cfg.AllowedDomains) > 0 {
  515. idx := strings.Index(login, "@")
  516. if idx == -1 {
  517. return nil, errors.UserNotExist{0, login}
  518. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  519. return nil, errors.UserNotExist{0, login}
  520. }
  521. }
  522. var auth smtp.Auth
  523. if cfg.Auth == SMTP_PLAIN {
  524. auth = smtp.PlainAuth("", login, password, cfg.Host)
  525. } else if cfg.Auth == SMTP_LOGIN {
  526. auth = &smtpLoginAuth{login, password}
  527. } else {
  528. return nil, errors.New("Unsupported SMTP authentication type")
  529. }
  530. if err := SMTPAuth(auth, cfg); err != nil {
  531. // Check standard error format first,
  532. // then fallback to worse case.
  533. tperr, ok := err.(*textproto.Error)
  534. if (ok && tperr.Code == 535) ||
  535. strings.Contains(err.Error(), "Username and Password not accepted") {
  536. return nil, errors.UserNotExist{0, login}
  537. }
  538. return nil, err
  539. }
  540. if !autoRegister {
  541. return user, nil
  542. }
  543. username := login
  544. idx := strings.Index(login, "@")
  545. if idx > -1 {
  546. username = login[:idx]
  547. }
  548. user = &User{
  549. LowerName: strings.ToLower(username),
  550. Name: strings.ToLower(username),
  551. Email: login,
  552. Passwd: password,
  553. LoginType: LOGIN_SMTP,
  554. LoginSource: sourceID,
  555. LoginName: login,
  556. IsActive: true,
  557. }
  558. return user, CreateUser(user)
  559. }
  560. // __________ _____ _____
  561. // \______ \/ _ \ / \
  562. // | ___/ /_\ \ / \ / \
  563. // | | / | \/ Y \
  564. // |____| \____|__ /\____|__ /
  565. // \/ \/
  566. // LoginViaPAM queries if login/password is valid against the PAM,
  567. // and create a local user if success when enabled.
  568. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  569. if err := pam.PAMAuth(cfg.ServiceName, login, password); err != nil {
  570. if strings.Contains(err.Error(), "Authentication failure") {
  571. return nil, errors.UserNotExist{0, login}
  572. }
  573. return nil, err
  574. }
  575. if !autoRegister {
  576. return user, nil
  577. }
  578. user = &User{
  579. LowerName: strings.ToLower(login),
  580. Name: login,
  581. Email: login,
  582. Passwd: password,
  583. LoginType: LOGIN_PAM,
  584. LoginSource: sourceID,
  585. LoginName: login,
  586. IsActive: true,
  587. }
  588. return user, CreateUser(user)
  589. }
  590. func remoteUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  591. if !source.IsActived {
  592. return nil, errors.LoginSourceNotActivated{source.ID}
  593. }
  594. switch source.Type {
  595. case LOGIN_LDAP, LOGIN_DLDAP:
  596. return LoginViaLDAP(user, login, password, source, autoRegister)
  597. case LOGIN_SMTP:
  598. return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  599. case LOGIN_PAM:
  600. return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  601. }
  602. return nil, errors.InvalidLoginSourceType{source.Type}
  603. }
  604. // UserLogin validates user name and password via given login source ID.
  605. // If the loginSourceID is negative, it will abort login process if user is not found.
  606. func UserLogin(username, password string, loginSourceID int64) (*User, error) {
  607. var user *User
  608. if strings.Contains(username, "@") {
  609. user = &User{Email: strings.ToLower(username)}
  610. } else {
  611. user = &User{LowerName: strings.ToLower(username)}
  612. }
  613. hasUser, err := x.Get(user)
  614. if err != nil {
  615. return nil, fmt.Errorf("get user record: %v", err)
  616. }
  617. if hasUser {
  618. // Note: This check is unnecessary but to reduce user confusion at login page
  619. // and make it more consistent at user's perspective.
  620. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  621. return nil, errors.LoginSourceMismatch{loginSourceID, user.LoginSource}
  622. }
  623. // Validate password hash fetched from database for local accounts
  624. if user.LoginType == LOGIN_NOTYPE ||
  625. user.LoginType == LOGIN_PLAIN {
  626. if user.ValidatePassword(password) {
  627. return user, nil
  628. }
  629. return nil, errors.UserNotExist{user.ID, user.Name}
  630. }
  631. // Remote login to the login source the user is associated with
  632. source, err := GetLoginSourceByID(user.LoginSource)
  633. if err != nil {
  634. return nil, err
  635. }
  636. return remoteUserLogin(user, user.LoginName, password, source, false)
  637. }
  638. // Non-local login source is always greater than 0
  639. if loginSourceID <= 0 {
  640. return nil, errors.UserNotExist{-1, username}
  641. }
  642. source, err := GetLoginSourceByID(loginSourceID)
  643. if err != nil {
  644. return nil, err
  645. }
  646. return remoteUserLogin(nil, username, password, source, true)
  647. }