provider.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package ldap
  2. import (
  3. "fmt"
  4. "gogs.io/gogs/internal/auth"
  5. )
  6. // Provider contains configuration of an LDAP authentication provider.
  7. type Provider struct {
  8. directBind bool
  9. config *Config
  10. }
  11. // NewProvider creates a new LDAP authentication provider.
  12. func NewProvider(directBind bool, cfg *Config) auth.Provider {
  13. return &Provider{
  14. directBind: directBind,
  15. config: cfg,
  16. }
  17. }
  18. // Authenticate queries if login/password is valid against the LDAP directory pool,
  19. // and returns queried information when succeeded.
  20. func (p *Provider) Authenticate(login, password string) (*auth.ExternalAccount, error) {
  21. username, fn, sn, email, isAdmin, succeed := p.config.searchEntry(login, password, p.directBind)
  22. if !succeed {
  23. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
  24. }
  25. if username == "" {
  26. username = login
  27. }
  28. if email == "" {
  29. email = fmt.Sprintf("%s@localhost", username)
  30. }
  31. composeFullName := func(firstname, surname, username string) string {
  32. switch {
  33. case firstname == "" && surname == "":
  34. return username
  35. case firstname == "":
  36. return surname
  37. case surname == "":
  38. return firstname
  39. default:
  40. return firstname + " " + surname
  41. }
  42. }
  43. return &auth.ExternalAccount{
  44. Login: login,
  45. Name: username,
  46. FullName: composeFullName(fn, sn, username),
  47. Email: email,
  48. Admin: isAdmin,
  49. }, nil
  50. }
  51. func (p *Provider) Config() any {
  52. return p.config
  53. }
  54. func (p *Provider) HasTLS() bool {
  55. return p.config.SecurityProtocol > SecurityProtocolUnencrypted
  56. }
  57. func (p *Provider) UseTLS() bool {
  58. return p.config.SecurityProtocol > SecurityProtocolUnencrypted
  59. }
  60. func (p *Provider) SkipTLSVerify() bool {
  61. return p.config.SkipVerify
  62. }