login_source.go 22 KB

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