login_source.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. "github.com/Unknwon/com"
  24. raven "github.com/getsentry/raven-go"
  25. "github.com/go-macaron/binding"
  26. "github.com/go-xorm/core"
  27. "github.com/go-xorm/xorm"
  28. "github.com/json-iterator/go"
  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. LOGIN_NOTYPE LoginType = iota
  36. LOGIN_PLAIN // 1
  37. LOGIN_LDAP // 2
  38. LOGIN_SMTP // 3
  39. LOGIN_PAM // 4
  40. LOGIN_DLDAP // 5
  41. LOGIN_GITHUB // 6
  42. )
  43. var LoginNames = map[LoginType]string{
  44. LOGIN_LDAP: "LDAP (via BindDN)",
  45. LOGIN_DLDAP: "LDAP (simple auth)", // Via direct bind
  46. LOGIN_SMTP: "SMTP",
  47. LOGIN_PAM: "PAM",
  48. LOGIN_GITHUB: "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 LOGIN_LDAP, LOGIN_DLDAP:
  159. s.Cfg = new(LDAPConfig)
  160. case LOGIN_SMTP:
  161. s.Cfg = new(SMTPConfig)
  162. case LOGIN_PAM:
  163. s.Cfg = new(PAMConfig)
  164. case LOGIN_GITHUB:
  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 == LOGIN_LDAP
  184. }
  185. func (s *LoginSource) IsDLDAP() bool {
  186. return s.Type == LOGIN_DLDAP
  187. }
  188. func (s *LoginSource) IsSMTP() bool {
  189. return s.Type == LOGIN_SMTP
  190. }
  191. func (s *LoginSource) IsPAM() bool {
  192. return s.Type == LOGIN_PAM
  193. }
  194. func (s *LoginSource) IsGitHub() bool {
  195. return s.Type == LOGIN_GITHUB
  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 LOGIN_LDAP, LOGIN_DLDAP:
  205. return s.LDAP().SecurityProtocol != ldap.SECURITY_PROTOCOL_UNENCRYPTED
  206. case LOGIN_SMTP:
  207. return s.SMTP().TLS
  208. }
  209. return false
  210. }
  211. func (s *LoginSource) SkipVerify() bool {
  212. switch s.Type {
  213. case LOGIN_LDAP, LOGIN_DLDAP:
  214. return s.LDAP().SkipVerify
  215. case LOGIN_SMTP:
  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. func CreateLoginSource(source *LoginSource) error {
  233. has, err := x.Get(&LoginSource{Name: source.Name})
  234. if err != nil {
  235. return err
  236. } else if has {
  237. return ErrLoginSourceAlreadyExist{source.Name}
  238. }
  239. _, err = x.Insert(source)
  240. if err != nil {
  241. return err
  242. } else if source.IsDefault {
  243. return ResetNonDefaultLoginSources(source)
  244. }
  245. return nil
  246. }
  247. // LoginSources returns all login sources defined.
  248. func LoginSources() ([]*LoginSource, error) {
  249. sources := make([]*LoginSource, 0, 2)
  250. if err := x.Find(&sources); err != nil {
  251. return nil, err
  252. }
  253. return append(sources, localLoginSources.List()...), nil
  254. }
  255. // ActivatedLoginSources returns login sources that are currently activated.
  256. func ActivatedLoginSources() ([]*LoginSource, error) {
  257. sources := make([]*LoginSource, 0, 2)
  258. if err := x.Where("is_actived = ?", true).Find(&sources); err != nil {
  259. return nil, fmt.Errorf("find activated login sources: %v", err)
  260. }
  261. return append(sources, localLoginSources.ActivatedList()...), nil
  262. }
  263. // GetLoginSourceByID returns login source by given ID.
  264. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  265. source := new(LoginSource)
  266. has, err := x.Id(id).Get(source)
  267. if err != nil {
  268. return nil, err
  269. } else if !has {
  270. return localLoginSources.GetLoginSourceByID(id)
  271. }
  272. return source, nil
  273. }
  274. // ResetNonDefaultLoginSources clean other default source flag
  275. func ResetNonDefaultLoginSources(source *LoginSource) error {
  276. // update changes to DB
  277. if _, err := x.NotIn("id", []int64{source.ID}).Cols("is_default").Update(&LoginSource{IsDefault: false}); err != nil {
  278. return err
  279. }
  280. // write changes to local authentications
  281. for i := range localLoginSources.sources {
  282. if localLoginSources.sources[i].LocalFile != nil && localLoginSources.sources[i].ID != source.ID {
  283. localLoginSources.sources[i].LocalFile.SetGeneral("is_default", "false")
  284. if err := localLoginSources.sources[i].LocalFile.SetConfig(source.Cfg); err != nil {
  285. return fmt.Errorf("LocalFile.SetConfig: %v", err)
  286. } else if err = localLoginSources.sources[i].LocalFile.Save(); err != nil {
  287. return fmt.Errorf("LocalFile.Save: %v", err)
  288. }
  289. }
  290. }
  291. // flush memory so that web page can show the same behaviors
  292. localLoginSources.UpdateLoginSource(source)
  293. return nil
  294. }
  295. // UpdateLoginSource updates information of login source to database or local file.
  296. func UpdateLoginSource(source *LoginSource) error {
  297. if source.LocalFile == nil {
  298. if _, err := x.Id(source.ID).AllCols().Update(source); err != nil {
  299. return err
  300. } else {
  301. return ResetNonDefaultLoginSources(source)
  302. }
  303. }
  304. source.LocalFile.SetGeneral("name", source.Name)
  305. source.LocalFile.SetGeneral("is_activated", com.ToStr(source.IsActived))
  306. source.LocalFile.SetGeneral("is_default", com.ToStr(source.IsDefault))
  307. if err := source.LocalFile.SetConfig(source.Cfg); err != nil {
  308. return fmt.Errorf("LocalFile.SetConfig: %v", err)
  309. } else if err = source.LocalFile.Save(); err != nil {
  310. return fmt.Errorf("LocalFile.Save: %v", err)
  311. }
  312. return ResetNonDefaultLoginSources(source)
  313. }
  314. func DeleteSource(source *LoginSource) error {
  315. count, err := x.Count(&User{LoginSource: source.ID})
  316. if err != nil {
  317. return err
  318. } else if count > 0 {
  319. return ErrLoginSourceInUse{source.ID}
  320. }
  321. _, err = x.Id(source.ID).Delete(new(LoginSource))
  322. return err
  323. }
  324. // CountLoginSources returns total number of login sources.
  325. func CountLoginSources() int64 {
  326. count, _ := x.Count(new(LoginSource))
  327. return count + int64(localLoginSources.Len())
  328. }
  329. // LocalLoginSources contains authentication sources configured and loaded from local files.
  330. // Calling its methods is thread-safe; otherwise, please maintain the mutex accordingly.
  331. type LocalLoginSources struct {
  332. sync.RWMutex
  333. sources []*LoginSource
  334. }
  335. func (s *LocalLoginSources) Len() int {
  336. return len(s.sources)
  337. }
  338. // List returns full clone of login sources.
  339. func (s *LocalLoginSources) List() []*LoginSource {
  340. s.RLock()
  341. defer s.RUnlock()
  342. list := make([]*LoginSource, s.Len())
  343. for i := range s.sources {
  344. list[i] = &LoginSource{}
  345. *list[i] = *s.sources[i]
  346. }
  347. return list
  348. }
  349. // ActivatedList returns clone of activated login sources.
  350. func (s *LocalLoginSources) ActivatedList() []*LoginSource {
  351. s.RLock()
  352. defer s.RUnlock()
  353. list := make([]*LoginSource, 0, 2)
  354. for i := range s.sources {
  355. if !s.sources[i].IsActived {
  356. continue
  357. }
  358. source := &LoginSource{}
  359. *source = *s.sources[i]
  360. list = append(list, source)
  361. }
  362. return list
  363. }
  364. // GetLoginSourceByID returns a clone of login source by given ID.
  365. func (s *LocalLoginSources) GetLoginSourceByID(id int64) (*LoginSource, error) {
  366. s.RLock()
  367. defer s.RUnlock()
  368. for i := range s.sources {
  369. if s.sources[i].ID == id {
  370. source := &LoginSource{}
  371. *source = *s.sources[i]
  372. return source, nil
  373. }
  374. }
  375. return nil, errors.LoginSourceNotExist{id}
  376. }
  377. // UpdateLoginSource updates in-memory copy of the authentication source.
  378. func (s *LocalLoginSources) UpdateLoginSource(source *LoginSource) {
  379. s.Lock()
  380. defer s.Unlock()
  381. source.Updated = time.Now()
  382. for i := range s.sources {
  383. if s.sources[i].ID == source.ID {
  384. *s.sources[i] = *source
  385. } else if source.IsDefault {
  386. s.sources[i].IsDefault = false
  387. }
  388. }
  389. }
  390. var localLoginSources = &LocalLoginSources{}
  391. // LoadAuthSources loads authentication sources from local files
  392. // and converts them into login sources.
  393. func LoadAuthSources() {
  394. authdPath := path.Join(setting.CustomPath, "conf/auth.d")
  395. if !com.IsDir(authdPath) {
  396. return
  397. }
  398. paths, err := com.GetFileListBySuffix(authdPath, ".conf")
  399. if err != nil {
  400. raven.CaptureErrorAndWait(err, nil)
  401. log.Fatal(2, "Failed to list authentication sources: %v", err)
  402. }
  403. localLoginSources.sources = make([]*LoginSource, 0, len(paths))
  404. for _, fpath := range paths {
  405. authSource, err := ini.Load(fpath)
  406. if err != nil {
  407. raven.CaptureErrorAndWait(err, nil)
  408. log.Fatal(2, "Failed to load authentication source: %v", err)
  409. }
  410. authSource.NameMapper = ini.TitleUnderscore
  411. // Set general attributes
  412. s := authSource.Section("")
  413. loginSource := &LoginSource{
  414. ID: s.Key("id").MustInt64(),
  415. Name: s.Key("name").String(),
  416. IsActived: s.Key("is_activated").MustBool(),
  417. IsDefault: s.Key("is_default").MustBool(),
  418. LocalFile: &AuthSourceFile{
  419. abspath: fpath,
  420. file: authSource,
  421. },
  422. }
  423. fi, err := os.Stat(fpath)
  424. if err != nil {
  425. raven.CaptureErrorAndWait(err, nil)
  426. log.Fatal(2, "Failed to load authentication source: %v", err)
  427. }
  428. loginSource.Updated = fi.ModTime()
  429. // Parse authentication source file
  430. authType := s.Key("type").String()
  431. switch authType {
  432. case "ldap_bind_dn":
  433. loginSource.Type = LOGIN_LDAP
  434. loginSource.Cfg = &LDAPConfig{}
  435. case "ldap_simple_auth":
  436. loginSource.Type = LOGIN_DLDAP
  437. loginSource.Cfg = &LDAPConfig{}
  438. case "smtp":
  439. loginSource.Type = LOGIN_SMTP
  440. loginSource.Cfg = &SMTPConfig{}
  441. case "pam":
  442. loginSource.Type = LOGIN_PAM
  443. loginSource.Cfg = &PAMConfig{}
  444. case "github":
  445. loginSource.Type = LOGIN_GITHUB
  446. loginSource.Cfg = &GitHubConfig{}
  447. default:
  448. raven.CaptureErrorAndWait(err, nil)
  449. log.Fatal(2, "Failed to load authentication source: unknown type '%s'", authType)
  450. }
  451. if err = authSource.Section("config").MapTo(loginSource.Cfg); err != nil {
  452. raven.CaptureErrorAndWait(err, nil)
  453. log.Fatal(2, "Failed to parse authentication source 'config': %v", err)
  454. }
  455. localLoginSources.sources = append(localLoginSources.sources, loginSource)
  456. }
  457. }
  458. func composeFullName(firstname, surname, username string) string {
  459. switch {
  460. case len(firstname) == 0 && len(surname) == 0:
  461. return username
  462. case len(firstname) == 0:
  463. return surname
  464. case len(surname) == 0:
  465. return firstname
  466. default:
  467. return firstname + " " + surname
  468. }
  469. }
  470. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  471. // and create a local user if success when enabled.
  472. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  473. username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LOGIN_DLDAP)
  474. if !succeed {
  475. // User not in LDAP, do nothing
  476. return nil, errors.UserNotExist{0, login}
  477. }
  478. if !autoRegister {
  479. return user, nil
  480. }
  481. // Fallback.
  482. if len(username) == 0 {
  483. username = login
  484. }
  485. // Validate username make sure it satisfies requirement.
  486. if binding.AlphaDashDotPattern.MatchString(username) {
  487. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", username)
  488. }
  489. if len(mail) == 0 {
  490. mail = fmt.Sprintf("%s@localhost", username)
  491. }
  492. user = &User{
  493. LowerName: strings.ToLower(username),
  494. Name: username,
  495. FullName: composeFullName(fn, sn, username),
  496. Email: mail,
  497. LoginType: source.Type,
  498. LoginSource: source.ID,
  499. LoginName: login,
  500. IsActive: true,
  501. IsAdmin: isAdmin,
  502. }
  503. ok, err := IsUserExist(0, user.Name)
  504. if err != nil {
  505. return user, err
  506. }
  507. if ok {
  508. return user, UpdateUser(user)
  509. }
  510. return user, CreateUser(user)
  511. }
  512. type smtpLoginAuth struct {
  513. username, password string
  514. }
  515. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  516. return "LOGIN", []byte(auth.username), nil
  517. }
  518. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  519. if more {
  520. switch string(fromServer) {
  521. case "Username:":
  522. return []byte(auth.username), nil
  523. case "Password:":
  524. return []byte(auth.password), nil
  525. }
  526. }
  527. return nil, nil
  528. }
  529. const (
  530. SMTP_PLAIN = "PLAIN"
  531. SMTP_LOGIN = "LOGIN"
  532. )
  533. var SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  534. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  535. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  536. if err != nil {
  537. return err
  538. }
  539. defer c.Close()
  540. if err = c.Hello("gitote"); err != nil {
  541. return err
  542. }
  543. if cfg.TLS {
  544. if ok, _ := c.Extension("STARTTLS"); ok {
  545. if err = c.StartTLS(&tls.Config{
  546. InsecureSkipVerify: cfg.SkipVerify,
  547. ServerName: cfg.Host,
  548. }); err != nil {
  549. return err
  550. }
  551. } else {
  552. return errors.New("SMTP server unsupports TLS")
  553. }
  554. }
  555. if ok, _ := c.Extension("AUTH"); ok {
  556. if err = c.Auth(a); err != nil {
  557. return err
  558. }
  559. return nil
  560. }
  561. return errors.New("Unsupported SMTP authentication method")
  562. }
  563. // LoginViaSMTP queries if login/password is valid against the SMTP,
  564. // and create a local user if success when enabled.
  565. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  566. // Verify allowed domains.
  567. if len(cfg.AllowedDomains) > 0 {
  568. idx := strings.Index(login, "@")
  569. if idx == -1 {
  570. return nil, errors.UserNotExist{0, login}
  571. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  572. return nil, errors.UserNotExist{0, login}
  573. }
  574. }
  575. var auth smtp.Auth
  576. if cfg.Auth == SMTP_PLAIN {
  577. auth = smtp.PlainAuth("", login, password, cfg.Host)
  578. } else if cfg.Auth == SMTP_LOGIN {
  579. auth = &smtpLoginAuth{login, password}
  580. } else {
  581. return nil, errors.New("Unsupported SMTP authentication type")
  582. }
  583. if err := SMTPAuth(auth, cfg); err != nil {
  584. // Check standard error format first,
  585. // then fallback to worse case.
  586. tperr, ok := err.(*textproto.Error)
  587. if (ok && tperr.Code == 535) ||
  588. strings.Contains(err.Error(), "Username and Password not accepted") {
  589. return nil, errors.UserNotExist{0, login}
  590. }
  591. return nil, err
  592. }
  593. if !autoRegister {
  594. return user, nil
  595. }
  596. username := login
  597. idx := strings.Index(login, "@")
  598. if idx > -1 {
  599. username = login[:idx]
  600. }
  601. user = &User{
  602. LowerName: strings.ToLower(username),
  603. Name: strings.ToLower(username),
  604. Email: login,
  605. Passwd: password,
  606. LoginType: LOGIN_SMTP,
  607. LoginSource: sourceID,
  608. LoginName: login,
  609. IsActive: true,
  610. }
  611. return user, CreateUser(user)
  612. }
  613. // LoginViaPAM queries if login/password is valid against the PAM,
  614. // and create a local user if success when enabled.
  615. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  616. if err := pam.PAMAuth(cfg.ServiceName, login, password); err != nil {
  617. if strings.Contains(err.Error(), "Authentication failure") {
  618. return nil, errors.UserNotExist{0, login}
  619. }
  620. return nil, err
  621. }
  622. if !autoRegister {
  623. return user, nil
  624. }
  625. user = &User{
  626. LowerName: strings.ToLower(login),
  627. Name: login,
  628. Email: login,
  629. Passwd: password,
  630. LoginType: LOGIN_PAM,
  631. LoginSource: sourceID,
  632. LoginName: login,
  633. IsActive: true,
  634. }
  635. return user, CreateUser(user)
  636. }
  637. func LoginViaGitHub(user *User, login, password string, sourceID int64, cfg *GitHubConfig, autoRegister bool) (*User, error) {
  638. fullname, email, url, location, err := github.Authenticate(cfg.APIEndpoint, login, password)
  639. if err != nil {
  640. if strings.Contains(err.Error(), "401") {
  641. return nil, errors.UserNotExist{0, login}
  642. }
  643. return nil, err
  644. }
  645. if !autoRegister {
  646. return user, nil
  647. }
  648. user = &User{
  649. LowerName: strings.ToLower(login),
  650. Name: login,
  651. FullName: fullname,
  652. Email: email,
  653. Website: url,
  654. Passwd: password,
  655. LoginType: LOGIN_GITHUB,
  656. LoginSource: sourceID,
  657. LoginName: login,
  658. IsActive: true,
  659. Location: location,
  660. }
  661. return user, CreateUser(user)
  662. }
  663. func remoteUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  664. if !source.IsActived {
  665. return nil, errors.LoginSourceNotActivated{source.ID}
  666. }
  667. switch source.Type {
  668. case LOGIN_LDAP, LOGIN_DLDAP:
  669. return LoginViaLDAP(user, login, password, source, autoRegister)
  670. case LOGIN_SMTP:
  671. return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  672. case LOGIN_PAM:
  673. return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  674. case LOGIN_GITHUB:
  675. return LoginViaGitHub(user, login, password, source.ID, source.Cfg.(*GitHubConfig), autoRegister)
  676. }
  677. return nil, errors.InvalidLoginSourceType{source.Type}
  678. }
  679. // UserLogin validates user name and password via given login source ID.
  680. // If the loginSourceID is negative, it will abort login process if user is not found.
  681. func UserLogin(username, password string, loginSourceID int64) (*User, error) {
  682. var user *User
  683. if strings.Contains(username, "@") {
  684. user = &User{Email: strings.ToLower(username)}
  685. } else {
  686. user = &User{LowerName: strings.ToLower(username)}
  687. }
  688. hasUser, err := x.Get(user)
  689. if err != nil {
  690. return nil, fmt.Errorf("get user record: %v", err)
  691. }
  692. if hasUser {
  693. // Note: This check is unnecessary but to reduce user confusion at login page
  694. // and make it more consistent at user's perspective.
  695. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  696. return nil, errors.LoginSourceMismatch{loginSourceID, user.LoginSource}
  697. }
  698. // Validate password hash fetched from database for local accounts
  699. if user.LoginType == LOGIN_NOTYPE ||
  700. user.LoginType == LOGIN_PLAIN {
  701. if user.ValidatePassword(password) {
  702. return user, nil
  703. }
  704. return nil, errors.UserNotExist{user.ID, user.Name}
  705. }
  706. // Remote login to the login source the user is associated with
  707. source, err := GetLoginSourceByID(user.LoginSource)
  708. if err != nil {
  709. return nil, err
  710. }
  711. return remoteUserLogin(user, user.LoginName, password, source, false)
  712. }
  713. // Non-local login source is always greater than 0
  714. if loginSourceID <= 0 {
  715. return nil, errors.UserNotExist{-1, username}
  716. }
  717. source, err := GetLoginSourceByID(loginSourceID)
  718. if err != nil {
  719. return nil, err
  720. }
  721. return remoteUserLogin(nil, username, password, source, true)
  722. }