-
Notifications
You must be signed in to change notification settings - Fork 130
/
api_token.go
71 lines (58 loc) · 1.76 KB
/
api_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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package prisma
import (
"context"
"time"
"github.com/hatchet-dev/hatchet/internal/repository"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/db"
"github.com/hatchet-dev/hatchet/internal/validator"
)
type apiTokenRepository struct {
client *db.PrismaClient
v validator.Validator
}
func NewAPITokenRepository(client *db.PrismaClient, v validator.Validator) repository.APITokenRepository {
return &apiTokenRepository{
client: client,
v: v,
}
}
func (a *apiTokenRepository) GetAPITokenById(id string) (*db.APITokenModel, error) {
return a.client.APIToken.FindUnique(
db.APIToken.ID.Equals(id),
).Exec(context.Background())
}
func (a *apiTokenRepository) CreateAPIToken(opts *repository.CreateAPITokenOpts) (*db.APITokenModel, error) {
if err := a.v.Validate(opts); err != nil {
return nil, err
}
optionals := []db.APITokenSetParam{
db.APIToken.ID.Set(opts.ID),
db.APIToken.ExpiresAt.Set(opts.ExpiresAt),
}
if opts.TenantId != nil {
optionals = append(optionals, db.APIToken.Tenant.Link(
db.Tenant.ID.Equals(*opts.TenantId),
))
}
if opts.Name != nil {
optionals = append(optionals, db.APIToken.Name.Set(*opts.Name))
}
return a.client.APIToken.CreateOne(
optionals...,
).Exec(context.Background())
}
func (a *apiTokenRepository) RevokeAPIToken(id string) error {
_, err := a.client.APIToken.FindUnique(
db.APIToken.ID.Equals(id),
).Update(
db.APIToken.ExpiresAt.Set(time.Now().Add(-1*time.Second)),
db.APIToken.Revoked.Set(true),
).Exec(context.Background())
return err
}
func (a *apiTokenRepository) ListAPITokensByTenant(tenantId string) ([]db.APITokenModel, error) {
return a.client.APIToken.FindMany(
db.APIToken.TenantID.Equals(tenantId),
db.APIToken.Revoked.Equals(false),
).Exec(context.Background())
}