login_source_files.go 5.1 KB

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