Refactored project structure

This commit is contained in:
2025-10-16 22:45:31 +02:00
parent cf74cce51c
commit d13ea9fc27
13 changed files with 1156 additions and 1023 deletions

41
backend/handlers/jwt.go Normal file
View File

@@ -0,0 +1,41 @@
package handlers
import (
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
var jwtSecret = []byte("supersecretkey") // TODO: move to env variable
func generateToken(userID int, username string) (string, error) {
claims := jwt.MapClaims{
"user_id": userID,
"username": username,
"exp": time.Now().Add(2 * time.Hour).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(jwtSecret)
}
func usernameFromJWT(r *http.Request) (string, error) {
auth := r.Header.Get("Authorization")
parts := strings.SplitN(auth, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
return "", nil
}
tokenStr := parts[1]
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) { return jwtSecret, nil })
if err != nil || !token.Valid {
return "", err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if u, ok := claims["username"].(string); ok {
return u, nil
}
}
return "", nil
}