dssdds
This commit is contained in:
parent
e5f043672c
commit
226cbe06cf
@ -20,8 +20,6 @@ func main() {
|
|||||||
// 3. Routes non protégées : on les monte sur le routeur principal
|
// 3. Routes non protégées : on les monte sur le routeur principal
|
||||||
routes.RoutesPublic(r, bd)
|
routes.RoutesPublic(r, bd)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 4. Créer un sous-routeur pour les routes protégées
|
// 4. Créer un sous-routeur pour les routes protégées
|
||||||
protected := r.PathPrefix("/").Subrouter()
|
protected := r.PathPrefix("/").Subrouter()
|
||||||
|
|
||||||
@ -29,7 +27,9 @@ func main() {
|
|||||||
protected.Use(middleware.AuthMiddleware)
|
protected.Use(middleware.AuthMiddleware)
|
||||||
// 6. Enregistrer les routes protégées sur ce sous-routeur
|
// 6. Enregistrer les routes protégées sur ce sous-routeur
|
||||||
routes.RoutesProtected(protected, bd)
|
routes.RoutesProtected(protected, bd)
|
||||||
|
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
|
})
|
||||||
// 7. Lancer le serveur sur le port 4000
|
// 7. Lancer le serveur sur le port 4000
|
||||||
log.Fatal(http.ListenAndServe(":3003", r))
|
log.Fatal(http.ListenAndServe(":3003", r))
|
||||||
}
|
}
|
||||||
@ -15,23 +15,29 @@ import (
|
|||||||
|
|
||||||
var secretKey = []byte("secret-key")
|
var secretKey = []byte("secret-key")
|
||||||
|
|
||||||
|
// AuthMiddleware protège les routes via JWT et redirige vers /login si non authentifié
|
||||||
func AuthMiddleware(next http.Handler) http.Handler {
|
func AuthMiddleware(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx, ok := RedirectToLoginIfUnauthenticated(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
||||||
var tokenString string
|
var tokenString string
|
||||||
|
|
||||||
// 1. Vérifie Authorization: Bearer ...
|
|
||||||
if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") {
|
if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") {
|
||||||
tokenString = strings.TrimPrefix(authHeader, "Bearer ")
|
tokenString = strings.TrimPrefix(authHeader, "Bearer ")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Vérifie le cookie si pas de header
|
|
||||||
if tokenString == "" {
|
if tokenString == "" {
|
||||||
if cookie, err := r.Cookie("token"); err == nil {
|
if cookie, err := r.Cookie("token"); err == nil {
|
||||||
tokenString = cookie.Value
|
tokenString = cookie.Value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Vérifie le body JSON uniquement si POST ou PUT
|
|
||||||
if tokenString == "" && r.Method == http.MethodPost || r.Method == http.MethodPut {
|
if tokenString == "" && r.Method == http.MethodPost || r.Method == http.MethodPut {
|
||||||
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
||||||
bodyCopy, _ := io.ReadAll(r.Body)
|
bodyCopy, _ := io.ReadAll(r.Body)
|
||||||
@ -39,62 +45,41 @@ func AuthMiddleware(next http.Handler) http.Handler {
|
|||||||
if err := json.Unmarshal(bodyCopy, &bodyMap); err == nil {
|
if err := json.Unmarshal(bodyCopy, &bodyMap); err == nil {
|
||||||
if val, ok := bodyMap["token"].(string); ok {
|
if val, ok := bodyMap["token"].(string); ok {
|
||||||
tokenString = val
|
tokenString = val
|
||||||
// restaure le body
|
|
||||||
r.Body = io.NopCloser(bytes.NewReader(bodyCopy))
|
r.Body = io.NopCloser(bytes.NewReader(bodyCopy))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if tokenString == "" {
|
if tokenString == "" {
|
||||||
http.Error(w, "Token manquant", http.StatusUnauthorized)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ Vérifie et parse le token
|
|
||||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
return nil, fmt.Errorf("méthode signature invalide")
|
return nil, fmt.Errorf("méthode signature invalide")
|
||||||
}
|
}
|
||||||
return secretKey, nil
|
return secretKey, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil || !token.Valid {
|
if err != nil || !token.Valid {
|
||||||
http.Error(w, "Token invalide", http.StatusUnauthorized)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
claims, ok := token.Claims.(jwt.MapClaims)
|
claims, ok := token.Claims.(jwt.MapClaims)
|
||||||
if !ok {
|
if !ok {
|
||||||
http.Error(w, "Claims invalides", http.StatusUnauthorized)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// vérifie l’expiration
|
|
||||||
if exp, ok := claims["exp"].(float64); ok {
|
if exp, ok := claims["exp"].(float64); ok {
|
||||||
if time.Now().Unix() > int64(exp) {
|
if time.Now().Unix() > int64(exp) {
|
||||||
http.Error(w, "Token expiré", http.StatusUnauthorized)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// récupère l’identifiant
|
|
||||||
ssoid, ok := claims["username"].(string)
|
ssoid, ok := claims["username"].(string)
|
||||||
if !ok {
|
if !ok || ssoid == "" {
|
||||||
http.Error(w, "SSOID manquant", http.StatusUnauthorized)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// injection dans le contexte
|
|
||||||
ctx := context.WithValue(r.Context(), "ssoid", ssoid)
|
ctx := context.WithValue(r.Context(), "ssoid", ssoid)
|
||||||
next.ServeHTTP(w, r.WithContext(ctx))
|
return ctx, true
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// helper pour remarshal le JSON quand il est relu après parse
|
|
||||||
func mustMarshal(data map[string]interface{}) []byte {
|
|
||||||
b, _ := json.Marshal(data)
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
@ -5,6 +5,7 @@ import (
|
|||||||
"cangui/whatsapp/backend/renders"
|
"cangui/whatsapp/backend/renders"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@ -17,7 +18,27 @@ func RoutesPublic(r *mux.Router, db *gorm.DB) {
|
|||||||
r.PathPrefix("/frontend/assets/").Handler(
|
r.PathPrefix("/frontend/assets/").Handler(
|
||||||
http.StripPrefix("/frontend/assets/", http.FileServer(http.Dir(staticDir))),
|
http.StripPrefix("/frontend/assets/", http.FileServer(http.Dir(staticDir))),
|
||||||
)
|
)
|
||||||
|
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Tente de lire le cookie
|
||||||
|
cookie, err := r.Cookie("token")
|
||||||
|
if err != nil || cookie.Value == "" {
|
||||||
|
// Redirige vers login si pas de cookie
|
||||||
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si cookie présent, tente de parser
|
||||||
|
token, err := jwt.Parse(cookie.Value, func(token *jwt.Token) (interface{}, error) {
|
||||||
|
return []byte("secret-key"), nil
|
||||||
|
})
|
||||||
|
if err != nil || !token.Valid {
|
||||||
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sinon on va vers le dashboard
|
||||||
|
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
|
||||||
|
})
|
||||||
// Page de login
|
// Page de login
|
||||||
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")
|
||||||
|
|||||||
@ -41,8 +41,11 @@
|
|||||||
"language": "fr",
|
"language": "fr",
|
||||||
"param1": "Jean",
|
"param1": "Jean",
|
||||||
"param2": "commande #1234",
|
"param2": "commande #1234",
|
||||||
|
"param3": "optionnel",
|
||||||
|
"param4": "optionnel",
|
||||||
|
"param5": "optionnel",
|
||||||
"token": "votre_jwt_token"
|
"token": "votre_jwt_token"
|
||||||
}</code></pre>
|
}</code></pre>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="box">
|
<div class="box">
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user