login_source.go 20 KB

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