You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

login_source.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "crypto/tls"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net/smtp"
  12. "net/textproto"
  13. "regexp"
  14. "strings"
  15. "code.gitea.io/gitea/modules/auth/ldap"
  16. "code.gitea.io/gitea/modules/auth/oauth2"
  17. "code.gitea.io/gitea/modules/auth/pam"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/timeutil"
  21. "github.com/unknwon/com"
  22. "xorm.io/core"
  23. "xorm.io/xorm"
  24. )
  25. // LoginType represents an login type.
  26. type LoginType int
  27. // Note: new type must append to the end of list to maintain compatibility.
  28. const (
  29. LoginNoType LoginType = iota
  30. LoginPlain // 1
  31. LoginLDAP // 2
  32. LoginSMTP // 3
  33. LoginPAM // 4
  34. LoginDLDAP // 5
  35. LoginOAuth2 // 6
  36. LoginSSPI // 7
  37. )
  38. // LoginNames contains the name of LoginType values.
  39. var LoginNames = map[LoginType]string{
  40. LoginLDAP: "LDAP (via BindDN)",
  41. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  42. LoginSMTP: "SMTP",
  43. LoginPAM: "PAM",
  44. LoginOAuth2: "OAuth2",
  45. LoginSSPI: "SPNEGO with SSPI",
  46. }
  47. // SecurityProtocolNames contains the name of SecurityProtocol values.
  48. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  49. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  50. ldap.SecurityProtocolLDAPS: "LDAPS",
  51. ldap.SecurityProtocolStartTLS: "StartTLS",
  52. }
  53. // Ensure structs implemented interface.
  54. var (
  55. _ core.Conversion = &LDAPConfig{}
  56. _ core.Conversion = &SMTPConfig{}
  57. _ core.Conversion = &PAMConfig{}
  58. _ core.Conversion = &OAuth2Config{}
  59. _ core.Conversion = &SSPIConfig{}
  60. )
  61. // LDAPConfig holds configuration for LDAP login source.
  62. type LDAPConfig struct {
  63. *ldap.Source
  64. }
  65. // FromDB fills up a LDAPConfig from serialized format.
  66. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  67. return json.Unmarshal(bs, &cfg)
  68. }
  69. // ToDB exports a LDAPConfig to a serialized format.
  70. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  71. return json.Marshal(cfg)
  72. }
  73. // SecurityProtocolName returns the name of configured security
  74. // protocol.
  75. func (cfg *LDAPConfig) SecurityProtocolName() string {
  76. return SecurityProtocolNames[cfg.SecurityProtocol]
  77. }
  78. // SMTPConfig holds configuration for the SMTP login source.
  79. type SMTPConfig struct {
  80. Auth string
  81. Host string
  82. Port int
  83. AllowedDomains string `xorm:"TEXT"`
  84. TLS bool
  85. SkipVerify bool
  86. }
  87. // FromDB fills up an SMTPConfig from serialized format.
  88. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  89. return json.Unmarshal(bs, cfg)
  90. }
  91. // ToDB exports an SMTPConfig to a serialized format.
  92. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  93. return json.Marshal(cfg)
  94. }
  95. // PAMConfig holds configuration for the PAM login source.
  96. type PAMConfig struct {
  97. ServiceName string // pam service (e.g. system-auth)
  98. }
  99. // FromDB fills up a PAMConfig from serialized format.
  100. func (cfg *PAMConfig) FromDB(bs []byte) error {
  101. return json.Unmarshal(bs, &cfg)
  102. }
  103. // ToDB exports a PAMConfig to a serialized format.
  104. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  105. return json.Marshal(cfg)
  106. }
  107. // OAuth2Config holds configuration for the OAuth2 login source.
  108. type OAuth2Config struct {
  109. Provider string
  110. ClientID string
  111. ClientSecret string
  112. OpenIDConnectAutoDiscoveryURL string
  113. CustomURLMapping *oauth2.CustomURLMapping
  114. }
  115. // FromDB fills up an OAuth2Config from serialized format.
  116. func (cfg *OAuth2Config) FromDB(bs []byte) error {
  117. return json.Unmarshal(bs, cfg)
  118. }
  119. // ToDB exports an SMTPConfig to a serialized format.
  120. func (cfg *OAuth2Config) ToDB() ([]byte, error) {
  121. return json.Marshal(cfg)
  122. }
  123. // SSPIConfig holds configuration for SSPI single sign-on.
  124. type SSPIConfig struct {
  125. AutoCreateUsers bool
  126. AutoActivateUsers bool
  127. StripDomainNames bool
  128. SeparatorReplacement string
  129. DefaultLanguage string
  130. }
  131. // FromDB fills up an SSPIConfig from serialized format.
  132. func (cfg *SSPIConfig) FromDB(bs []byte) error {
  133. return json.Unmarshal(bs, cfg)
  134. }
  135. // ToDB exports an SSPIConfig to a serialized format.
  136. func (cfg *SSPIConfig) ToDB() ([]byte, error) {
  137. return json.Marshal(cfg)
  138. }
  139. // LoginSource represents an external way for authorizing users.
  140. type LoginSource struct {
  141. ID int64 `xorm:"pk autoincr"`
  142. Type LoginType
  143. Name string `xorm:"UNIQUE"`
  144. IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
  145. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  146. Cfg core.Conversion `xorm:"TEXT"`
  147. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  148. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  149. }
  150. // Cell2Int64 converts a xorm.Cell type to int64,
  151. // and handles possible irregular cases.
  152. func Cell2Int64(val xorm.Cell) int64 {
  153. switch (*val).(type) {
  154. case []uint8:
  155. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  156. return com.StrTo(string((*val).([]uint8))).MustInt64()
  157. }
  158. return (*val).(int64)
  159. }
  160. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  161. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  162. if colName == "type" {
  163. switch LoginType(Cell2Int64(val)) {
  164. case LoginLDAP, LoginDLDAP:
  165. source.Cfg = new(LDAPConfig)
  166. case LoginSMTP:
  167. source.Cfg = new(SMTPConfig)
  168. case LoginPAM:
  169. source.Cfg = new(PAMConfig)
  170. case LoginOAuth2:
  171. source.Cfg = new(OAuth2Config)
  172. case LoginSSPI:
  173. source.Cfg = new(SSPIConfig)
  174. default:
  175. panic("unrecognized login source type: " + com.ToStr(*val))
  176. }
  177. }
  178. }
  179. // TypeName return name of this login source type.
  180. func (source *LoginSource) TypeName() string {
  181. return LoginNames[source.Type]
  182. }
  183. // IsLDAP returns true of this source is of the LDAP type.
  184. func (source *LoginSource) IsLDAP() bool {
  185. return source.Type == LoginLDAP
  186. }
  187. // IsDLDAP returns true of this source is of the DLDAP type.
  188. func (source *LoginSource) IsDLDAP() bool {
  189. return source.Type == LoginDLDAP
  190. }
  191. // IsSMTP returns true of this source is of the SMTP type.
  192. func (source *LoginSource) IsSMTP() bool {
  193. return source.Type == LoginSMTP
  194. }
  195. // IsPAM returns true of this source is of the PAM type.
  196. func (source *LoginSource) IsPAM() bool {
  197. return source.Type == LoginPAM
  198. }
  199. // IsOAuth2 returns true of this source is of the OAuth2 type.
  200. func (source *LoginSource) IsOAuth2() bool {
  201. return source.Type == LoginOAuth2
  202. }
  203. // IsSSPI returns true of this source is of the SSPI type.
  204. func (source *LoginSource) IsSSPI() bool {
  205. return source.Type == LoginSSPI
  206. }
  207. // HasTLS returns true of this source supports TLS.
  208. func (source *LoginSource) HasTLS() bool {
  209. return ((source.IsLDAP() || source.IsDLDAP()) &&
  210. source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
  211. source.IsSMTP()
  212. }
  213. // UseTLS returns true of this source is configured to use TLS.
  214. func (source *LoginSource) UseTLS() bool {
  215. switch source.Type {
  216. case LoginLDAP, LoginDLDAP:
  217. return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
  218. case LoginSMTP:
  219. return source.SMTP().TLS
  220. }
  221. return false
  222. }
  223. // SkipVerify returns true if this source is configured to skip SSL
  224. // verification.
  225. func (source *LoginSource) SkipVerify() bool {
  226. switch source.Type {
  227. case LoginLDAP, LoginDLDAP:
  228. return source.LDAP().SkipVerify
  229. case LoginSMTP:
  230. return source.SMTP().SkipVerify
  231. }
  232. return false
  233. }
  234. // LDAP returns LDAPConfig for this source, if of LDAP type.
  235. func (source *LoginSource) LDAP() *LDAPConfig {
  236. return source.Cfg.(*LDAPConfig)
  237. }
  238. // SMTP returns SMTPConfig for this source, if of SMTP type.
  239. func (source *LoginSource) SMTP() *SMTPConfig {
  240. return source.Cfg.(*SMTPConfig)
  241. }
  242. // PAM returns PAMConfig for this source, if of PAM type.
  243. func (source *LoginSource) PAM() *PAMConfig {
  244. return source.Cfg.(*PAMConfig)
  245. }
  246. // OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
  247. func (source *LoginSource) OAuth2() *OAuth2Config {
  248. return source.Cfg.(*OAuth2Config)
  249. }
  250. // SSPI returns SSPIConfig for this source, if of SSPI type.
  251. func (source *LoginSource) SSPI() *SSPIConfig {
  252. return source.Cfg.(*SSPIConfig)
  253. }
  254. // CreateLoginSource inserts a LoginSource in the DB if not already
  255. // existing with the given name.
  256. func CreateLoginSource(source *LoginSource) error {
  257. has, err := x.Get(&LoginSource{Name: source.Name})
  258. if err != nil {
  259. return err
  260. } else if has {
  261. return ErrLoginSourceAlreadyExist{source.Name}
  262. }
  263. // Synchronization is only aviable with LDAP for now
  264. if !source.IsLDAP() {
  265. source.IsSyncEnabled = false
  266. }
  267. _, err = x.Insert(source)
  268. if err == nil && source.IsOAuth2() && source.IsActived {
  269. oAuth2Config := source.OAuth2()
  270. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  271. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  272. if err != nil {
  273. // remove the LoginSource in case of errors while registering OAuth2 providers
  274. if _, err := x.Delete(source); err != nil {
  275. log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  276. }
  277. return err
  278. }
  279. }
  280. return err
  281. }
  282. // LoginSources returns a slice of all login sources found in DB.
  283. func LoginSources() ([]*LoginSource, error) {
  284. auths := make([]*LoginSource, 0, 6)
  285. return auths, x.Find(&auths)
  286. }
  287. // LoginSourcesByType returns all sources of the specified type
  288. func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) {
  289. sources := make([]*LoginSource, 0, 1)
  290. if err := x.Where("type = ?", loginType).Find(&sources); err != nil {
  291. return nil, err
  292. }
  293. return sources, nil
  294. }
  295. // ActiveLoginSources returns all active sources of the specified type
  296. func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) {
  297. sources := make([]*LoginSource, 0, 1)
  298. if err := x.Where("is_actived = ? and type = ?", true, loginType).Find(&sources); err != nil {
  299. return nil, err
  300. }
  301. return sources, nil
  302. }
  303. // IsSSPIEnabled returns true if there is at least one activated login
  304. // source of type LoginSSPI
  305. func IsSSPIEnabled() bool {
  306. if !HasEngine {
  307. return false
  308. }
  309. sources, err := ActiveLoginSources(LoginSSPI)
  310. if err != nil {
  311. log.Error("ActiveLoginSources: %v", err)
  312. return false
  313. }
  314. return len(sources) > 0
  315. }
  316. // GetLoginSourceByID returns login source by given ID.
  317. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  318. source := new(LoginSource)
  319. has, err := x.ID(id).Get(source)
  320. if err != nil {
  321. return nil, err
  322. } else if !has {
  323. return nil, ErrLoginSourceNotExist{id}
  324. }
  325. return source, nil
  326. }
  327. // UpdateSource updates a LoginSource record in DB.
  328. func UpdateSource(source *LoginSource) error {
  329. var originalLoginSource *LoginSource
  330. if source.IsOAuth2() {
  331. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  332. var err error
  333. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  334. return err
  335. }
  336. }
  337. _, err := x.ID(source.ID).AllCols().Update(source)
  338. if err == nil && source.IsOAuth2() && source.IsActived {
  339. oAuth2Config := source.OAuth2()
  340. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  341. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  342. if err != nil {
  343. // restore original values since we cannot update the provider it self
  344. if _, err := x.ID(source.ID).AllCols().Update(originalLoginSource); err != nil {
  345. log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  346. }
  347. return err
  348. }
  349. }
  350. return err
  351. }
  352. // DeleteSource deletes a LoginSource record in DB.
  353. func DeleteSource(source *LoginSource) error {
  354. count, err := x.Count(&User{LoginSource: source.ID})
  355. if err != nil {
  356. return err
  357. } else if count > 0 {
  358. return ErrLoginSourceInUse{source.ID}
  359. }
  360. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  361. if err != nil {
  362. return err
  363. } else if count > 0 {
  364. return ErrLoginSourceInUse{source.ID}
  365. }
  366. if source.IsOAuth2() {
  367. oauth2.RemoveProvider(source.Name)
  368. }
  369. _, err = x.ID(source.ID).Delete(new(LoginSource))
  370. return err
  371. }
  372. // CountLoginSources returns number of login sources.
  373. func CountLoginSources() int64 {
  374. count, _ := x.Count(new(LoginSource))
  375. return count
  376. }
  377. // .____ ________ _____ __________
  378. // | | \______ \ / _ \\______ \
  379. // | | | | \ / /_\ \| ___/
  380. // | |___ | ` \/ | \ |
  381. // |_______ \/_______ /\____|__ /____|
  382. // \/ \/ \/
  383. func composeFullName(firstname, surname, username string) string {
  384. switch {
  385. case len(firstname) == 0 && len(surname) == 0:
  386. return username
  387. case len(firstname) == 0:
  388. return surname
  389. case len(surname) == 0:
  390. return firstname
  391. default:
  392. return firstname + " " + surname
  393. }
  394. }
  395. var (
  396. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  397. )
  398. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  399. // and create a local user if success when enabled.
  400. func LoginViaLDAP(user *User, login, password string, source *LoginSource) (*User, error) {
  401. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  402. if sr == nil {
  403. // User not in LDAP, do nothing
  404. return nil, ErrUserNotExist{0, login, 0}
  405. }
  406. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
  407. // Update User admin flag if exist
  408. if isExist, err := IsUserExist(0, sr.Username); err != nil {
  409. return nil, err
  410. } else if isExist {
  411. if user == nil {
  412. user, err = GetUserByName(sr.Username)
  413. if err != nil {
  414. return nil, err
  415. }
  416. }
  417. if user != nil &&
  418. !user.ProhibitLogin && len(source.LDAP().AdminFilter) > 0 && user.IsAdmin != sr.IsAdmin {
  419. // Change existing admin flag only if AdminFilter option is set
  420. user.IsAdmin = sr.IsAdmin
  421. err = UpdateUserCols(user, "is_admin")
  422. if err != nil {
  423. return nil, err
  424. }
  425. }
  426. }
  427. if user != nil {
  428. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  429. return user, RewriteAllPublicKeys()
  430. }
  431. return user, nil
  432. }
  433. // Fallback.
  434. if len(sr.Username) == 0 {
  435. sr.Username = login
  436. }
  437. // Validate username make sure it satisfies requirement.
  438. if alphaDashDotPattern.MatchString(sr.Username) {
  439. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
  440. }
  441. if len(sr.Mail) == 0 {
  442. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  443. }
  444. user = &User{
  445. LowerName: strings.ToLower(sr.Username),
  446. Name: sr.Username,
  447. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  448. Email: sr.Mail,
  449. LoginType: source.Type,
  450. LoginSource: source.ID,
  451. LoginName: login,
  452. IsActive: true,
  453. IsAdmin: sr.IsAdmin,
  454. }
  455. err := CreateUser(user)
  456. if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
  457. err = RewriteAllPublicKeys()
  458. }
  459. return user, err
  460. }
  461. // _________ __________________________
  462. // / _____/ / \__ ___/\______ \
  463. // \_____ \ / \ / \| | | ___/
  464. // / \/ Y \ | | |
  465. // /_______ /\____|__ /____| |____|
  466. // \/ \/
  467. type smtpLoginAuth struct {
  468. username, password string
  469. }
  470. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  471. return "LOGIN", []byte(auth.username), nil
  472. }
  473. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  474. if more {
  475. switch string(fromServer) {
  476. case "Username:":
  477. return []byte(auth.username), nil
  478. case "Password:":
  479. return []byte(auth.password), nil
  480. }
  481. }
  482. return nil, nil
  483. }
  484. // SMTP authentication type names.
  485. const (
  486. SMTPPlain = "PLAIN"
  487. SMTPLogin = "LOGIN"
  488. )
  489. // SMTPAuths contains available SMTP authentication type names.
  490. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  491. // SMTPAuth performs an SMTP authentication.
  492. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  493. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  494. if err != nil {
  495. return err
  496. }
  497. defer c.Close()
  498. if err = c.Hello("gogs"); err != nil {
  499. return err
  500. }
  501. if cfg.TLS {
  502. if ok, _ := c.Extension("STARTTLS"); ok {
  503. if err = c.StartTLS(&tls.Config{
  504. InsecureSkipVerify: cfg.SkipVerify,
  505. ServerName: cfg.Host,
  506. }); err != nil {
  507. return err
  508. }
  509. } else {
  510. return errors.New("SMTP server unsupports TLS")
  511. }
  512. }
  513. if ok, _ := c.Extension("AUTH"); ok {
  514. return c.Auth(a)
  515. }
  516. return ErrUnsupportedLoginType
  517. }
  518. // LoginViaSMTP queries if login/password is valid against the SMTP,
  519. // and create a local user if success when enabled.
  520. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig) (*User, error) {
  521. // Verify allowed domains.
  522. if len(cfg.AllowedDomains) > 0 {
  523. idx := strings.Index(login, "@")
  524. if idx == -1 {
  525. return nil, ErrUserNotExist{0, login, 0}
  526. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  527. return nil, ErrUserNotExist{0, login, 0}
  528. }
  529. }
  530. var auth smtp.Auth
  531. if cfg.Auth == SMTPPlain {
  532. auth = smtp.PlainAuth("", login, password, cfg.Host)
  533. } else if cfg.Auth == SMTPLogin {
  534. auth = &smtpLoginAuth{login, password}
  535. } else {
  536. return nil, errors.New("Unsupported SMTP auth type")
  537. }
  538. if err := SMTPAuth(auth, cfg); err != nil {
  539. // Check standard error format first,
  540. // then fallback to worse case.
  541. tperr, ok := err.(*textproto.Error)
  542. if (ok && tperr.Code == 535) ||
  543. strings.Contains(err.Error(), "Username and Password not accepted") {
  544. return nil, ErrUserNotExist{0, login, 0}
  545. }
  546. return nil, err
  547. }
  548. if user != nil {
  549. return user, nil
  550. }
  551. username := login
  552. idx := strings.Index(login, "@")
  553. if idx > -1 {
  554. username = login[:idx]
  555. }
  556. user = &User{
  557. LowerName: strings.ToLower(username),
  558. Name: strings.ToLower(username),
  559. Email: login,
  560. Passwd: password,
  561. LoginType: LoginSMTP,
  562. LoginSource: sourceID,
  563. LoginName: login,
  564. IsActive: true,
  565. }
  566. return user, CreateUser(user)
  567. }
  568. // __________ _____ _____
  569. // \______ \/ _ \ / \
  570. // | ___/ /_\ \ / \ / \
  571. // | | / | \/ Y \
  572. // |____| \____|__ /\____|__ /
  573. // \/ \/
  574. // LoginViaPAM queries if login/password is valid against the PAM,
  575. // and create a local user if success when enabled.
  576. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig) (*User, error) {
  577. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  578. if strings.Contains(err.Error(), "Authentication failure") {
  579. return nil, ErrUserNotExist{0, login, 0}
  580. }
  581. return nil, err
  582. }
  583. if user != nil {
  584. return user, nil
  585. }
  586. user = &User{
  587. LowerName: strings.ToLower(login),
  588. Name: login,
  589. Email: login,
  590. Passwd: password,
  591. LoginType: LoginPAM,
  592. LoginSource: sourceID,
  593. LoginName: login,
  594. IsActive: true,
  595. }
  596. return user, CreateUser(user)
  597. }
  598. // ExternalUserLogin attempts a login using external source types.
  599. func ExternalUserLogin(user *User, login, password string, source *LoginSource) (*User, error) {
  600. if !source.IsActived {
  601. return nil, ErrLoginSourceNotActived
  602. }
  603. var err error
  604. switch source.Type {
  605. case LoginLDAP, LoginDLDAP:
  606. user, err = LoginViaLDAP(user, login, password, source)
  607. case LoginSMTP:
  608. user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig))
  609. case LoginPAM:
  610. user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig))
  611. default:
  612. return nil, ErrUnsupportedLoginType
  613. }
  614. if err != nil {
  615. return nil, err
  616. }
  617. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  618. // user could be hint to resend confirm email.
  619. if user.ProhibitLogin {
  620. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  621. }
  622. return user, nil
  623. }
  624. // UserSignIn validates user name and password.
  625. func UserSignIn(username, password string) (*User, error) {
  626. var user *User
  627. if strings.Contains(username, "@") {
  628. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  629. // check same email
  630. cnt, err := x.Count(user)
  631. if err != nil {
  632. return nil, err
  633. }
  634. if cnt > 1 {
  635. return nil, ErrEmailAlreadyUsed{
  636. Email: user.Email,
  637. }
  638. }
  639. } else {
  640. trimmedUsername := strings.TrimSpace(username)
  641. if len(trimmedUsername) == 0 {
  642. return nil, ErrUserNotExist{0, username, 0}
  643. }
  644. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  645. }
  646. hasUser, err := x.Get(user)
  647. if err != nil {
  648. return nil, err
  649. }
  650. if hasUser {
  651. switch user.LoginType {
  652. case LoginNoType, LoginPlain, LoginOAuth2:
  653. if user.IsPasswordSet() && user.ValidatePassword(password) {
  654. // Update password hash if server password hash algorithm have changed
  655. if user.PasswdHashAlgo != setting.PasswordHashAlgo {
  656. user.HashPassword(password)
  657. if err := UpdateUserCols(user, "passwd", "passwd_hash_algo"); err != nil {
  658. return nil, err
  659. }
  660. }
  661. // WARN: DON'T check user.IsActive, that will be checked on reqSign so that
  662. // user could be hint to resend confirm email.
  663. if user.ProhibitLogin {
  664. return nil, ErrUserProhibitLogin{user.ID, user.Name}
  665. }
  666. return user, nil
  667. }
  668. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  669. default:
  670. var source LoginSource
  671. hasSource, err := x.ID(user.LoginSource).Get(&source)
  672. if err != nil {
  673. return nil, err
  674. } else if !hasSource {
  675. return nil, ErrLoginSourceNotExist{user.LoginSource}
  676. }
  677. return ExternalUserLogin(user, user.LoginName, password, &source)
  678. }
  679. }
  680. sources := make([]*LoginSource, 0, 5)
  681. if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
  682. return nil, err
  683. }
  684. for _, source := range sources {
  685. if source.IsOAuth2() || source.IsSSPI() {
  686. // don't try to authenticate against OAuth2 and SSPI sources here
  687. continue
  688. }
  689. authUser, err := ExternalUserLogin(nil, username, password, source)
  690. if err == nil {
  691. return authUser, nil
  692. }
  693. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  694. }
  695. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  696. }