Ajout authentification JWT complète (app 100% protégée)
Backend: - Nouveau module auth.py avec JWT et password handling - Endpoint /api/auth/login (public) - Endpoint /api/auth/me (protégé) - TOUS les endpoints API protégés par require_auth - Variables env: ADMIN_EMAIL, ADMIN_PASSWORD, JWT_SECRET_KEY - Dependencies: python-jose, passlib Frontend: - Page de login (/login) - AuthGuard component pour redirection automatique - Axios interceptor: ajoute JWT token à chaque requête - Gestion erreur 401: redirect automatique vers /login - Bouton logout dans header - Token stocké dans localStorage Configuration: - .env.example mis à jour avec variables auth - Credentials admin configurables via env Sécurité: - Aucun endpoint public (sauf /api/auth/login et /health) - JWT expiration configurable (24h par défaut) - Password en clair dans env (à améliorer avec hash en prod) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,7 @@ import type { Metadata } from "next"
|
||||
import { Inter } from "next/font/google"
|
||||
import "./globals.css"
|
||||
import { QueryProvider } from "@/components/providers/QueryProvider"
|
||||
import AuthGuard from "@/components/AuthGuard"
|
||||
import Script from "next/script"
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] })
|
||||
@@ -23,7 +24,9 @@ export default function RootLayout({
|
||||
</head>
|
||||
<body className={inter.className}>
|
||||
<QueryProvider>
|
||||
{children}
|
||||
<AuthGuard>
|
||||
{children}
|
||||
</AuthGuard>
|
||||
</QueryProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
124
frontend/app/login/page.tsx
Normal file
124
frontend/app/login/page.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { getApiUrl } from "@/lib/api"
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter()
|
||||
const [email, setEmail] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [error, setError] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${getApiUrl()}/api/auth/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ email, password }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json()
|
||||
throw new Error(data.detail || "Login failed")
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
// Store token in localStorage
|
||||
localStorage.setItem("access_token", data.access_token)
|
||||
localStorage.setItem("user", JSON.stringify(data.user))
|
||||
|
||||
// Redirect to home
|
||||
router.push("/")
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Login failed")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900">
|
||||
<div className="max-w-md w-full mx-4">
|
||||
<div className="bg-white rounded-lg shadow-2xl p-8">
|
||||
{/* Logo/Title */}
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">
|
||||
Audio Classifier
|
||||
</h1>
|
||||
<p className="text-gray-600">Sign in to continue</p>
|
||||
</div>
|
||||
|
||||
{/* Error message */}
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Login form */}
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div>
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-gray-700 mb-1"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder="admin@example.com"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-gray-700 mb-1"
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder="••••••••"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors disabled:bg-blue-400 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isLoading ? "Signing in..." : "Sign in"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="text-center text-gray-400 text-sm mt-6">
|
||||
Audio Classifier v1.0.0
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useMemo } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { getTracks, getApiUrl } from "@/lib/api"
|
||||
import { logout, getUser } from "@/lib/auth"
|
||||
import type { FilterParams, Track } from "@/lib/types"
|
||||
import FilterPanel from "@/components/FilterPanel"
|
||||
import AudioPlayer from "@/components/AudioPlayer"
|
||||
@@ -160,6 +161,18 @@ export default function Home() {
|
||||
{tracksData?.total || 0} piste{(tracksData?.total || 0) > 1 ? 's' : ''}
|
||||
</div>
|
||||
|
||||
{/* Logout button */}
|
||||
<button
|
||||
onClick={logout}
|
||||
className="px-3 py-2 text-sm text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg transition-colors flex items-center gap-2"
|
||||
title="Déconnexion"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
|
||||
</svg>
|
||||
Logout
|
||||
</button>
|
||||
|
||||
{/* Rescan button */}
|
||||
<button
|
||||
onClick={handleRescan}
|
||||
|
||||
37
frontend/components/AuthGuard.tsx
Normal file
37
frontend/components/AuthGuard.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter, usePathname } from "next/navigation"
|
||||
import { isAuthenticated } from "@/lib/auth"
|
||||
|
||||
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const [isChecking, setIsChecking] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
// Skip auth check for login page
|
||||
if (pathname === "/login") {
|
||||
setIsChecking(false)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if user is authenticated
|
||||
if (!isAuthenticated()) {
|
||||
router.push("/login")
|
||||
} else {
|
||||
setIsChecking(false)
|
||||
}
|
||||
}, [pathname, router])
|
||||
|
||||
// Show loading while checking auth
|
||||
if (isChecking && pathname !== "/login") {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-900">
|
||||
<div className="text-white">Loading...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
@@ -24,12 +24,38 @@ export function getApiUrl(): string {
|
||||
|
||||
// Create axios instance dynamically to use runtime config
|
||||
function getApiClient() {
|
||||
return axios.create({
|
||||
const client = axios.create({
|
||||
baseURL: getApiUrl(),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
// Add JWT token to requests if available
|
||||
client.interceptors.request.use((config) => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const token = localStorage.getItem('access_token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
// Handle 401 errors (redirect to login)
|
||||
client.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401 && typeof window !== 'undefined') {
|
||||
localStorage.removeItem('access_token')
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
// Tracks
|
||||
|
||||
34
frontend/lib/auth.ts
Normal file
34
frontend/lib/auth.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Authentication utilities
|
||||
*/
|
||||
|
||||
export function getToken(): string | null {
|
||||
if (typeof window === "undefined") return null
|
||||
return localStorage.getItem("access_token")
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
localStorage.setItem("access_token", token)
|
||||
}
|
||||
|
||||
export function removeToken(): void {
|
||||
localStorage.removeItem("access_token")
|
||||
localStorage.removeItem("user")
|
||||
}
|
||||
|
||||
export function getUser(): any | null {
|
||||
if (typeof window === "undefined") return null
|
||||
const user = localStorage.getItem("user")
|
||||
return user ? JSON.parse(user) : null
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return getToken() !== null
|
||||
}
|
||||
|
||||
export function logout(): void {
|
||||
removeToken()
|
||||
if (typeof window !== "undefined") {
|
||||
window.location.href = "/login"
|
||||
}
|
||||
}
|
||||
20
frontend/middleware.ts
Normal file
20
frontend/middleware.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
// Middleware runs on server, can't access localStorage
|
||||
// Auth check will be done client-side in layout.tsx
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except for the ones starting with:
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
*/
|
||||
'/((?!_next/static|_next/image|favicon.ico).*)',
|
||||
],
|
||||
}
|
||||
Reference in New Issue
Block a user