login_source.go 22 KB

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