Skip to content

Commit 7e3ef1c

Browse files
Create token module for JWT handling
1 parent f7ac5a3 commit 7e3ef1c

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

internal/token/token.go

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package token
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"strings"
7+
"time"
8+
9+
"github.com/golang-jwt/jwt/v5"
10+
11+
"github.com/PythonHacker24/linux-acl-management-backend/config"
12+
)
13+
14+
/* generating jwt token for user identification with specified configs */
15+
func GenerateJWT(username string) (string, error) {
16+
expiryHours := config.BackendConfig.BackendSecurity.JWTExpiry
17+
18+
/* generate JWT token with claims */
19+
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
20+
"username": username,
21+
"exp": time.Now().Add(time.Hour * time.Duration(expiryHours)).Unix(),
22+
})
23+
24+
return token.SignedString([]byte(config.BackendConfig.BackendSecurity.JWTTokenSecret))
25+
}
26+
27+
/* validate JWT token and return claims */
28+
func ValidateJWT(tokenString string) (jwt.MapClaims, error) {
29+
/* parse the token */
30+
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
31+
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
32+
return nil, fmt.Errorf("unexpected signing method")
33+
}
34+
return []byte(config.BackendConfig.BackendSecurity.JWTTokenSecret), nil
35+
})
36+
37+
/* check if token is valid */
38+
if err != nil {
39+
return nil, fmt.Errorf("JWT parsing error: %w", err)
40+
}
41+
42+
/* check if token is valid */
43+
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
44+
return claims, nil
45+
}
46+
47+
return nil, fmt.Errorf("invalid token")
48+
}
49+
50+
/* extracts username from JWT token */
51+
func GetUsernameFromJWT(tokenString string) (string, error) {
52+
/* get claims from JWT Token */
53+
claims, err := ValidateJWT(tokenString)
54+
if err != nil {
55+
return "", fmt.Errorf("JWT validation error: %w", err)
56+
}
57+
58+
/* extract username from JWT Token */
59+
username, ok := claims["username"].(string)
60+
if !ok {
61+
return "", fmt.Errorf("username not found in token")
62+
}
63+
64+
return username, nil
65+
}
66+
67+
/* extract username from http request (wrapper around GetUsernameFromJWT for http requests) */
68+
func ExtractUsernameFromRequest(r *http.Request) (string, error) {
69+
/* get the authorization header */
70+
authHeader := r.Header.Get("Authorization")
71+
if authHeader == "" {
72+
return "", fmt.Errorf("authorization header not found")
73+
}
74+
75+
/* check if the header is in the correct format */
76+
parts := strings.Split(authHeader, " ")
77+
if len(parts) != 2 || parts[0] != "Bearer" {
78+
return "", fmt.Errorf("invalid authorization header format")
79+
}
80+
81+
/* extract username from JWT token */
82+
return GetUsernameFromJWT(parts[1])
83+
}

0 commit comments

Comments
 (0)