login_source.go 21 KB

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