login_sources.go 8.8 KB

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