/
auth_service.go
45 lines (38 loc) · 1.33 KB
/
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
package service
import (
"encoding/base64"
"fmt"
"github.com/OscarYuen/go-graphql-starter/context"
"github.com/OscarYuen/go-graphql-starter/model"
jwt "github.com/dgrijalva/jwt-go"
"github.com/op/go-logging"
"time"
)
type AuthService struct {
appName *string
signedSecret *string
expiredTimeInSecond *time.Duration
log *logging.Logger
}
func NewAuthService(config *context.Config, log *logging.Logger) *AuthService {
return &AuthService{&config.AppName, &config.JWTSecret, &config.JWTExpireIn, log}
}
func (a *AuthService) SignJWT(user *model.User) (*string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": base64.StdEncoding.EncodeToString([]byte(user.ID)),
"created_at": user.CreatedAt,
"exp": time.Now().Add(time.Second * *a.expiredTimeInSecond).Unix(),
"iss": *a.appName,
})
tokenString, err := token.SignedString([]byte(*a.signedSecret))
return &tokenString, err
}
func (a *AuthService) ValidateJWT(tokenString *string) (*jwt.Token, error) {
token, err := jwt.Parse(*tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf(" unexpected signing method: %v", token.Header["alg"])
}
return []byte(*a.signedSecret), nil
})
return token, err
}