forked from vmware-archive/atc
/
token_generator.go
48 lines (37 loc) · 1.13 KB
/
token_generator.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
package auth
import (
"crypto/rsa"
"time"
"github.com/dgrijalva/jwt-go"
)
//go:generate counterfeiter . TokenGenerator
type TokenType string
type TokenValue string
const TokenTypeBearer = "Bearer"
const expClaimKey = "exp"
const teamNameClaimKey = "teamName"
const teamIDClaimKey = "teamID"
const isAdminClaimKey = "isAdmin"
type TokenGenerator interface {
GenerateToken(expiration time.Time, teamName string, teamID int, isAdmin bool) (TokenType, TokenValue, error)
}
type tokenGenerator struct {
privateKey *rsa.PrivateKey
}
func NewTokenGenerator(privateKey *rsa.PrivateKey) TokenGenerator {
return &tokenGenerator{
privateKey: privateKey,
}
}
func (generator *tokenGenerator) GenerateToken(expiration time.Time, teamName string, teamID int, isAdmin bool) (TokenType, TokenValue, error) {
jwtToken := jwt.New(SigningMethod)
jwtToken.Claims["exp"] = expiration.Unix()
jwtToken.Claims["teamName"] = teamName
jwtToken.Claims["teamID"] = teamID
jwtToken.Claims["isAdmin"] = isAdmin
signed, err := jwtToken.SignedString(generator.privateKey)
if err != nil {
return "", "", err
}
return TokenTypeBearer, TokenValue(signed), err
}