-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
49 lines (41 loc) · 1.15 KB
/
auth.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
package auth
import (
"crypto/rsa"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
type Auth interface {
GenerateToken(email string, exp time.Duration) (string, error)
ValidateToken(token string) (string, error)
}
type tokenClaim struct {
Email string `json:"email"`
jwt.StandardClaims
}
type JWTAuth struct {
privateKey *rsa.PrivateKey
publicKey *rsa.PublicKey
}
func (a *JWTAuth) GenerateToken(email string, exp time.Duration) (string, error) {
jwtClaims := jwt.MapClaims{
"email": email,
"exp": time.Now().Add(exp).Unix()}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwtClaims)
return token.SignedString(a.privateKey)
}
func (a *JWTAuth) ValidateToken(token string) (string, error) {
parsedToken, err := jwt.ParseWithClaims(token, &tokenClaim{}, func(*jwt.Token) (interface{}, error) {
return a.publicKey, nil
})
if err != nil || !parsedToken.Valid {
return "", ErrPermissionDenied
}
claims, ok := parsedToken.Claims.(*tokenClaim)
if !ok {
return "", ErrPermissionDenied
}
return claims.Email, nil
}
func New(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Auth {
return &JWTAuth{privateKey: privateKey, publicKey: publicKey}
}