login_source.go 22 KB

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