Files
latosa-escrima/backend/api/auth.go
cdricms 9a6e4a7565 Added some routes for users
And some fixes
2025-01-16 10:51:30 +01:00

154 lines
3.4 KiB
Go

package api
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
core "fr.latosa-escrima/api/core"
"github.com/golang-jwt/jwt/v5"
)
var MySigningKey = []byte("COUCOU")
type LoginInformation struct {
Email string `json:"email"`
Password string `json:"password"`
}
type Claims struct {
UserID string `json:"user_id"`
jwt.RegisteredClaims
}
func HandleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
core.JSONError{
Status: core.Error,
Message: "Method is not allowed",
}.Respond(w, http.StatusMethodNotAllowed)
return
}
if r.Body == nil {
core.JSONError{
Status: core.Error,
Message: "No body has been provided.",
}.Respond(w, http.StatusNoContent)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
var login LoginInformation
err = json.Unmarshal(body, &login)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
var user core.User
count, err := core.DB.NewSelect().
Model(&user).
Where("email = ? AND password = ?", login.Email, login.Password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
core.JSONError{
Status: core.Error,
Message: "User not found.",
}.Respond(w, http.StatusNotFound)
return
}
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
claims := Claims{
UserID: user.UserID.String(),
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "latosa-escrima.fr",
Subject: "authentification",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString(MySigningKey)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
core.JSONSuccess{
Status: core.Success,
Message: "JWT Created",
Data: signed,
}.Respond(w, http.StatusCreated)
}
func AuthJWT(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the Authorization header is provided
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
core.JSONError{
Status: core.Error,
Message: "Missing Authorization header",
}.Respond(w, http.StatusUnauthorized)
return
}
// Bearer token is expected, so split the header into "Bearer <token>"
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
core.JSONError{
Status: core.Error,
Message: "Invalid Authorization header format",
}.Respond(w, http.StatusUnauthorized)
return
}
// Parse the token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Ensure that the token's signing method is valid
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return MySigningKey, nil
})
if err != nil || !token.Valid {
core.JSONError{
Status: core.Error,
Message: "Invalid Token",
}.Respond(w, http.StatusUnauthorized)
return
}
// Call the next handler if the JWT is valid
next.ServeHTTP(w, r)
})
}