43 lines
943 B
Go
43 lines
943 B
Go
package tokenize
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.nobla.cn/golang/aeus/pkg/cache"
|
|
"git.nobla.cn/golang/aeus/pkg/errors"
|
|
)
|
|
|
|
// Tokenize 实现简单的session管理, 结合AuthService和JWT middleware可以实现登录和登出等操作
|
|
type Tokenize struct {
|
|
cache cache.Cache
|
|
}
|
|
|
|
func (t *Tokenize) buildKey(token string) string {
|
|
return "user:session:" + token
|
|
}
|
|
|
|
func (t *Tokenize) Put(ctx context.Context, token string, ttl int64) error {
|
|
return t.cache.Store(ctx, t.buildKey(token), token, time.Second*time.Duration(ttl))
|
|
}
|
|
|
|
func (t *Tokenize) Del(ctx context.Context, token string) error {
|
|
return t.cache.Delete(ctx, t.buildKey(token))
|
|
}
|
|
|
|
func (t *Tokenize) Validate(ctx context.Context, token string) (err error) {
|
|
var ok bool
|
|
if ok, err = t.cache.Exists(ctx, t.buildKey(token)); err == nil {
|
|
if !ok {
|
|
return errors.ErrAccessDenied
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func New(c cache.Cache) *Tokenize {
|
|
return &Tokenize{
|
|
cache: c,
|
|
}
|
|
}
|