package api import ( "encoding/json" "net/http" "os" "time" "github.com/golang-jwt/jwt/v5" "golang.org/x/crypto/bcrypt" ) func jwtSecret() []byte { if s := os.Getenv("JWT_SECRET"); s != "" { return []byte(s) } return []byte("dev-secret-change-me") } type jwtClaims struct { jwt.RegisteredClaims } func (h *Handler) Login(w http.ResponseWriter, r *http.Request) { var body struct { Username string `json:"username"` Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Username == "" || body.Password == "" { http.Error(w, "invalid body", http.StatusBadRequest) return } hash, err := h.store.GetUserHash(body.Username) if err != nil { http.Error(w, "invalid credentials", http.StatusUnauthorized) return } if bcrypt.CompareHashAndPassword([]byte(hash), []byte(body.Password)) != nil { http.Error(w, "invalid credentials", http.StatusUnauthorized) return } token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwtClaims{ RegisteredClaims: jwt.RegisteredClaims{ Subject: body.Username, ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), IssuedAt: jwt.NewNumericDate(time.Now()), }, }) signed, err := token.SignedString(jwtSecret()) if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } jsonOK(w, map[string]string{"token": signed}) } func (h *Handler) ChangePassword(w http.ResponseWriter, r *http.Request) { claims, ok := claimsFromContext(r) if !ok { http.Error(w, "unauthorized", http.StatusUnauthorized) return } var body struct { CurrentPassword string `json:"current_password"` NewPassword string `json:"new_password"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.NewPassword == "" { http.Error(w, "invalid body", http.StatusBadRequest) return } hash, err := h.store.GetUserHash(claims.Subject) if err != nil { http.Error(w, "user not found", http.StatusNotFound) return } if bcrypt.CompareHashAndPassword([]byte(hash), []byte(body.CurrentPassword)) != nil { http.Error(w, "mot de passe actuel incorrect", http.StatusUnauthorized) return } newHash, err := bcrypt.GenerateFromPassword([]byte(body.NewPassword), bcrypt.DefaultCost) if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } if err := h.store.UpsertUser(claims.Subject, string(newHash)); err != nil { http.Error(w, "store error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } func requireJWT(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw := extractToken(r) if raw == "" { http.Error(w, "unauthorized", http.StatusUnauthorized) return } t, err := jwt.ParseWithClaims(raw, &jwtClaims{}, func(t *jwt.Token) (any, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, jwt.ErrSignatureInvalid } return jwtSecret(), nil }) if err != nil || !t.Valid { http.Error(w, "unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r.WithContext( contextWithClaims(r.Context(), t.Claims.(*jwtClaims)), )) }) } func extractToken(r *http.Request) string { if auth := r.Header.Get("Authorization"); len(auth) > 7 && auth[:7] == "Bearer " { return auth[7:] } return r.URL.Query().Get("token") }