/
jwt.go
64 lines (53 loc) · 1.66 KB
/
jwt.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
60
61
62
63
64
package middleware
import (
"github.com/dgrijalva/jwt-go"
"github.com/joho/godotenv"
"github.com/labstack/echo/middleware"
"go-echo-api/models"
"os"
"path/filepath"
"time"
)
// on this function why load .env
// because handler function on echo reload before
// func init on main.go
func GetJwtSecretKey() []byte {
fileExecutable, _ := os.Executable()
basepath, _ := filepath.Split(fileExecutable)
if os.Getenv("APP_ENV") != "production" {
basepath = ""
}
_ = godotenv.Load(basepath + ".env")
jwtSecretKey := os.Getenv("JWT_SECRET_KEY")
return []byte(jwtSecretKey)
}
var IsLoggedIn = middleware.JWTWithConfig(
middleware.JWTConfig{
SigningKey: GetJwtSecretKey(),
ContextKey: "user",
TokenLookup: "header:Authorization",
AuthScheme: "Bearer",
Claims: jwt.MapClaims{},
})
func GenerateTokenPair(user models.User) (*string, *string, interface{}, error) {
// Create token with claims
token := jwt.New(jwt.SigningMethodHS256)
tokenClaims := token.Claims.(jwt.MapClaims)
tokenClaims["id"] = user.ID
tokenClaims["email"] = user.Email
tokenClaims["name"] = user.Name
tokenClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()
// Generate encoded token and send it as response.
refreshToken := jwt.New(jwt.SigningMethodHS256)
rtClaims := refreshToken.Claims.(jwt.MapClaims)
rtClaims["email"] = user.Email
rtClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()
//Encode Token
accessToken, err := token.SignedString([]byte(os.Getenv("JWT_SECRET_KEY")))
//Encode Refresh Token
rt, err := refreshToken.SignedString([]byte(os.Getenv("JWT_SECRET_KEY")))
if err != nil {
return nil, nil, nil, err
}
return &accessToken, &rt, tokenClaims["exp"], nil
}