This commit is contained in:
2025-11-11 02:33:05 +01:00
parent eb2c8fea64
commit 17a671a417
21 changed files with 560 additions and 73 deletions

72
network/http/web/auth.go Normal file
View File

@@ -0,0 +1,72 @@
package web
import (
"go_oxspeak_server/models"
"go_oxspeak_server/network/http/handler"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"gorm.io/gorm"
)
type AuthHandler struct {
*handler.Handler
}
func NewAuthHandler(h *handler.Handler) *AuthHandler {
return &AuthHandler{h}
}
func (h *AuthHandler) RegisterRoutes(rg *gin.RouterGroup) {
channel := rg.Group("/channel")
channel.GET("/login/", h.authenticate)
}
type AuthRequest struct {
PublicKey string `json:"pub_key" binding:"required"`
}
type AuthResponse struct {
JWT string `json:"JWT"`
}
func (h *AuthHandler) authenticate(c *gin.Context) {
var req AuthRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var user models.User
result := h.DB.Where("public_key = ?", req.PublicKey).First(&user)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid public key"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
}
// Generate token
claims := jwt.MapClaims{
"user_id": user.ID,
"expiration_date": time.Now().Add(time.Hour * 72).Unix(),
"creation_date": time.Now().Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
// TODO: Remplacer par votre clé secrète (utiliser une variable d'environnement)
secretKey := []byte("votre-cle-secrete-a-changer")
jwtString, err := token.SignedString(secretKey)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur lors de la génération du JWT"})
return
}
c.JSON(http.StatusOK, AuthResponse{JWT: jwtString})
}