-
Notifications
You must be signed in to change notification settings - Fork 0
/
signer.go
53 lines (40 loc) · 1.15 KB
/
signer.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
// Copyright (C) 2021 Creditor Corp. Group.
// See LICENSE for copying information.
package goauth
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"github.com/zeebo/errs"
)
// TokenSignerError is an error class for TokenSigner errors.
var TokenSignerError = errs.Class("auth token signer error")
// TokenSigner creates signature for provided auth Token. Its hmac256 based TokenSigner.
type TokenSigner struct {
Secret []byte
}
// SignToken signs token with some secret key.
func (a *TokenSigner) SignToken(token *Token) error {
mac := hmac.New(sha256.New, a.Secret)
encoded := base64.URLEncoding.EncodeToString(token.Payload)
_, err := mac.Write([]byte(encoded))
if err != nil {
return TokenSignerError.Wrap(err)
}
token.Signature = mac.Sum(nil)
return nil
}
// CreateToken creates string representation.
func (a *TokenSigner) CreateToken(ctx context.Context, claims *Claims) (string, error) {
json, err := claims.JSON()
if err != nil {
return "", TokenSignerError.Wrap(err)
}
token := Token{Payload: json}
err = a.SignToken(&token)
if err != nil {
return "", TokenSignerError.Wrap(err)
}
return token.String(), nil
}