login_source_files.go 5.8 KB

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