login_source_files.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 database
  5. import (
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/pkg/errors"
  13. "gopkg.in/ini.v1"
  14. "gogs.io/gogs/internal/auth"
  15. "gogs.io/gogs/internal/auth/github"
  16. "gogs.io/gogs/internal/auth/ldap"
  17. "gogs.io/gogs/internal/auth/pam"
  18. "gogs.io/gogs/internal/auth/smtp"
  19. "gogs.io/gogs/internal/errutil"
  20. "gogs.io/gogs/internal/osutil"
  21. )
  22. // loginSourceFilesStore is the in-memory interface for login source files stored on file system.
  23. type loginSourceFilesStore interface {
  24. // GetByID returns a clone of login source by given ID.
  25. GetByID(id int64) (*LoginSource, error)
  26. // Len returns number of login sources.
  27. Len() int
  28. // List returns a list of login sources filtered by options.
  29. List(opts ListLoginSourceOptions) []*LoginSource
  30. // Update updates in-memory copy of the authentication source.
  31. Update(source *LoginSource)
  32. }
  33. var _ loginSourceFilesStore = (*loginSourceFiles)(nil)
  34. // loginSourceFiles contains authentication sources configured and loaded from local files.
  35. type loginSourceFiles struct {
  36. sync.RWMutex
  37. sources []*LoginSource
  38. clock func() time.Time
  39. }
  40. var _ errutil.NotFound = (*ErrLoginSourceNotExist)(nil)
  41. type ErrLoginSourceNotExist struct {
  42. args errutil.Args
  43. }
  44. func IsErrLoginSourceNotExist(err error) bool {
  45. return errors.As(err, &ErrLoginSourceNotExist{})
  46. }
  47. func (err ErrLoginSourceNotExist) Error() string {
  48. return fmt.Sprintf("login source does not exist: %v", err.args)
  49. }
  50. func (ErrLoginSourceNotExist) NotFound() bool {
  51. return true
  52. }
  53. func (s *loginSourceFiles) GetByID(id int64) (*LoginSource, error) {
  54. s.RLock()
  55. defer s.RUnlock()
  56. for _, source := range s.sources {
  57. if source.ID == id {
  58. return source, nil
  59. }
  60. }
  61. return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
  62. }
  63. func (s *loginSourceFiles) Len() int {
  64. s.RLock()
  65. defer s.RUnlock()
  66. return len(s.sources)
  67. }
  68. func (s *loginSourceFiles) List(opts ListLoginSourceOptions) []*LoginSource {
  69. s.RLock()
  70. defer s.RUnlock()
  71. list := make([]*LoginSource, 0, s.Len())
  72. for _, source := range s.sources {
  73. if opts.OnlyActivated && !source.IsActived {
  74. continue
  75. }
  76. list = append(list, source)
  77. }
  78. return list
  79. }
  80. func (s *loginSourceFiles) Update(source *LoginSource) {
  81. s.Lock()
  82. defer s.Unlock()
  83. source.Updated = s.clock()
  84. for _, old := range s.sources {
  85. if old.ID == source.ID {
  86. *old = *source
  87. } else if source.IsDefault {
  88. old.IsDefault = false
  89. }
  90. }
  91. }
  92. // loadLoginSourceFiles loads login sources from file system.
  93. func loadLoginSourceFiles(authdPath string, clock func() time.Time) (loginSourceFilesStore, error) {
  94. if !osutil.IsDir(authdPath) {
  95. return &loginSourceFiles{clock: clock}, nil
  96. }
  97. store := &loginSourceFiles{clock: clock}
  98. return store, filepath.Walk(authdPath, func(path string, info os.FileInfo, err error) error {
  99. if err != nil {
  100. return err
  101. }
  102. if path == authdPath || !strings.HasSuffix(path, ".conf") {
  103. return nil
  104. } else if info.IsDir() {
  105. return filepath.SkipDir
  106. }
  107. authSource, err := ini.Load(path)
  108. if err != nil {
  109. return errors.Wrap(err, "load file")
  110. }
  111. authSource.NameMapper = ini.TitleUnderscore
  112. // Set general attributes
  113. s := authSource.Section("")
  114. loginSource := &LoginSource{
  115. ID: s.Key("id").MustInt64(),
  116. Name: s.Key("name").String(),
  117. IsActived: s.Key("is_activated").MustBool(),
  118. IsDefault: s.Key("is_default").MustBool(),
  119. File: &loginSourceFile{
  120. path: path,
  121. file: authSource,
  122. },
  123. }
  124. fi, err := os.Stat(path)
  125. if err != nil {
  126. return errors.Wrap(err, "stat file")
  127. }
  128. loginSource.Updated = fi.ModTime()
  129. // Parse authentication source file
  130. authType := s.Key("type").String()
  131. cfgSection := authSource.Section("config")
  132. switch authType {
  133. case "ldap_bind_dn":
  134. var cfg ldap.Config
  135. err = cfgSection.MapTo(&cfg)
  136. if err != nil {
  137. return errors.Wrap(err, `map "config" section`)
  138. }
  139. loginSource.Type = auth.LDAP
  140. loginSource.Provider = ldap.NewProvider(false, &cfg)
  141. case "ldap_simple_auth":
  142. var cfg ldap.Config
  143. err = cfgSection.MapTo(&cfg)
  144. if err != nil {
  145. return errors.Wrap(err, `map "config" section`)
  146. }
  147. loginSource.Type = auth.DLDAP
  148. loginSource.Provider = ldap.NewProvider(true, &cfg)
  149. case "smtp":
  150. var cfg smtp.Config
  151. err = cfgSection.MapTo(&cfg)
  152. if err != nil {
  153. return errors.Wrap(err, `map "config" section`)
  154. }
  155. loginSource.Type = auth.SMTP
  156. loginSource.Provider = smtp.NewProvider(&cfg)
  157. case "pam":
  158. var cfg pam.Config
  159. err = cfgSection.MapTo(&cfg)
  160. if err != nil {
  161. return errors.Wrap(err, `map "config" section`)
  162. }
  163. loginSource.Type = auth.PAM
  164. loginSource.Provider = pam.NewProvider(&cfg)
  165. case "github":
  166. var cfg github.Config
  167. err = cfgSection.MapTo(&cfg)
  168. if err != nil {
  169. return errors.Wrap(err, `map "config" section`)
  170. }
  171. loginSource.Type = auth.GitHub
  172. loginSource.Provider = github.NewProvider(&cfg)
  173. default:
  174. return fmt.Errorf("unknown type %q", authType)
  175. }
  176. store.sources = append(store.sources, loginSource)
  177. return nil
  178. })
  179. }
  180. // loginSourceFileStore is the persistent interface for a login source file.
  181. type loginSourceFileStore interface {
  182. // SetGeneral sets new value to the given key in the general (default) section.
  183. SetGeneral(name, value string)
  184. // SetConfig sets new values to the "config" section.
  185. SetConfig(cfg any) error
  186. // Save persists values to file system.
  187. Save() error
  188. }
  189. var _ loginSourceFileStore = (*loginSourceFile)(nil)
  190. type loginSourceFile struct {
  191. path string
  192. file *ini.File
  193. }
  194. func (f *loginSourceFile) SetGeneral(name, value string) {
  195. f.file.Section("").Key(name).SetValue(value)
  196. }
  197. func (f *loginSourceFile) SetConfig(cfg any) error {
  198. return f.file.Section("config").ReflectFrom(cfg)
  199. }
  200. func (f *loginSourceFile) Save() error {
  201. return f.file.SaveTo(f.path)
  202. }