-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
56 lines (45 loc) · 1.2 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
package helpers
import (
"strings"
"time"
"github.com/FianGumilar/email-otp-verification/config"
"github.com/FianGumilar/email-otp-verification/models"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
)
type JwtClaims struct {
ID int64 `json:"id"`
Email string `json:"email"`
Username string `json:"username"`
jwt.StandardClaims
}
func GenerateJwtToken(user models.User) (string, error) {
claims := JwtClaims{
user.ID,
user.Email,
user.FullName,
jwt.StandardClaims{
Id: "12345678",
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
},
}
rawToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := rawToken.SignedString([]byte(config.GetEnv("JWT_KEY")))
if err != nil {
return "", err
}
return token, nil
}
func ParseToken(ctx echo.Context) (*JwtClaims, error) {
token := ctx.Request().Header.Get("Authorization")
token = strings.ReplaceAll(token, "Bearer ", "")
// Parse Token Jwt
claims := &JwtClaims{}
parsedToken, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {
return []byte(config.GetEnv("JWT_KEY")), nil
})
if err != nil || !parsedToken.Valid {
return nil, err
}
return claims, nil
}