zero-ppanel/pkg/signature/nonce_store.go

33 lines
895 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package signature
import (
"context"
"github.com/zeromicro/go-zero/core/stores/redis"
)
// NonceStore 防重放存储接口
type NonceStore interface {
// SetIfNotExists 返回 (true, nil) 表示 key 已存在(重放攻击)
SetIfNotExists(ctx context.Context, appId, nonce string, ttlSeconds int64) (bool, error)
}
type RedisNonceStore struct {
client *redis.Redis
}
func NewRedisNonceStore(client *redis.Redis) *RedisNonceStore {
return &RedisNonceStore{client: client}
}
func (s *RedisNonceStore) SetIfNotExists(_ context.Context, appId, nonce string, ttlSeconds int64) (bool, error) {
key := "sig:nonce:" + appId + ":" + nonce
// go-zero redis.Redis.SetNX 返回 true 表示设置成功(首次)
ok, err := s.client.SetnxEx(key, "1", int(ttlSeconds))
if err != nil {
return false, err
}
// SetnxEx ok=true 首次ok=false 已存在(重放)
return !ok, nil
}