Skip to content

Commit 6619dd9

Browse files
committed
feat(auth): extract jwt token validation to make it reusable for cli
1 parent f39ae34 commit 6619dd9

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

internal/app/jwt/jwt.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,23 @@ import (
44
"os"
55
"time"
66

7-
"github.com/golang-jwt/jwt/v4"
7+
jwtlib "github.com/golang-jwt/jwt/v4"
88
)
99

1010
var JwtSecret = []byte(os.Getenv("JWT_SECRET"))
1111

1212
func CreateToken(userID string) (string, error) {
13-
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
13+
token := jwtlib.NewWithClaims(jwtlib.SigningMethodHS256, jwtlib.MapClaims{
1414
"user_id": userID,
1515
"exp": time.Now().Add(24 * time.Hour).Unix(),
1616
})
1717
return token.SignedString(JwtSecret)
1818
}
19+
20+
func ValidateToken(token string) (*jwtlib.Token, map[string]interface{}, error) {
21+
claims := jwtlib.MapClaims{}
22+
t, err := jwtlib.ParseWithClaims(token, claims, func(t *jwtlib.Token) (interface{}, error) {
23+
return JwtSecret, nil
24+
})
25+
return t, claims, err
26+
}

internal/app/middleware/auth.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"github.com/axzilla/deeploy/internal/app/cookie"
88
"github.com/axzilla/deeploy/internal/app/jwt"
99
"github.com/axzilla/deeploy/internal/app/services"
10-
jwtlib "github.com/golang-jwt/jwt/v4"
1110
)
1211

1312
type AuthMiddleWare struct {
@@ -26,10 +25,7 @@ func (m *AuthMiddleWare) Auth(next http.HandlerFunc) http.HandlerFunc {
2625
return
2726
}
2827

29-
claims := jwtlib.MapClaims{}
30-
t, err := jwtlib.ParseWithClaims(token, claims, func(t *jwtlib.Token) (interface{}, error) {
31-
return jwt.JwtSecret, nil
32-
})
28+
t, claims, err := jwt.ValidateToken(token)
3329
if err != nil || !t.Valid {
3430
http.Error(w, "Unauthorized", http.StatusUnauthorized)
3531
return

0 commit comments

Comments
 (0)