-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokens.go
76 lines (65 loc) · 1.88 KB
/
tokens.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
72
73
74
75
76
package models
import (
"time"
"github.com/google/uuid"
"github.com/nats-io/jwt"
"gorm.io/gorm"
)
// OwnerType is the struct that is used to define the owner of the token.
type OwnerType string
const (
// Operator is the owner of the token.
OperatorToken OwnerType = "operator"
// Account is the owner of the token.
AccountToken OwnerType = "account"
// User is the owner of the token.
UserToken OwnerType = "user"
)
// Token is a model for storing the the JWT token used to authenticate the user.
type Token struct {
// ID is the unique identifier for the token.
// This is the public key portion of the NKey.
ID string `json:"token_id" gorm:"primaryKey"`
// Token is the JWT token used to authenticate the account.
Token string `json:"token"`
// OwnerID is the owner of the token.
OwnerID uuid.UUID `json:"owner_id"`
// OwnerType is the type of the owner.
OwnerType OwnerType `json:"owner_type"`
// CreatedAt is the time the token was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is the time the token was updated.
UpdatedAt time.Time `json:"updated_at"`
// DeletedAt is the time the token was deleted.
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// Bytes returns the token as a byte slice.
func (t *Token) Bytes() []byte {
return []byte(t.Token)
}
// DeepCopy returns a deep copy of the token.
func (t *Token) DeepCopy() Token {
return Token{
ID: t.ID,
Token: t.Token,
CreatedAt: t.CreatedAt,
UpdatedAt: t.UpdatedAt,
DeletedAt: t.DeletedAt,
}
}
// PublicKey returns the public key of the token.
func (t *Token) PublicKey() (string, error) {
claim, err := t.Claim()
if err != nil {
return "", err
}
return claim.Subject, nil
}
// Claim is returning the claim of the token.
func (t *Token) Claim() (*jwt.GenericClaims, error) {
claim, err := jwt.DecodeGeneric(t.Token)
if err != nil {
return nil, err
}
return claim, nil
}