login_source.go 20 KB

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