login_source.go 22 KB

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