-
Notifications
You must be signed in to change notification settings - Fork 63
/
jwt_auth_service.go
59 lines (50 loc) · 1.48 KB
/
jwt_auth_service.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
package services
import (
"errors"
"github.com/dgrijalva/jwt-go"
"github.com/dipeshdulal/clean-gin/domains"
"github.com/dipeshdulal/clean-gin/lib"
"github.com/dipeshdulal/clean-gin/models"
)
// JWTAuthService service relating to authorization
type JWTAuthService struct {
env lib.Env
logger lib.Logger
}
// NewJWTAuthService creates a new auth service
func NewJWTAuthService(env lib.Env, logger lib.Logger) domains.AuthService {
return JWTAuthService{
env: env,
logger: logger,
}
}
// Authorize authorizes the generated token
func (s JWTAuthService) Authorize(tokenString string) (bool, error) {
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
return []byte(s.env.JWTSecret), nil
})
if token.Valid {
return true, nil
} else if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return false, errors.New("token malformed")
}
if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
return false, errors.New("token expired")
}
}
return false, errors.New("couldn't handle token")
}
// CreateToken creates jwt auth token
func (s JWTAuthService) CreateToken(user models.User) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": user.ID,
"name": user.Name,
"email": *user.Email,
})
tokenString, err := token.SignedString([]byte(s.env.JWTSecret))
if err != nil {
s.logger.Error("JWT validation failed: ", err)
}
return tokenString
}