guard/internal/repository/token.go

302 lines
8.5 KiB
Go
Raw Normal View History

2024-08-06 05:59:24 +00:00
package repository
import (
"ark-permission/internal/domain"
"ark-permission/internal/domain/repository"
"ark-permission/internal/entity"
2024-08-08 03:02:13 +00:00
ers "code.30cm.net/wanderland/library-go/errors"
2024-08-06 05:59:24 +00:00
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/zeromicro/go-zero/core/stores/redis"
)
type TokenRepositoryParam struct {
Store *redis.Redis `name:"redis"`
}
type tokenRepository struct {
store *redis.Redis
}
func NewTokenRepository(param TokenRepositoryParam) repository.TokenRepository {
return &tokenRepository{
store: param.Store,
}
}
func (t *tokenRepository) Create(ctx context.Context, token entity.Token) error {
body, err := json.Marshal(token)
if err != nil {
2024-08-08 08:10:38 +00:00
return ers.ArkInternal("json.Marshal token error", err.Error())
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
if err := t.store.Pipelined(func(tx redis.Pipeliner) error {
refreshTTL := time.Duration(token.RedisRefreshExpiredSec()) * time.Second
2024-08-06 05:59:24 +00:00
2024-08-12 14:19:34 +00:00
if err := t.setToken(ctx, tx, token, body, refreshTTL); err != nil {
2024-08-06 05:59:24 +00:00
return err
}
2024-08-12 14:19:34 +00:00
if err := t.setRefreshToken(ctx, tx, token, refreshTTL); err != nil {
2024-08-06 05:59:24 +00:00
return err
}
2024-08-12 14:19:34 +00:00
return t.setRelation(ctx, tx, token.UID, token.DeviceID, token.ID, refreshTTL)
}); err != nil {
2024-08-08 08:10:38 +00:00
return domain.RedisPipLineError(err.Error())
2024-08-06 05:59:24 +00:00
}
2024-08-11 12:21:42 +00:00
return nil
}
func (t *tokenRepository) Delete(ctx context.Context, token entity.Token) error {
2024-08-12 14:19:34 +00:00
keys := []string{
domain.GetAccessTokenRedisKey(token.ID),
domain.RefreshTokenRedisKey.With(token.RefreshToken).ToString(),
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
if err := t.deleteKeys(ctx, keys...); err != nil {
return domain.RedisPipLineError(err.Error())
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
_, _ = t.store.Srem(domain.DeviceTokenRedisKey.With(token.DeviceID).ToString(), token.ID)
_, _ = t.store.Srem(domain.UIDTokenRedisKey.With(token.UID).ToString(), token.ID)
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
return nil
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) GetAccessTokenByID(ctx context.Context, id string) (entity.Token, error) {
token, err := t.get(ctx, domain.GetAccessTokenRedisKey(id))
2024-08-11 12:21:42 +00:00
if err != nil {
2024-08-12 14:19:34 +00:00
return entity.Token{}, err
2024-08-11 12:21:42 +00:00
}
2024-08-12 14:19:34 +00:00
return token, nil
2024-08-11 12:21:42 +00:00
}
func (t *tokenRepository) DeleteAccessTokensByUID(ctx context.Context, uid string) error {
tokens, err := t.GetAccessTokensByUID(ctx, uid)
if err != nil {
return err
}
2024-08-12 14:19:34 +00:00
for _, token := range tokens {
if err := t.Delete(ctx, token); err != nil {
2024-08-11 12:21:42 +00:00
return err
}
2024-08-06 05:59:24 +00:00
}
return nil
}
2024-08-11 12:21:42 +00:00
func (t *tokenRepository) DeleteAccessTokenByID(ctx context.Context, ids []string) error {
for _, tokenID := range ids {
token, err := t.GetAccessTokenByID(ctx, tokenID)
if err != nil {
continue
}
2024-08-12 14:19:34 +00:00
keys := []string{
domain.GetAccessTokenRedisKey(token.ID),
domain.RefreshTokenRedisKey.With(token.RefreshToken).ToString(),
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
if err := t.deleteKeys(ctx, keys...); err != nil {
2024-08-11 12:21:42 +00:00
continue
}
2024-08-12 14:19:34 +00:00
_, _ = t.store.Srem(domain.DeviceTokenRedisKey.With(token.DeviceID).ToString(), token.ID)
_, _ = t.store.Srem(domain.UIDTokenRedisKey.With(token.UID).ToString(), token.ID)
2024-08-11 12:21:42 +00:00
}
return nil
}
2024-08-10 01:52:23 +00:00
func (t *tokenRepository) GetAccessTokensByUID(ctx context.Context, uid string) ([]entity.Token, error) {
2024-08-12 14:19:34 +00:00
return t.getTokensBySet(ctx, domain.GetUIDTokenRedisKey(uid))
2024-08-08 03:02:13 +00:00
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) GetAccessTokensByDeviceID(ctx context.Context, deviceID string) ([]entity.Token, error) {
return t.getTokensBySet(ctx, domain.DeviceTokenRedisKey.With(deviceID).ToString())
}
2024-08-10 01:52:23 +00:00
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) DeleteAccessTokensByDeviceID(ctx context.Context, deviceID string) error {
2024-08-10 01:52:23 +00:00
2024-08-12 14:19:34 +00:00
tokens, err := t.GetAccessTokensByDeviceID(ctx, deviceID)
2024-08-10 01:52:23 +00:00
if err != nil {
2024-08-12 14:19:34 +00:00
return domain.RedisDelError(fmt.Sprintf("GetAccessTokensByDeviceID error: %v", err))
2024-08-10 01:52:23 +00:00
}
2024-08-12 14:19:34 +00:00
var keys []string
for _, token := range tokens {
keys = append(keys, domain.GetAccessTokenRedisKey(token.ID))
keys = append(keys, domain.RefreshTokenRedisKey.With(token.RefreshToken).ToString())
2024-08-10 01:52:23 +00:00
2024-08-12 14:19:34 +00:00
}
2024-08-10 01:52:23 +00:00
2024-08-12 14:19:34 +00:00
err = t.store.Pipelined(func(tx redis.Pipeliner) error {
2024-08-10 01:52:23 +00:00
for _, token := range tokens {
2024-08-12 14:19:34 +00:00
_, _ = t.store.Srem(domain.UIDTokenRedisKey.With(token.UID).ToString(), token.ID)
2024-08-10 01:52:23 +00:00
}
return nil
})
if err != nil {
2024-08-12 14:19:34 +00:00
return err
2024-08-10 01:52:23 +00:00
}
2024-08-12 14:19:34 +00:00
if err := t.deleteKeys(ctx, keys...); err != nil {
return err
2024-08-10 01:52:23 +00:00
}
2024-08-12 14:19:34 +00:00
_, err = t.store.Del(domain.DeviceTokenRedisKey.With(deviceID).ToString())
return err
2024-08-10 01:52:23 +00:00
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) GetAccessTokenCountByDeviceID(deviceID string) (int, error) {
return t.getCountBySet(domain.DeviceTokenRedisKey.With(deviceID).ToString())
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) GetAccessTokenCountByUID(uid string) (int, error) {
return t.getCountBySet(domain.UIDTokenRedisKey.With(uid).ToString())
2024-08-11 12:21:42 +00:00
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) GetAccessTokenByByOneTimeToken(ctx context.Context, oneTimeToken string) (entity.Token, error) {
id, err := t.store.Get(domain.RefreshTokenRedisKey.With(oneTimeToken).ToString())
2024-08-11 12:21:42 +00:00
if err != nil {
2024-08-12 14:19:34 +00:00
return entity.Token{}, domain.RedisError(fmt.Sprintf("GetAccessTokenByByOneTimeToken store.Get error: %s", err.Error()))
2024-08-11 12:21:42 +00:00
}
2024-08-12 14:19:34 +00:00
if id == "" {
return entity.Token{}, ers.ResourceNotFound("token key not found in redis", domain.RefreshTokenRedisKey.With(oneTimeToken).ToString())
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
return t.GetAccessTokenByID(ctx, id)
}
2024-08-08 03:02:13 +00:00
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) DeleteOneTimeToken(ctx context.Context, ids []string, tokens []entity.Token) error {
var keys []string
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
for _, id := range ids {
keys = append(keys, domain.RefreshTokenRedisKey.With(id).ToString())
}
2024-08-08 03:02:13 +00:00
2024-08-12 14:19:34 +00:00
for _, token := range tokens {
keys = append(keys, domain.RefreshTokenRedisKey.With(token.RefreshToken).ToString())
2024-08-08 03:02:13 +00:00
}
2024-08-12 14:19:34 +00:00
return t.deleteKeys(ctx, keys...)
2024-08-08 03:02:13 +00:00
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) CreateOneTimeToken(ctx context.Context, key string, ticket entity.Ticket, expires time.Duration) error {
body, err := json.Marshal(ticket)
2024-08-11 12:21:42 +00:00
if err != nil {
2024-08-12 14:19:34 +00:00
return ers.InvalidFormat("CreateOneTimeToken json.Marshal error", err.Error())
2024-08-11 12:21:42 +00:00
}
2024-08-12 14:19:34 +00:00
_, err = t.store.SetnxEx(domain.RefreshTokenRedisKey.With(key).ToString(), string(body), int(expires.Seconds()))
2024-08-11 12:21:42 +00:00
if err != nil {
2024-08-12 14:19:34 +00:00
return domain.RedisError(fmt.Sprintf("CreateOneTimeToken store.SetnxEx error: %s", err.Error()))
2024-08-11 12:21:42 +00:00
}
2024-08-12 14:19:34 +00:00
return nil
2024-08-11 12:21:42 +00:00
}
// -------------------- Private area --------------------
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) get(ctx context.Context, key string) (entity.Token, error) {
body, err := t.store.GetCtx(ctx, key)
if err != nil {
return entity.Token{}, domain.RedisError(fmt.Sprintf("token %s not found in redis: %s", key, err.Error()))
2024-08-08 03:02:13 +00:00
}
2024-08-12 14:19:34 +00:00
if body == "" {
return entity.Token{}, ers.ResourceNotFound("this token not found")
2024-08-08 03:02:13 +00:00
}
var token entity.Token
if err := json.Unmarshal([]byte(body), &token); err != nil {
2024-08-12 14:19:34 +00:00
return entity.Token{}, ers.ArkInternal("json.Unmarshal token error", err.Error())
2024-08-08 03:02:13 +00:00
}
return token, nil
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) setToken(ctx context.Context, tx redis.Pipeliner, token entity.Token, body []byte, ttl time.Duration) error {
return tx.Set(ctx, domain.GetAccessTokenRedisKey(token.ID), body, ttl).Err()
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) setRefreshToken(ctx context.Context, tx redis.Pipeliner, token entity.Token, ttl time.Duration) error {
2024-08-06 05:59:24 +00:00
if token.RefreshToken != "" {
2024-08-12 14:19:34 +00:00
return tx.Set(ctx, domain.RefreshTokenRedisKey.With(token.RefreshToken).ToString(), token.ID, ttl).Err()
2024-08-06 05:59:24 +00:00
}
return nil
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) setRelation(ctx context.Context, tx redis.Pipeliner, uid, deviceID, tokenID string, ttl time.Duration) error {
if err := tx.SAdd(ctx, domain.UIDTokenRedisKey.With(uid).ToString(), tokenID).Err(); err != nil {
2024-08-11 12:21:42 +00:00
return err
2024-08-06 05:59:24 +00:00
}
2024-08-11 12:21:42 +00:00
2024-08-12 14:19:34 +00:00
if err := tx.SAdd(ctx, domain.DeviceTokenRedisKey.With(deviceID).ToString(), tokenID).Err(); err != nil {
2024-08-11 12:21:42 +00:00
return err
}
2024-08-06 05:59:24 +00:00
return nil
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) deleteKeys(ctx context.Context, keys ...string) error {
return t.store.Pipelined(func(tx redis.Pipeliner) error {
for _, key := range keys {
if err := tx.Del(ctx, key).Err(); err != nil {
return domain.RedisDelError(fmt.Sprintf("store.Del key error: %v", err))
}
}
return nil
})
}
2024-08-06 05:59:24 +00:00
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) getTokensBySet(ctx context.Context, setKey string) ([]entity.Token, error) {
ids, err := t.store.Smembers(setKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, nil
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
return nil, domain.RedisError(fmt.Sprintf("getTokensBySet store.Get %s error: %v", setKey, err.Error()))
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
var tokens []entity.Token
var deleteTokens []string
2024-08-06 05:59:24 +00:00
now := time.Now().Unix()
2024-08-12 14:19:34 +00:00
for _, id := range ids {
token, err := t.get(ctx, domain.GetAccessTokenRedisKey(id))
if err != nil {
deleteTokens = append(deleteTokens, id)
continue
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
if int64(token.ExpiresIn) < now {
deleteTokens = append(deleteTokens, id)
continue
}
tokens = append(tokens, token)
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
if len(deleteTokens) > 0 {
_ = t.DeleteAccessTokenByID(ctx, deleteTokens)
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
return tokens, nil
2024-08-06 05:59:24 +00:00
}
2024-08-12 14:19:34 +00:00
func (t *tokenRepository) getCountBySet(setKey string) (int, error) {
count, err := t.store.Scard(setKey)
if err != nil {
return 0, err
}
return int(count), nil
2024-08-06 05:59:24 +00:00
}