login_sources.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package database
  2. import (
  3. "context"
  4. "fmt"
  5. "strconv"
  6. "time"
  7. jsoniter "github.com/json-iterator/go"
  8. "github.com/pkg/errors"
  9. "gorm.io/gorm"
  10. "gogs.io/gogs/internal/auth"
  11. "gogs.io/gogs/internal/auth/github"
  12. "gogs.io/gogs/internal/auth/ldap"
  13. "gogs.io/gogs/internal/auth/pam"
  14. "gogs.io/gogs/internal/auth/smtp"
  15. "gogs.io/gogs/internal/errutil"
  16. )
  17. // LoginSource represents an external way for authorizing users.
  18. type LoginSource struct {
  19. ID int64 `gorm:"primaryKey"`
  20. Type auth.Type
  21. Name string `xorm:"UNIQUE" gorm:"unique"`
  22. IsActived bool `xorm:"NOT NULL DEFAULT false" gorm:"not null"`
  23. IsDefault bool `xorm:"DEFAULT false"`
  24. Provider auth.Provider `xorm:"-" gorm:"-"`
  25. Config string `xorm:"TEXT cfg" gorm:"column:cfg;type:TEXT" json:"RawConfig"`
  26. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  27. CreatedUnix int64
  28. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  29. UpdatedUnix int64
  30. File loginSourceFileStore `xorm:"-" gorm:"-" json:"-"`
  31. }
  32. // BeforeSave implements the GORM save hook.
  33. func (s *LoginSource) BeforeSave(_ *gorm.DB) (err error) {
  34. if s.Provider == nil {
  35. return nil
  36. }
  37. s.Config, err = jsoniter.MarshalToString(s.Provider.Config())
  38. return err
  39. }
  40. // BeforeCreate implements the GORM create hook.
  41. func (s *LoginSource) BeforeCreate(tx *gorm.DB) error {
  42. if s.CreatedUnix == 0 {
  43. s.CreatedUnix = tx.NowFunc().Unix()
  44. s.UpdatedUnix = s.CreatedUnix
  45. }
  46. return nil
  47. }
  48. // BeforeUpdate implements the GORM update hook.
  49. func (s *LoginSource) BeforeUpdate(tx *gorm.DB) error {
  50. s.UpdatedUnix = tx.NowFunc().Unix()
  51. return nil
  52. }
  53. type mockProviderConfig struct {
  54. ExternalAccount *auth.ExternalAccount
  55. }
  56. // AfterFind implements the GORM query hook.
  57. func (s *LoginSource) AfterFind(_ *gorm.DB) error {
  58. s.Created = time.Unix(s.CreatedUnix, 0).Local()
  59. s.Updated = time.Unix(s.UpdatedUnix, 0).Local()
  60. switch s.Type {
  61. case auth.LDAP:
  62. var cfg ldap.Config
  63. err := jsoniter.UnmarshalFromString(s.Config, &cfg)
  64. if err != nil {
  65. return err
  66. }
  67. s.Provider = ldap.NewProvider(false, &cfg)
  68. case auth.DLDAP:
  69. var cfg ldap.Config
  70. err := jsoniter.UnmarshalFromString(s.Config, &cfg)
  71. if err != nil {
  72. return err
  73. }
  74. s.Provider = ldap.NewProvider(true, &cfg)
  75. case auth.SMTP:
  76. var cfg smtp.Config
  77. err := jsoniter.UnmarshalFromString(s.Config, &cfg)
  78. if err != nil {
  79. return err
  80. }
  81. s.Provider = smtp.NewProvider(&cfg)
  82. case auth.PAM:
  83. var cfg pam.Config
  84. err := jsoniter.UnmarshalFromString(s.Config, &cfg)
  85. if err != nil {
  86. return err
  87. }
  88. s.Provider = pam.NewProvider(&cfg)
  89. case auth.GitHub:
  90. var cfg github.Config
  91. err := jsoniter.UnmarshalFromString(s.Config, &cfg)
  92. if err != nil {
  93. return err
  94. }
  95. s.Provider = github.NewProvider(&cfg)
  96. case auth.Mock:
  97. var cfg mockProviderConfig
  98. err := jsoniter.UnmarshalFromString(s.Config, &cfg)
  99. if err != nil {
  100. return err
  101. }
  102. mockProvider := NewMockProvider()
  103. mockProvider.AuthenticateFunc.SetDefaultReturn(cfg.ExternalAccount, nil)
  104. s.Provider = mockProvider
  105. default:
  106. return fmt.Errorf("unrecognized login source type: %v", s.Type)
  107. }
  108. return nil
  109. }
  110. func (s *LoginSource) TypeName() string {
  111. return auth.Name(s.Type)
  112. }
  113. func (s *LoginSource) IsLDAP() bool {
  114. return s.Type == auth.LDAP
  115. }
  116. func (s *LoginSource) IsDLDAP() bool {
  117. return s.Type == auth.DLDAP
  118. }
  119. func (s *LoginSource) IsSMTP() bool {
  120. return s.Type == auth.SMTP
  121. }
  122. func (s *LoginSource) IsPAM() bool {
  123. return s.Type == auth.PAM
  124. }
  125. func (s *LoginSource) IsGitHub() bool {
  126. return s.Type == auth.GitHub
  127. }
  128. func (s *LoginSource) LDAP() *ldap.Config {
  129. return s.Provider.Config().(*ldap.Config)
  130. }
  131. func (s *LoginSource) SMTP() *smtp.Config {
  132. return s.Provider.Config().(*smtp.Config)
  133. }
  134. func (s *LoginSource) PAM() *pam.Config {
  135. return s.Provider.Config().(*pam.Config)
  136. }
  137. func (s *LoginSource) GitHub() *github.Config {
  138. return s.Provider.Config().(*github.Config)
  139. }
  140. // LoginSourcesStore is the storage layer for login sources.
  141. type LoginSourcesStore struct {
  142. db *gorm.DB
  143. files loginSourceFilesStore
  144. }
  145. func newLoginSourcesStore(db *gorm.DB, files loginSourceFilesStore) *LoginSourcesStore {
  146. return &LoginSourcesStore{
  147. db: db,
  148. files: files,
  149. }
  150. }
  151. type CreateLoginSourceOptions struct {
  152. Type auth.Type
  153. Name string
  154. Activated bool
  155. Default bool
  156. Config any
  157. }
  158. type ErrLoginSourceAlreadyExist struct {
  159. args errutil.Args
  160. }
  161. func IsErrLoginSourceAlreadyExist(err error) bool {
  162. return errors.As(err, &ErrLoginSourceAlreadyExist{})
  163. }
  164. func (err ErrLoginSourceAlreadyExist) Error() string {
  165. return fmt.Sprintf("login source already exists: %v", err.args)
  166. }
  167. // Create creates a new login source and persists it to the database. It returns
  168. // ErrLoginSourceAlreadyExist when a login source with same name already exists.
  169. func (s *LoginSourcesStore) Create(ctx context.Context, opts CreateLoginSourceOptions) (*LoginSource, error) {
  170. err := s.db.WithContext(ctx).Where("name = ?", opts.Name).First(new(LoginSource)).Error
  171. if err == nil {
  172. return nil, ErrLoginSourceAlreadyExist{args: errutil.Args{"name": opts.Name}}
  173. } else if !errors.Is(err, gorm.ErrRecordNotFound) {
  174. return nil, err
  175. }
  176. source := &LoginSource{
  177. Type: opts.Type,
  178. Name: opts.Name,
  179. IsActived: opts.Activated,
  180. IsDefault: opts.Default,
  181. }
  182. source.Config, err = jsoniter.MarshalToString(opts.Config)
  183. if err != nil {
  184. return nil, err
  185. }
  186. return source, s.db.WithContext(ctx).Create(source).Error
  187. }
  188. // Count returns the total number of login sources.
  189. func (s *LoginSourcesStore) Count(ctx context.Context) int64 {
  190. var count int64
  191. s.db.WithContext(ctx).Model(new(LoginSource)).Count(&count)
  192. return count + int64(s.files.Len())
  193. }
  194. type ErrLoginSourceInUse struct {
  195. args errutil.Args
  196. }
  197. func IsErrLoginSourceInUse(err error) bool {
  198. return errors.As(err, &ErrLoginSourceInUse{})
  199. }
  200. func (err ErrLoginSourceInUse) Error() string {
  201. return fmt.Sprintf("login source is still used by some users: %v", err.args)
  202. }
  203. // DeleteByID deletes a login source by given ID. It returns ErrLoginSourceInUse
  204. // if at least one user is associated with the login source.
  205. func (s *LoginSourcesStore) DeleteByID(ctx context.Context, id int64) error {
  206. var count int64
  207. err := s.db.WithContext(ctx).Model(new(User)).Where("login_source = ?", id).Count(&count).Error
  208. if err != nil {
  209. return err
  210. } else if count > 0 {
  211. return ErrLoginSourceInUse{args: errutil.Args{"id": id}}
  212. }
  213. return s.db.WithContext(ctx).Where("id = ?", id).Delete(new(LoginSource)).Error
  214. }
  215. // GetByID returns the login source with given ID. It returns
  216. // ErrLoginSourceNotExist when not found.
  217. func (s *LoginSourcesStore) GetByID(ctx context.Context, id int64) (*LoginSource, error) {
  218. source := new(LoginSource)
  219. err := s.db.WithContext(ctx).Where("id = ?", id).First(source).Error
  220. if err != nil {
  221. if errors.Is(err, gorm.ErrRecordNotFound) {
  222. return s.files.GetByID(id)
  223. }
  224. return nil, err
  225. }
  226. return source, nil
  227. }
  228. type ListLoginSourceOptions struct {
  229. // Whether to only include activated login sources.
  230. OnlyActivated bool
  231. }
  232. // List returns a list of login sources filtered by options.
  233. func (s *LoginSourcesStore) List(ctx context.Context, opts ListLoginSourceOptions) ([]*LoginSource, error) {
  234. var sources []*LoginSource
  235. query := s.db.WithContext(ctx).Order("id ASC")
  236. if opts.OnlyActivated {
  237. query = query.Where("is_actived = ?", true)
  238. }
  239. err := query.Find(&sources).Error
  240. if err != nil {
  241. return nil, err
  242. }
  243. return append(sources, s.files.List(opts)...), nil
  244. }
  245. // ResetNonDefault clears default flag for all the other login sources.
  246. func (s *LoginSourcesStore) ResetNonDefault(ctx context.Context, dflt *LoginSource) error {
  247. err := s.db.WithContext(ctx).
  248. Model(new(LoginSource)).
  249. Where("id != ?", dflt.ID).
  250. Updates(map[string]any{"is_default": false}).
  251. Error
  252. if err != nil {
  253. return err
  254. }
  255. for _, source := range s.files.List(ListLoginSourceOptions{}) {
  256. if source.File != nil && source.ID != dflt.ID {
  257. source.File.SetGeneral("is_default", "false")
  258. if err = source.File.Save(); err != nil {
  259. return errors.Wrap(err, "save file")
  260. }
  261. }
  262. }
  263. s.files.Update(dflt)
  264. return nil
  265. }
  266. // Save persists all values of given login source to database or local file. The
  267. // Updated field is set to current time automatically.
  268. func (s *LoginSourcesStore) Save(ctx context.Context, source *LoginSource) error {
  269. if source.File == nil {
  270. return s.db.WithContext(ctx).Save(source).Error
  271. }
  272. source.File.SetGeneral("name", source.Name)
  273. source.File.SetGeneral("is_activated", strconv.FormatBool(source.IsActived))
  274. source.File.SetGeneral("is_default", strconv.FormatBool(source.IsDefault))
  275. if err := source.File.SetConfig(source.Provider.Config()); err != nil {
  276. return errors.Wrap(err, "set config")
  277. } else if err = source.File.Save(); err != nil {
  278. return errors.Wrap(err, "save file")
  279. }
  280. return nil
  281. }