aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/auth/provider.go
blob: 0d515ab4858ebeb5fdd99765be51450bec7088e8 (plain)
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
package auth

import (
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type Authenticator struct {
	secretKey []byte
	parser    *jwt.Parser
}

func NewAuthenticator(secretKey []byte) *Authenticator {
	parser := jwt.NewParser(jwt.WithIssuer("scrapbook"), jwt.WithExpirationRequired())

	a := &Authenticator{
		secretKey: secretKey,
		parser:    parser,
	}

	return a
}

func (a *Authenticator) NewJwt() (string, error) {
	t := jwt.NewWithClaims(jwt.SigningMethodHS256,
		jwt.MapClaims{
			"iss": "scrapbook",
			"exp": jwt.NewNumericDate(time.Now().Add(time.Hour * 2)),
		})

	return t.SignedString(a.secretKey)
}

func (a *Authenticator) VerifyJwt(token string) error {
	_, err := a.parser.Parse(token, func(t *jwt.Token) (interface{}, error) { return a.secretKey, nil })
	return err
}