login_source.go 21 KB

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