login_sources.go 8.8 KB

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