feat: enhance user authentication and profile retrieval
- Updated GET handler in auth route to fetch user UUID from cookie using AuthService. - Improved error handling for unauthenticated and non-existent users. - Added team name retrieval for the user profile, with fallback handling. - Refactored AuthClient to return detailed user information including team details. - Enhanced navigation component to use a dropdown menu for user actions, improving UI/UX. - Implemented loading state in UserContext to manage user info fetching.
This commit is contained in:
36
app/account/page.tsx
Normal file
36
app/account/page.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { AuthService, userService, TeamsService } from "@/services";
|
||||
import { AccountForm } from "@/components/account/account-form";
|
||||
|
||||
export default async function AccountPage() {
|
||||
try {
|
||||
// Vérifier si l'utilisateur est connecté
|
||||
const userUuid = await AuthService.getUserUuidFromCookie();
|
||||
|
||||
if (!userUuid) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
// Récupérer le profil utilisateur
|
||||
const userProfile = await userService.getUserByUuid(userUuid);
|
||||
|
||||
if (!userProfile) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
// Charger les équipes pour la sélection
|
||||
const teams = await TeamsService.getTeams();
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h1 className="text-3xl font-bold mb-8">Mon compte</h1>
|
||||
<AccountForm initialProfile={userProfile} teams={teams} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error loading account page:", error);
|
||||
redirect("/login");
|
||||
}
|
||||
}
|
||||
46
app/api/auth/profile/route.ts
Normal file
46
app/api/auth/profile/route.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { AuthService, userService } from "@/services";
|
||||
|
||||
export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
// Vérifier si l'utilisateur est connecté
|
||||
const userUuid = await AuthService.getUserUuidFromCookie();
|
||||
|
||||
if (!userUuid) {
|
||||
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Récupérer les données de mise à jour
|
||||
const { firstName, lastName, teamId } = await request.json();
|
||||
|
||||
// Validation des données
|
||||
if (!firstName || !lastName || !teamId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Tous les champs sont requis" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Mettre à jour l'utilisateur
|
||||
await userService.updateUserByUuid(userUuid, {
|
||||
firstName,
|
||||
lastName,
|
||||
teamId,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: "Profil mis à jour avec succès",
|
||||
user: {
|
||||
firstName,
|
||||
lastName,
|
||||
teamId,
|
||||
},
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Profile update error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Erreur lors de la mise à jour du profil" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,52 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { userService } from "@/services/user-service";
|
||||
import { AuthService, COOKIE_NAME } from "@/services/auth-service";
|
||||
import { UserProfile } from "@/lib/types";
|
||||
import { AuthService, userService, TeamsService } from "@/services";
|
||||
|
||||
/**
|
||||
* GET /api/auth - Récupère l'utilisateur actuel depuis le cookie
|
||||
*/
|
||||
export async function GET() {
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const userUuid = cookieStore.get(COOKIE_NAME)?.value;
|
||||
// Récupérer l'UUID utilisateur depuis le cookie
|
||||
const userUuid = await AuthService.getUserUuidFromCookie();
|
||||
|
||||
if (!userUuid) {
|
||||
return NextResponse.json({ user: null }, { status: 200 });
|
||||
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Récupérer le profil utilisateur
|
||||
const userProfile = await userService.getUserByUuid(userUuid);
|
||||
|
||||
if (!userProfile) {
|
||||
// Cookie invalide, le supprimer
|
||||
const response = NextResponse.json({ user: null }, { status: 200 });
|
||||
response.cookies.set(COOKIE_NAME, "", { maxAge: 0 });
|
||||
return response;
|
||||
return NextResponse.json(
|
||||
{ error: "Utilisateur non trouvé" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ user: userProfile }, { status: 200 });
|
||||
// Récupérer le nom de l'équipe
|
||||
let teamName = "Équipe non définie";
|
||||
if (userProfile.teamId) {
|
||||
try {
|
||||
const team = await TeamsService.getTeamById(userProfile.teamId);
|
||||
if (team) {
|
||||
teamName = team.name;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error getting current user:", error);
|
||||
console.error("Failed to fetch team name:", error);
|
||||
}
|
||||
}
|
||||
|
||||
// Retourner les informations complètes de l'utilisateur
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
firstName: userProfile.firstName,
|
||||
lastName: userProfile.lastName,
|
||||
teamId: userProfile.teamId,
|
||||
teamName: teamName,
|
||||
uuid: userUuid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Auth GET error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to get current user" },
|
||||
{ error: "Erreur interne du serveur" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,9 +51,23 @@ export class AuthClient extends BaseHttpClient {
|
||||
/**
|
||||
* Récupère l'utilisateur actuel depuis le cookie
|
||||
*/
|
||||
async getCurrentUser(): Promise<UserProfile | null> {
|
||||
async getCurrentUser(): Promise<{
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
teamId: string;
|
||||
teamName: string;
|
||||
uuid: string;
|
||||
} | null> {
|
||||
try {
|
||||
const response = await this.get<{ user: UserProfile }>("/auth");
|
||||
const response = await this.get<{
|
||||
user: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
teamId: string;
|
||||
teamName: string;
|
||||
uuid: string;
|
||||
};
|
||||
}>("/auth");
|
||||
return response.user;
|
||||
} catch (error) {
|
||||
console.error("Failed to get current user:", error);
|
||||
|
||||
300
components/account/account-form.tsx
Normal file
300
components/account/account-form.tsx
Normal file
@@ -0,0 +1,300 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo, useRef, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { UserProfile, Team } from "@/lib/types";
|
||||
import { Search, Building2, ChevronDown, Check, Save, X } from "lucide-react";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
interface AccountFormProps {
|
||||
initialProfile: UserProfile;
|
||||
teams: Team[];
|
||||
}
|
||||
|
||||
export function AccountForm({ initialProfile, teams }: AccountFormProps) {
|
||||
const [firstName, setFirstName] = useState(initialProfile.firstName);
|
||||
const [lastName, setLastName] = useState(initialProfile.lastName);
|
||||
const [teamId, setTeamId] = useState(initialProfile.teamId);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [isTeamDropdownOpen, setIsTeamDropdownOpen] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const teamDropdownRef = useRef<HTMLDivElement>(null);
|
||||
const [dropdownPosition, setDropdownPosition] = useState<"below" | "above">(
|
||||
"below"
|
||||
);
|
||||
const { toast } = useToast();
|
||||
|
||||
const hasChanges =
|
||||
firstName !== initialProfile.firstName ||
|
||||
lastName !== initialProfile.lastName ||
|
||||
teamId !== initialProfile.teamId;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!hasChanges) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch("/api/auth/profile", {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
firstName,
|
||||
lastName,
|
||||
teamId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Erreur lors de la mise à jour");
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
toast({
|
||||
title: "Profil mis à jour",
|
||||
description:
|
||||
result.message || "Vos informations ont été modifiées avec succès.",
|
||||
});
|
||||
|
||||
setIsEditing(false);
|
||||
} catch (error: any) {
|
||||
console.error("Update failed:", error);
|
||||
toast({
|
||||
title: "Erreur de mise à jour",
|
||||
description: error.message || "Erreur lors de la mise à jour du profil",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setFirstName(initialProfile.firstName);
|
||||
setLastName(initialProfile.lastName);
|
||||
setTeamId(initialProfile.teamId);
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
// Group teams by direction and filter by search term
|
||||
const teamsByDirection = useMemo(() => {
|
||||
const filteredTeams = teams.filter(
|
||||
(team) =>
|
||||
team.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
team.direction.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
|
||||
return filteredTeams.reduce((acc, team) => {
|
||||
if (!acc[team.direction]) {
|
||||
acc[team.direction] = [];
|
||||
}
|
||||
acc[team.direction].push(team);
|
||||
return acc;
|
||||
}, {} as Record<string, Team[]>);
|
||||
}, [teams, searchTerm]);
|
||||
|
||||
// Calculate dropdown position when opening
|
||||
const handleDropdownToggle = () => {
|
||||
if (!isTeamDropdownOpen && teamDropdownRef.current) {
|
||||
const rect = teamDropdownRef.current.getBoundingClientRect();
|
||||
const viewportHeight = window.innerHeight;
|
||||
const spaceBelow = viewportHeight - rect.bottom;
|
||||
const spaceAbove = rect.top;
|
||||
const dropdownHeight = 300;
|
||||
|
||||
setDropdownPosition(
|
||||
spaceBelow >= dropdownHeight || spaceBelow > spaceAbove
|
||||
? "below"
|
||||
: "above"
|
||||
);
|
||||
}
|
||||
setIsTeamDropdownOpen(!isTeamDropdownOpen);
|
||||
};
|
||||
|
||||
// Close dropdown when clicking outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
teamDropdownRef.current &&
|
||||
!teamDropdownRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setIsTeamDropdownOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const selectedTeam = teams.find((team) => team.id === teamId);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Informations personnelles</CardTitle>
|
||||
<CardDescription>
|
||||
Modifiez vos informations personnelles. Vos identifiants de connexion
|
||||
(email et mot de passe) ne peuvent pas être modifiés ici.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="firstName">Prénom</Label>
|
||||
<Input
|
||||
id="firstName"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
placeholder="Votre prénom"
|
||||
disabled={!isEditing}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="lastName">Nom</Label>
|
||||
<Input
|
||||
id="lastName"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
placeholder="Votre nom"
|
||||
disabled={!isEditing}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="team">Équipe</Label>
|
||||
<div className="relative" ref={teamDropdownRef}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full justify-between"
|
||||
onClick={handleDropdownToggle}
|
||||
disabled={!isEditing}
|
||||
>
|
||||
<span
|
||||
className={
|
||||
selectedTeam ? "text-foreground" : "text-muted-foreground"
|
||||
}
|
||||
>
|
||||
{selectedTeam
|
||||
? selectedTeam.name
|
||||
: "Sélectionnez votre équipe"}
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{isTeamDropdownOpen && isEditing && (
|
||||
<div
|
||||
className={`absolute left-0 right-0 bg-background border border-border rounded-md shadow-lg z-50 max-h-[300px] overflow-y-auto ${
|
||||
dropdownPosition === "below"
|
||||
? "top-full mt-1"
|
||||
: "bottom-full mb-1"
|
||||
}`}
|
||||
>
|
||||
<div className="sticky top-0 bg-background border-b p-2">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Rechercher une équipe..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8 h-8 text-sm"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{Object.entries(teamsByDirection).map(
|
||||
([direction, directionTeams]) => (
|
||||
<div key={direction}>
|
||||
<div className="px-3 py-2 text-sm font-semibold text-muted-foreground bg-muted/30 border-b border-border flex items-center gap-2">
|
||||
<Building2 className="h-3 w-3" />
|
||||
{direction}
|
||||
</div>
|
||||
{directionTeams.map((team) => (
|
||||
<button
|
||||
key={team.id}
|
||||
type="button"
|
||||
className={`w-full px-3 py-2 text-left hover:bg-muted/50 flex items-center justify-between ${
|
||||
team.id === teamId ? "bg-muted" : ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
setTeamId(team.id);
|
||||
setIsTeamDropdownOpen(false);
|
||||
setSearchTerm("");
|
||||
}}
|
||||
>
|
||||
<span>{team.name}</span>
|
||||
{team.id === teamId && (
|
||||
<Check className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{Object.keys(teamsByDirection).length === 0 && (
|
||||
<div className="px-3 py-4 text-center text-sm text-muted-foreground">
|
||||
Aucune équipe trouvée pour "{searchTerm}"
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 justify-end">
|
||||
{!isEditing ? (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => setIsEditing(true)}
|
||||
className="bg-blue-500 hover:bg-blue-600"
|
||||
>
|
||||
Modifier
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleCancel}
|
||||
disabled={loading}
|
||||
>
|
||||
<X className="w-4 h-4 mr-2" />
|
||||
Annuler
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!hasChanges || loading}
|
||||
className="bg-blue-500 hover:bg-blue-600"
|
||||
>
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
{loading ? "Sauvegarde..." : "Sauvegarder"}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
1
components/account/index.ts
Normal file
1
components/account/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { AccountForm } from "./account-form";
|
||||
@@ -4,7 +4,19 @@ import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ThemeToggle } from "@/components/layout/theme-toggle";
|
||||
import { BarChart3, User, Settings, Building2 } from "lucide-react";
|
||||
import {
|
||||
BarChart3,
|
||||
User,
|
||||
Settings,
|
||||
Building2,
|
||||
ChevronDown,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
interface NavigationProps {
|
||||
userInfo?: {
|
||||
@@ -67,14 +79,16 @@ export function Navigation({ userInfo }: NavigationProps = {}) {
|
||||
|
||||
<div className="flex items-center space-x-4">
|
||||
{userInfo && (
|
||||
<Link
|
||||
href="/login"
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-muted/50 hover:bg-muted/70 transition-colors cursor-pointer"
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-muted/50 hover:bg-muted/70 transition-colors"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-full bg-primary/20 border border-primary/30 flex items-center justify-center">
|
||||
<User className="h-4 w-4 text-primary" />
|
||||
</div>
|
||||
<div className="hidden sm:block">
|
||||
<div className="hidden sm:block text-left">
|
||||
<p className="text-sm font-medium">
|
||||
{userInfo.firstName} {userInfo.lastName}
|
||||
</p>
|
||||
@@ -82,7 +96,24 @@ export function Navigation({ userInfo }: NavigationProps = {}) {
|
||||
{userInfo.teamName}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/account" className="flex items-center gap-2">
|
||||
<Settings className="h-4 w-4" />
|
||||
Mon compte
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/login" className="flex items-center gap-2">
|
||||
<User className="h-4 w-4" />
|
||||
Se déconnecter
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useState, ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
ReactNode,
|
||||
} from "react";
|
||||
import { authClient } from "@/clients";
|
||||
|
||||
interface UserInfo {
|
||||
firstName: string;
|
||||
@@ -11,15 +18,41 @@ interface UserInfo {
|
||||
interface UserContextType {
|
||||
userInfo: UserInfo | null;
|
||||
setUserInfo: (userInfo: UserInfo | null) => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
const UserContext = createContext<UserContextType | undefined>(undefined);
|
||||
|
||||
export function UserProvider({ children }: { children: ReactNode }) {
|
||||
const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUserInfo = async () => {
|
||||
try {
|
||||
// Récupérer les informations utilisateur depuis l'API
|
||||
const user = await authClient.getCurrentUser();
|
||||
if (user) {
|
||||
setUserInfo({
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
teamName: user.teamName || "Équipe non définie",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user info:", error);
|
||||
// En cas d'erreur, on considère que l'utilisateur n'est pas connecté
|
||||
setUserInfo(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchUserInfo();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ userInfo, setUserInfo }}>
|
||||
<UserContext.Provider value={{ userInfo, setUserInfo, loading }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user