mirror of
https://github.com/coaidev/coai.git
synced 2025-05-19 04:50:14 +09:00
refactor: improve user cache management and password migration
This commit is contained in:
parent
9f6cec4298
commit
e5d28b808d
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user