login_source.go 24 KB

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