provider.go 1.8 KB

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