refactor: improve user cache management and password migration
Some checks failed
Build Test / release (18.x) (push) Has been cancelled
Docker Image CI / build (push) Has been cancelled

This commit is contained in:
ncs19960831 2025-02-26 21:00:10 +08:00 committed by Sh1n3zZ
parent 9f6cec4298
commit e5d28b808d

View File

@ -113,19 +113,40 @@ func getUsersForm(db *sql.DB, page int64, search string) PaginationForm {
}
}
// clearUserCache clears all cache keys starting with nio:user:
func clearUserCache(cache *redis.Client) error {
ctx := context.Background()
iter := cache.Scan(ctx, 0, "nio:user:*", 100).Iterator()
for iter.Next(ctx) {
if err := cache.Del(ctx, iter.Val()).Err(); err != nil {
return fmt.Errorf("failed to delete cache key %s: %v", iter.Val(), err)
}
}
return iter.Err()
}
func passwordMigration(db *sql.DB, cache *redis.Client, id int64, password string) error {
password = strings.TrimSpace(password)
if len(password) < 6 || len(password) > 36 {
return fmt.Errorf("password length must be between 6 and 36")
}
hash_passwd := utils.Sha2Encrypt(password)
// Update password in database
_, err := globals.ExecDb(db, `
UPDATE auth SET password = ? WHERE id = ?
`, utils.Sha2Encrypt(password), id)
`, hash_passwd, id)
cache.Del(context.Background(), fmt.Sprint("nio:user:root"))
if err != nil {
return err
}
return err
// Clear all user related cache
if err := clearUserCache(cache); err != nil {
return fmt.Errorf("failed to clear user cache: %v", err)
}
return nil
}
func emailMigration(db *sql.DB, id int64, email string) error {
@ -228,7 +249,10 @@ func UpdateRootPassword(db *sql.DB, cache *redis.Client, password string) error
return err
}
cache.Del(context.Background(), fmt.Sprint("nio:user:root"))
// Clear all user related cache
if err := clearUserCache(cache); err != nil {
return fmt.Errorf("failed to clear user cache: %v", err)
}
return nil
}