feat(auth): implement role-based access control and user management features

This commit is contained in:
Nils-Johan Gynther
2026-04-18 09:34:22 +02:00
parent 20330f6410
commit c5ccef2313
22 changed files with 358 additions and 10 deletions
+3
View File
@@ -34,6 +34,9 @@ export default async function Navigation() {
<Link href="/recipes" style={linkStyle}>📖 Recept</Link>
<Link href="/baslager" style={linkStyle}>🏪 Baslager</Link>
<Link href="/admin/products" style={linkStyle}> Admin</Link>
{(session?.user as any)?.role === 'admin' && (
<Link href="/admin/users" style={linkStyle}>👥 Användare</Link>
)}
<Link href="/import" style={linkStyle}>📥 Importera</Link>
<Link href="/matplan" style={linkStyle}>📅 Matplan</Link>
<span style={{ flex: 1 }} />
@@ -0,0 +1,110 @@
'use client';
import { useState } from 'react';
type User = {
id: number;
username: string;
email: string;
firstName: string | null;
lastName: string | null;
role: string;
createdAt: string;
};
type Props = {
users: User[];
currentUserId: string;
};
export default function UserAdminClient({ users: initial, currentUserId }: Props) {
const [users, setUsers] = useState(initial);
const [loading, setLoading] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
async function toggleRole(user: User) {
const newRole = user.role === 'admin' ? 'user' : 'admin';
setLoading(user.id);
setError(null);
try {
const res = await fetch(`/api/admin-users/${user.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ role: newRole }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.message ?? 'Okänt fel');
}
const updated: User = await res.json();
setUsers((prev) => prev.map((u) => (u.id === updated.id ? { ...u, role: updated.role } : u)));
} catch (e: any) {
setError(e.message);
} finally {
setLoading(null);
}
}
return (
<>
{error && (
<div className="mb-4 p-3 bg-red-100 text-red-800 rounded">{error}</div>
)}
<table className="w-full border-collapse text-sm">
<thead>
<tr className="bg-gray-100 text-left">
<th className="p-2 border">Användarnamn</th>
<th className="p-2 border">E-post</th>
<th className="p-2 border">Namn</th>
<th className="p-2 border">Roll</th>
<th className="p-2 border">Skapad</th>
<th className="p-2 border">Åtgärd</th>
</tr>
</thead>
<tbody>
{users.map((user) => {
const isSelf = String(user.id) === currentUserId;
return (
<tr key={user.id} className="hover:bg-gray-50">
<td className="p-2 border font-medium">{user.username}</td>
<td className="p-2 border">{user.email}</td>
<td className="p-2 border">
{[user.firstName, user.lastName].filter(Boolean).join(' ') || '—'}
</td>
<td className="p-2 border">
<span
className={`px-2 py-0.5 rounded text-xs font-semibold ${
user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100 text-gray-700'
}`}
>
{user.role}
</span>
</td>
<td className="p-2 border text-gray-500">
{new Date(user.createdAt).toLocaleDateString('sv-SE')}
</td>
<td className="p-2 border">
{isSelf ? (
<span className="text-gray-400 text-xs">Du själv</span>
) : (
<button
onClick={() => toggleRole(user)}
disabled={loading === user.id}
className="px-3 py-1 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
{loading === user.id
? 'Sparar…'
: user.role === 'admin'
? 'Sätt som user'
: 'Sätt som admin'}
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { auth } from '../../../../auth';
import { redirect } from 'next/navigation';
import { fetchJson } from '../../../lib/api';
import UserAdminClient from './UserAdminClient';
type User = {
id: number;
username: string;
email: string;
firstName: string | null;
lastName: string | null;
role: string;
createdAt: string;
};
export default async function AdminUsersPage() {
const session = await auth();
if (!session || (session.user as any)?.role !== 'admin') {
redirect('/');
}
const users = await fetchJson<User[]>('/api/users');
return (
<main className="p-6 max-w-4xl mx-auto">
<h1 className="text-2xl font-bold mb-6">Användarhantering</h1>
<UserAdminClient users={users} currentUserId={session.user.id} />
</main>
);
}
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '../../../../../auth';
const API_BASE =
process.env.NEXT_PUBLIC_API_URL_INTERNAL ?? 'http://recipe-api:8080';
export async function PATCH(
request: NextRequest,
{ params }: { params: { id: string } },
) {
const session = await auth();
if (!session || (session.user as any)?.role !== 'admin') {
return NextResponse.json({ message: 'Förbjuden' }, { status: 403 });
}
const body = await request.json();
const res = await fetch(`${API_BASE}/api/users/${params.id}/role`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${session.accessToken}`,
},
body: JSON.stringify(body),
});
const data = await res.json();
return NextResponse.json(data, { status: res.status });
}
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from 'next/server';
import { auth } from '../../../../auth';
const API_BASE =
process.env.NEXT_PUBLIC_API_URL_INTERNAL ?? 'http://recipe-api:8080';
export async function GET() {
const session = await auth();
if (!session || (session.user as any)?.role !== 'admin') {
return NextResponse.json({ message: 'Förbjuden' }, { status: 403 });
}
const res = await fetch(`${API_BASE}/api/users`, {
headers: { Authorization: `Bearer ${session.accessToken}` },
cache: 'no-store',
});
const data = await res.json();
return NextResponse.json(data, { status: res.status });
}