v20.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2022 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 migrations
  5. import (
  6. "github.com/pkg/errors"
  7. "gorm.io/gorm"
  8. "gogs.io/gogs/internal/cryptoutil"
  9. )
  10. func migrateAccessTokenToSHA256(db *gorm.DB) error {
  11. return db.Transaction(func(tx *gorm.DB) error {
  12. // 1. Add column without constraints because all rows have NULL values for the
  13. // "sha256" column.
  14. type accessToken struct {
  15. ID int64
  16. Sha1 string
  17. SHA256 string `gorm:"TYPE:VARCHAR(64)"`
  18. }
  19. err := tx.Migrator().AddColumn(&accessToken{}, "SHA256")
  20. if err != nil {
  21. return errors.Wrap(err, "add column")
  22. }
  23. // 2. Generate SHA256 for existing rows from their values in the "sha1" column.
  24. var accessTokens []*accessToken
  25. err = tx.Where("sha256 IS NULL").Find(&accessTokens).Error
  26. if err != nil {
  27. return errors.Wrap(err, "list")
  28. }
  29. for _, t := range accessTokens {
  30. sha256 := cryptoutil.SHA256(t.Sha1)
  31. err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error
  32. if err != nil {
  33. return errors.Wrap(err, "update")
  34. }
  35. }
  36. // 3. We are now safe to apply constraints to the "sha256" column.
  37. type accessTokenWithConstraint struct {
  38. SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
  39. }
  40. err = tx.Table("access_token").AutoMigrate(&accessTokenWithConstraint{})
  41. if err != nil {
  42. return errors.Wrap(err, "auto migrate")
  43. }
  44. return nil
  45. })
  46. }