init repo
This commit is contained in:
63
internal/storage/cache/user.go
vendored
Normal file
63
internal/storage/cache/user.go
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
UserSmsCodeTTL = 10 * time.Minute
|
||||
UserSendSmsLimitTTL = 24 * time.Hour
|
||||
UserSendSmsLimitCount = 5
|
||||
)
|
||||
|
||||
const (
|
||||
UserSmsCodePrefix = "user:sms_code:%s"
|
||||
UserSendSmsLimit = "user:send_sms_limit:%s"
|
||||
)
|
||||
|
||||
func GetUserSmsCode(ctx context.Context, phone string) (string, error) {
|
||||
code, err := RedisClient.Get(ctx, fmt.Sprintf(UserSmsCodePrefix, phone)).Result()
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
||||
func SetUserSmsCode(ctx context.Context, phone, code string) error {
|
||||
return RedisClient.Set(ctx, fmt.Sprintf(UserSmsCodePrefix, phone), code, UserSmsCodeTTL).Err()
|
||||
}
|
||||
|
||||
func GetUserSendSmsLimit(ctx context.Context, phone string) (int, error) {
|
||||
limit, err := RedisClient.Get(ctx, fmt.Sprintf(UserSendSmsLimit, phone)).Result()
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return strconv.Atoi(limit)
|
||||
}
|
||||
|
||||
func SetUserSendSmsLimit(ctx context.Context, phone string) error {
|
||||
count, err := RedisClient.Incr(ctx, fmt.Sprintf(UserSendSmsLimit, phone)).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > UserSendSmsLimitCount {
|
||||
return errors.New("send sms limit")
|
||||
}
|
||||
return RedisClient.Expire(ctx, fmt.Sprintf(UserSendSmsLimit, phone), UserSendSmsLimitTTL).Err()
|
||||
}
|
||||
|
||||
func DeleteUserSmsCode(ctx context.Context, phone string) error {
|
||||
return RedisClient.Del(ctx, fmt.Sprintf(UserSmsCodePrefix, phone)).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user