/
token.go
45 lines (36 loc) · 1 KB
/
token.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package core
import (
"context"
"github.com/kuzznya/letsdeploy/app/apperrors"
"github.com/kuzznya/letsdeploy/app/middleware"
"github.com/redis/go-redis/v9"
"math/rand"
"time"
)
const tempTokenPrefix = "ldt_"
type Tokens interface {
CreateTempToken(ctx context.Context, auth middleware.Authentication) (string, error)
}
type tokensImpl struct {
rdb *redis.Client
}
var _ Tokens = (*tokensImpl)(nil)
func InitTokens(rdb *redis.Client) Tokens {
return &tokensImpl{
rdb: rdb,
}
}
func (t tokensImpl) CreateTempToken(ctx context.Context, auth middleware.Authentication) (string, error) {
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
tokenLen := 16
b := make([]rune, tokenLen)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
token := tempTokenPrefix + string(b)
err := t.rdb.Set(ctx, token, auth.Username, 1*time.Minute).Err()
if err != nil {
return "", apperrors.InternalServerErrorWrap(err, "failed to save token to Redis")
}
return token, nil
}