login_source.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, 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.SecurityProtocolUnencrypted: "Unencrypted",
  54. ldap.SecurityProtocolLDAPS: "LDAPS",
  55. ldap.SecurityProtocolStartTLS: "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.SecurityProtocolUnencrypted) ||
  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.SecurityProtocolUnencrypted
  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. }
  336. return ResetNonDefaultLoginSources(source)
  337. }
  338. source.LocalFile.SetGeneral("name", source.Name)
  339. source.LocalFile.SetGeneral("is_activated", com.ToStr(source.IsActived))
  340. source.LocalFile.SetGeneral("is_default", com.ToStr(source.IsDefault))
  341. if err := source.LocalFile.SetConfig(source.Cfg); err != nil {
  342. return fmt.Errorf("LocalFile.SetConfig: %v", err)
  343. } else if err = source.LocalFile.Save(); err != nil {
  344. return fmt.Errorf("LocalFile.Save: %v", err)
  345. }
  346. return ResetNonDefaultLoginSources(source)
  347. }
  348. // DeleteSource deletes a LoginSource record in DB.
  349. func DeleteSource(source *LoginSource) error {
  350. count, err := x.Count(&User{LoginSource: source.ID})
  351. if err != nil {
  352. return err
  353. } else if count > 0 {
  354. return ErrLoginSourceInUse{source.ID}
  355. }
  356. _, err = x.Id(source.ID).Delete(new(LoginSource))
  357. return err
  358. }
  359. // CountLoginSources returns total number of login sources.
  360. func CountLoginSources() int64 {
  361. count, _ := x.Count(new(LoginSource))
  362. return count + int64(localLoginSources.Len())
  363. }
  364. // LocalLoginSources contains authentication sources configured and loaded from local files.
  365. // Calling its methods is thread-safe; otherwise, please maintain the mutex accordingly.
  366. type LocalLoginSources struct {
  367. sync.RWMutex
  368. sources []*LoginSource
  369. }
  370. // Len returns length of local login sources.
  371. func (s *LocalLoginSources) Len() int {
  372. return len(s.sources)
  373. }
  374. // List returns full clone of login sources.
  375. func (s *LocalLoginSources) List() []*LoginSource {
  376. s.RLock()
  377. defer s.RUnlock()
  378. list := make([]*LoginSource, s.Len())
  379. for i := range s.sources {
  380. list[i] = &LoginSource{}
  381. *list[i] = *s.sources[i]
  382. }
  383. return list
  384. }
  385. // ActivatedList returns clone of activated login sources.
  386. func (s *LocalLoginSources) ActivatedList() []*LoginSource {
  387. s.RLock()
  388. defer s.RUnlock()
  389. list := make([]*LoginSource, 0, 2)
  390. for i := range s.sources {
  391. if !s.sources[i].IsActived {
  392. continue
  393. }
  394. source := &LoginSource{}
  395. *source = *s.sources[i]
  396. list = append(list, source)
  397. }
  398. return list
  399. }
  400. // GetLoginSourceByID returns a clone of login source by given ID.
  401. func (s *LocalLoginSources) GetLoginSourceByID(id int64) (*LoginSource, error) {
  402. s.RLock()
  403. defer s.RUnlock()
  404. for i := range s.sources {
  405. if s.sources[i].ID == id {
  406. source := &LoginSource{}
  407. *source = *s.sources[i]
  408. return source, nil
  409. }
  410. }
  411. return nil, errors.LoginSourceNotExist{id}
  412. }
  413. // UpdateLoginSource updates in-memory copy of the authentication source.
  414. func (s *LocalLoginSources) UpdateLoginSource(source *LoginSource) {
  415. s.Lock()
  416. defer s.Unlock()
  417. source.Updated = time.Now()
  418. for i := range s.sources {
  419. if s.sources[i].ID == source.ID {
  420. *s.sources[i] = *source
  421. } else if source.IsDefault {
  422. s.sources[i].IsDefault = false
  423. }
  424. }
  425. }
  426. var localLoginSources = &LocalLoginSources{}
  427. // LoadAuthSources loads authentication sources from local files
  428. // and converts them into login sources.
  429. func LoadAuthSources() {
  430. authdPath := path.Join(setting.CustomPath, "conf/auth.d")
  431. if !com.IsDir(authdPath) {
  432. return
  433. }
  434. paths, err := com.GetFileListBySuffix(authdPath, ".conf")
  435. if err != nil {
  436. raven.CaptureErrorAndWait(err, nil)
  437. log.Fatal(2, "Failed to list authentication sources: %v", err)
  438. }
  439. localLoginSources.sources = make([]*LoginSource, 0, len(paths))
  440. for _, fpath := range paths {
  441. authSource, err := ini.Load(fpath)
  442. if err != nil {
  443. raven.CaptureErrorAndWait(err, nil)
  444. log.Fatal(2, "Failed to load authentication source: %v", err)
  445. }
  446. authSource.NameMapper = ini.TitleUnderscore
  447. // Set general attributes
  448. s := authSource.Section("")
  449. loginSource := &LoginSource{
  450. ID: s.Key("id").MustInt64(),
  451. Name: s.Key("name").String(),
  452. IsActived: s.Key("is_activated").MustBool(),
  453. IsDefault: s.Key("is_default").MustBool(),
  454. LocalFile: &AuthSourceFile{
  455. abspath: fpath,
  456. file: authSource,
  457. },
  458. }
  459. fi, err := os.Stat(fpath)
  460. if err != nil {
  461. raven.CaptureErrorAndWait(err, nil)
  462. log.Fatal(2, "Failed to load authentication source: %v", err)
  463. }
  464. loginSource.Updated = fi.ModTime()
  465. // Parse authentication source file
  466. authType := s.Key("type").String()
  467. switch authType {
  468. case "ldap_bind_dn":
  469. loginSource.Type = LoginLDAP
  470. loginSource.Cfg = &LDAPConfig{}
  471. case "ldap_simple_auth":
  472. loginSource.Type = LoginDLDAP
  473. loginSource.Cfg = &LDAPConfig{}
  474. case "smtp":
  475. loginSource.Type = LoginSMTP
  476. loginSource.Cfg = &SMTPConfig{}
  477. case "pam":
  478. loginSource.Type = LoginPAM
  479. loginSource.Cfg = &PAMConfig{}
  480. case "github":
  481. loginSource.Type = LoginGitHub
  482. loginSource.Cfg = &GitHubConfig{}
  483. default:
  484. raven.CaptureErrorAndWait(err, nil)
  485. log.Fatal(2, "Failed to load authentication source: unknown type '%s'", authType)
  486. }
  487. if err = authSource.Section("config").MapTo(loginSource.Cfg); err != nil {
  488. raven.CaptureErrorAndWait(err, nil)
  489. log.Fatal(2, "Failed to parse authentication source 'config': %v", err)
  490. }
  491. localLoginSources.sources = append(localLoginSources.sources, loginSource)
  492. }
  493. }
  494. func composeFullName(firstname, surname, username string) string {
  495. switch {
  496. case len(firstname) == 0 && len(surname) == 0:
  497. return username
  498. case len(firstname) == 0:
  499. return surname
  500. case len(surname) == 0:
  501. return firstname
  502. default:
  503. return firstname + " " + surname
  504. }
  505. }
  506. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  507. // and create a local user if success when enabled.
  508. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  509. username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  510. if !succeed {
  511. // User not in LDAP, do nothing
  512. return nil, errors.UserNotExist{0, login}
  513. }
  514. if !autoRegister {
  515. return user, nil
  516. }
  517. // Fallback.
  518. if len(username) == 0 {
  519. username = login
  520. }
  521. // Validate username make sure it satisfies requirement.
  522. if binding.AlphaDashDotPattern.MatchString(username) {
  523. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", username)
  524. }
  525. if len(mail) == 0 {
  526. mail = fmt.Sprintf("%s@localhost", username)
  527. }
  528. user = &User{
  529. LowerName: strings.ToLower(username),
  530. Name: username,
  531. FullName: composeFullName(fn, sn, username),
  532. Email: mail,
  533. LoginType: source.Type,
  534. LoginSource: source.ID,
  535. LoginName: login,
  536. IsActive: true,
  537. IsAdmin: isAdmin,
  538. }
  539. ok, err := IsUserExist(0, user.Name)
  540. if err != nil {
  541. return user, err
  542. }
  543. if ok {
  544. return user, UpdateUser(user)
  545. }
  546. return user, CreateUser(user)
  547. }
  548. type smtpLoginAuth struct {
  549. username, password string
  550. }
  551. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  552. return "LOGIN", []byte(auth.username), nil
  553. }
  554. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  555. if more {
  556. switch string(fromServer) {
  557. case "Username:":
  558. return []byte(auth.username), nil
  559. case "Password:":
  560. return []byte(auth.password), nil
  561. }
  562. }
  563. return nil, nil
  564. }
  565. // SMTP authentication type names.
  566. const (
  567. SMTPPlain = "PLAIN"
  568. SMTPLogin = "LOGIN"
  569. )
  570. // SMTPAuths contains available SMTP authentication type names.
  571. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  572. // SMTPAuth contains available SMTP authentication type names.
  573. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  574. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  575. if err != nil {
  576. return err
  577. }
  578. defer c.Close()
  579. if err = c.Hello("gitote"); err != nil {
  580. return err
  581. }
  582. if cfg.TLS {
  583. if ok, _ := c.Extension("STARTTLS"); ok {
  584. if err = c.StartTLS(&tls.Config{
  585. InsecureSkipVerify: cfg.SkipVerify,
  586. ServerName: cfg.Host,
  587. }); err != nil {
  588. return err
  589. }
  590. } else {
  591. return errors.New("SMTP server unsupports TLS")
  592. }
  593. }
  594. if ok, _ := c.Extension("AUTH"); ok {
  595. if err = c.Auth(a); err != nil {
  596. return err
  597. }
  598. return nil
  599. }
  600. return errors.New("Unsupported SMTP authentication method")
  601. }
  602. // LoginViaSMTP queries if login/password is valid against the SMTP,
  603. // and create a local user if success when enabled.
  604. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  605. // Verify allowed domains.
  606. if len(cfg.AllowedDomains) > 0 {
  607. idx := strings.Index(login, "@")
  608. if idx == -1 {
  609. return nil, errors.UserNotExist{0, login}
  610. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  611. return nil, errors.UserNotExist{0, login}
  612. }
  613. }
  614. var auth smtp.Auth
  615. if cfg.Auth == SMTPPlain {
  616. auth = smtp.PlainAuth("", login, password, cfg.Host)
  617. } else if cfg.Auth == SMTPLogin {
  618. auth = &smtpLoginAuth{login, password}
  619. } else {
  620. return nil, errors.New("Unsupported SMTP authentication type")
  621. }
  622. if err := SMTPAuth(auth, cfg); err != nil {
  623. // Check standard error format first,
  624. // then fallback to worse case.
  625. tperr, ok := err.(*textproto.Error)
  626. if (ok && tperr.Code == 535) ||
  627. strings.Contains(err.Error(), "Username and Password not accepted") {
  628. return nil, errors.UserNotExist{0, login}
  629. }
  630. return nil, err
  631. }
  632. if !autoRegister {
  633. return user, nil
  634. }
  635. username := login
  636. idx := strings.Index(login, "@")
  637. if idx > -1 {
  638. username = login[:idx]
  639. }
  640. user = &User{
  641. LowerName: strings.ToLower(username),
  642. Name: strings.ToLower(username),
  643. Email: login,
  644. Passwd: password,
  645. LoginType: LoginSMTP,
  646. LoginSource: sourceID,
  647. LoginName: login,
  648. IsActive: true,
  649. }
  650. return user, CreateUser(user)
  651. }
  652. // LoginViaPAM queries if login/password is valid against the PAM,
  653. // and create a local user if success when enabled.
  654. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  655. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  656. if strings.Contains(err.Error(), "Authentication failure") {
  657. return nil, errors.UserNotExist{0, login}
  658. }
  659. return nil, err
  660. }
  661. if !autoRegister {
  662. return user, nil
  663. }
  664. user = &User{
  665. LowerName: strings.ToLower(login),
  666. Name: login,
  667. Email: login,
  668. Passwd: password,
  669. LoginType: LoginPAM,
  670. LoginSource: sourceID,
  671. LoginName: login,
  672. IsActive: true,
  673. }
  674. return user, CreateUser(user)
  675. }
  676. // LoginViaGitHub contains available GitHub authentication type names.
  677. func LoginViaGitHub(user *User, login, password string, sourceID int64, cfg *GitHubConfig, autoRegister bool) (*User, error) {
  678. fullname, email, url, location, err := github.Authenticate(cfg.APIEndpoint, login, password)
  679. if err != nil {
  680. if strings.Contains(err.Error(), "401") {
  681. return nil, errors.UserNotExist{0, login}
  682. }
  683. return nil, err
  684. }
  685. if !autoRegister {
  686. return user, nil
  687. }
  688. user = &User{
  689. LowerName: strings.ToLower(login),
  690. Name: login,
  691. FullName: fullname,
  692. Email: email,
  693. Website: url,
  694. Passwd: password,
  695. LoginType: LoginGitHub,
  696. LoginSource: sourceID,
  697. LoginName: login,
  698. IsActive: true,
  699. Location: location,
  700. }
  701. return user, CreateUser(user)
  702. }
  703. func remoteUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  704. if !source.IsActived {
  705. return nil, errors.LoginSourceNotActivated{source.ID}
  706. }
  707. switch source.Type {
  708. case LoginLDAP, LoginDLDAP:
  709. return LoginViaLDAP(user, login, password, source, autoRegister)
  710. case LoginSMTP:
  711. return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  712. case LoginPAM:
  713. return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  714. case LoginGitHub:
  715. return LoginViaGitHub(user, login, password, source.ID, source.Cfg.(*GitHubConfig), autoRegister)
  716. }
  717. return nil, errors.InvalidLoginSourceType{source.Type}
  718. }
  719. // UserLogin validates user name and password via given login source ID.
  720. // If the loginSourceID is negative, it will abort login process if user is not found.
  721. func UserLogin(username, password string, loginSourceID int64) (*User, error) {
  722. var user *User
  723. if strings.Contains(username, "@") {
  724. user = &User{Email: strings.ToLower(username)}
  725. } else {
  726. user = &User{LowerName: strings.ToLower(username)}
  727. }
  728. hasUser, err := x.Get(user)
  729. if err != nil {
  730. return nil, fmt.Errorf("get user record: %v", err)
  731. }
  732. if hasUser {
  733. // Note: This check is unnecessary but to reduce user confusion at login page
  734. // and make it more consistent at user's perspective.
  735. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  736. return nil, errors.LoginSourceMismatch{loginSourceID, user.LoginSource}
  737. }
  738. // Validate password hash fetched from database for local accounts
  739. if user.LoginType == LoginNotype ||
  740. user.LoginType == LoginPlain {
  741. if user.ValidatePassword(password) {
  742. return user, nil
  743. }
  744. return nil, errors.UserNotExist{user.ID, user.Name}
  745. }
  746. // Remote login to the login source the user is associated with
  747. source, err := GetLoginSourceByID(user.LoginSource)
  748. if err != nil {
  749. return nil, err
  750. }
  751. return remoteUserLogin(user, user.LoginName, password, source, false)
  752. }
  753. // Non-local login source is always greater than 0
  754. if loginSourceID <= 0 {
  755. return nil, errors.UserNotExist{-1, username}
  756. }
  757. source, err := GetLoginSourceByID(loginSourceID)
  758. if err != nil {
  759. return nil, err
  760. }
  761. return remoteUserLogin(nil, username, password, source, true)
  762. }