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.

source_authenticate.go 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package pam
  5. import (
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/models/auth"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/auth/pam"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/services/mailer"
  13. "github.com/google/uuid"
  14. )
  15. // Authenticate queries if login/password is valid against the PAM,
  16. // and create a local user if success when enabled.
  17. func (source *Source) Authenticate(user *user_model.User, userName, password string) (*user_model.User, error) {
  18. pamLogin, err := pam.Auth(source.ServiceName, userName, password)
  19. if err != nil {
  20. if strings.Contains(err.Error(), "Authentication failure") {
  21. return nil, user_model.ErrUserNotExist{Name: userName}
  22. }
  23. return nil, err
  24. }
  25. if user != nil {
  26. return user, nil
  27. }
  28. // Allow PAM sources with `@` in their name, like from Active Directory
  29. username := pamLogin
  30. email := pamLogin
  31. idx := strings.Index(pamLogin, "@")
  32. if idx > -1 {
  33. username = pamLogin[:idx]
  34. }
  35. if user_model.ValidateEmail(email) != nil {
  36. if source.EmailDomain != "" {
  37. email = fmt.Sprintf("%s@%s", username, source.EmailDomain)
  38. } else {
  39. email = fmt.Sprintf("%s@%s", username, setting.Service.NoReplyAddress)
  40. }
  41. if user_model.ValidateEmail(email) != nil {
  42. email = uuid.New().String() + "@localhost"
  43. }
  44. }
  45. user = &user_model.User{
  46. LowerName: strings.ToLower(username),
  47. Name: username,
  48. Email: email,
  49. Passwd: password,
  50. LoginType: auth.PAM,
  51. LoginSource: source.authSource.ID,
  52. LoginName: userName, // This is what the user typed in
  53. IsActive: true,
  54. }
  55. if err := user_model.CreateUser(user); err != nil {
  56. return user, err
  57. }
  58. mailer.SendRegisterNotifyMail(user)
  59. return user, nil
  60. }
  61. // IsSkipLocalTwoFA returns if this source should skip local 2fa for password authentication
  62. func (source *Source) IsSkipLocalTwoFA() bool {
  63. return source.SkipLocalTwoFA
  64. }