v20.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 and LICENSE.gogs file.
  4. // Copyright 2025 Huan-Gogs Authors. All rights reserved.
  5. // Use of this source code is governed by a MIT-style
  6. // license that can be found in the LICENSE file.
  7. package migrations
  8. import (
  9. "github.com/pkg/errors"
  10. "gorm.io/gorm"
  11. "github.com/SongZihuan/huan-gogs/internal/cryptoutil"
  12. )
  13. func migrateAccessTokenToSHA256(db *gorm.DB) error {
  14. type accessToken struct {
  15. ID int64
  16. Sha1 string
  17. SHA256 string `gorm:"TYPE:VARCHAR(64)"`
  18. }
  19. if db.Migrator().HasColumn(&accessToken{}, "SHA256") {
  20. return errMigrationSkipped
  21. }
  22. return db.Transaction(func(tx *gorm.DB) error {
  23. // 1. Add column without constraints because all rows have NULL values for the
  24. // "sha256" column.
  25. err := tx.Migrator().AddColumn(&accessToken{}, "SHA256")
  26. if err != nil {
  27. return errors.Wrap(err, "add column")
  28. }
  29. // 2. Generate SHA256 for existing rows from their values in the "sha1" column.
  30. var accessTokens []*accessToken
  31. err = tx.Where("sha256 IS NULL").Find(&accessTokens).Error
  32. if err != nil {
  33. return errors.Wrap(err, "list")
  34. }
  35. for _, t := range accessTokens {
  36. sha256 := cryptoutil.SHA256(t.Sha1)
  37. err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error
  38. if err != nil {
  39. return errors.Wrap(err, "update")
  40. }
  41. }
  42. // 3. We are now safe to apply constraints to the "sha256" column.
  43. type accessTokenWithConstraint struct {
  44. SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
  45. }
  46. err = tx.Table("access_token").AutoMigrate(&accessTokenWithConstraint{})
  47. if err != nil {
  48. return errors.Wrap(err, "auto migrate")
  49. }
  50. return nil
  51. })
  52. }