This commit is contained in:
cangui 2025-05-11 10:45:42 +02:00
parent cd20579501
commit 22170c192a
3 changed files with 74 additions and 0 deletions

View File

@ -93,6 +93,44 @@ func SSOLoginHandler(db *gorm.DB) http.HandlerFunc {
http.Redirect(w, r, "/dashboard", http.StatusSeeOther) http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
} }
} }
func SSOLoginPostHandler(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var body struct {
Code string `json:"code"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Code == "" {
http.Error(w, "Code SSO requis", http.StatusBadRequest)
return
}
var user models.User
if result := db.Where("sso_id = ?", body.Code).First(&user); result.Error != nil || !user.IsActive {
http.Error(w, "SSO invalide ou utilisateur inactif", http.StatusUnauthorized)
return
}
token, err := jwt.CreateToken(user.SSOID)
if err != nil {
http.Error(w, "Erreur génération token", http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: token,
Path: "/",
HttpOnly: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Connexion réussie",
"token": token,
})
}
}
var MessageTypeCreditCost = map[string]uint{ var MessageTypeCreditCost = map[string]uint{

View File

@ -25,6 +25,39 @@ func AuthMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(w, r.WithContext(ctx)) next.ServeHTTP(w, r.WithContext(ctx))
}) })
} }
func AuthWithTokenHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token == "" {
http.Error(w, "Token JWT manquant", http.StatusBadRequest)
return
}
// Facultatif : tu peux valider ici que le token est correct avant de le poser
_, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("méthode de signature invalide")
}
return []byte("secret-key"), nil
})
if err != nil {
http.Error(w, "Token invalide", http.StatusUnauthorized)
return
}
// ✅ Pose le token comme cookie
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: token,
Path: "/",
HttpOnly: true,
Secure: false, // true en prod
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}
}
// RedirectToLoginIfUnauthenticated vérifie le JWT et injecte ssoid dans le contexte, sinon redirige vers /login // RedirectToLoginIfUnauthenticated vérifie le JWT et injecte ssoid dans le contexte, sinon redirige vers /login
func RedirectToLoginIfUnauthenticated(w http.ResponseWriter, r *http.Request) (context.Context, bool) { func RedirectToLoginIfUnauthenticated(w http.ResponseWriter, r *http.Request) (context.Context, bool) {

View File

@ -2,6 +2,7 @@ package routes
import ( import (
"cangui/whatsapp/backend/handlers" "cangui/whatsapp/backend/handlers"
"cangui/whatsapp/backend/middleware"
"cangui/whatsapp/backend/renders" "cangui/whatsapp/backend/renders"
"net/http" "net/http"
@ -40,6 +41,8 @@ func RoutesPublic(r *mux.Router, db *gorm.DB) {
http.Redirect(w, r, "/dashboard", http.StatusSeeOther) http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}) })
// Page de login // Page de login
r.HandleFunc("/auth/with-token", middleware.AuthWithTokenHandler()).Methods("GET")
r.HandleFunc("/api/sso/login", handlers.SSOLoginPostHandler(db)).Methods("POST")
r.HandleFunc("/login", renders.Login) r.HandleFunc("/login", renders.Login)
r.HandleFunc("/api/whatsapp/webhook", handlers.WebhookVerifyHandler()).Methods("GET") r.HandleFunc("/api/whatsapp/webhook", handlers.WebhookVerifyHandler()).Methods("GET")
r.HandleFunc("/api/whatsapp/webhook", handlers.WebhookReceiveHandler(db)).Methods("POST") r.HandleFunc("/api/whatsapp/webhook", handlers.WebhookReceiveHandler(db)).Methods("POST")