login_source.go 20 KB

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