login_source.go 22 KB

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