login_source.go 20 KB

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