Refactored project structure
This commit is contained in:
41
backend/handlers/jwt.go
Normal file
41
backend/handlers/jwt.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user