Admin: widacznosc konta usera - lastLoginAt + IP w logach logowania + kafel historii konta (kto edytowal dane, historia kar) ; GET /admin/users/:id/activity
This commit is contained in:
@@ -36,6 +36,8 @@ export interface User {
|
||||
status: 'ACTIVE' | 'SUSPENDED' | 'BANNED';
|
||||
suspensionUntil: string | null;
|
||||
restrictionReason: string | null;
|
||||
/** Data ostatniego udanego logowania (login, nie odświeżanie tokenu); null = nigdy. */
|
||||
lastLoginAt?: string | null;
|
||||
createdAt: string;
|
||||
memberships?: { gymId: string; roles: GymRole[]; gym: Gym }[];
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"userId": "user",
|
||||
"date": "date",
|
||||
"client": "client",
|
||||
"ip": "IP address",
|
||||
"isAdmin": "admin",
|
||||
"suspensionUntil": "suspended until",
|
||||
"restrictionReason": "restriction reason",
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
"statKillstreak": "Killstreak",
|
||||
"statVolume7d": "7-day volume",
|
||||
"statSessions": "Sessions",
|
||||
"statLastLogin": "Last login",
|
||||
"accountHistory": "Account history",
|
||||
"noActivity": "No account events.",
|
||||
"byActor": "by {{actor}}",
|
||||
"lastLoginWord": "login: {{date}}",
|
||||
"ageValue": "{{age}} years",
|
||||
"personalInfo": "Personal details",
|
||||
"bodyParams": "Body parameters",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"userId": "użytkownik",
|
||||
"date": "data",
|
||||
"client": "klient",
|
||||
"ip": "adres IP",
|
||||
"isAdmin": "admin",
|
||||
"suspensionUntil": "zawieszenie do",
|
||||
"restrictionReason": "powód kary",
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
"statKillstreak": "Killstreak",
|
||||
"statVolume7d": "Objętość 7 dni",
|
||||
"statSessions": "Sesje",
|
||||
"statLastLogin": "Ostatnie logowanie",
|
||||
"accountHistory": "Historia konta",
|
||||
"noActivity": "Brak zdarzeń konta.",
|
||||
"byActor": "przez {{actor}}",
|
||||
"lastLoginWord": "log: {{date}}",
|
||||
"ageValue": "{{age}} lat",
|
||||
"personalInfo": "Dane osobowe",
|
||||
"bodyParams": "Parametry ciała",
|
||||
|
||||
@@ -93,7 +93,7 @@ export function actionLabel(action: string) {
|
||||
return t(`actions.${action}`, { defaultValue: action });
|
||||
}
|
||||
|
||||
function actionColor(action: string): BadgeColor {
|
||||
export function actionColor(action: string): BadgeColor {
|
||||
if (action.startsWith('plan.')) return 'blue';
|
||||
if (action.startsWith('session.')) return 'green';
|
||||
if (action.startsWith('gym.')) return 'gray';
|
||||
@@ -108,7 +108,7 @@ export function formatLogDate(iso: string) {
|
||||
return fmtDateTime(iso);
|
||||
}
|
||||
|
||||
function actorName(log: ActivityLog) {
|
||||
export function actorName(log: ActivityLog) {
|
||||
const { firstName, lastName, email } = log.actor;
|
||||
return [firstName, lastName].filter(Boolean).join(' ') || email;
|
||||
}
|
||||
@@ -144,7 +144,7 @@ function formatDetailValue(log: ActivityLog, key: string, value: unknown): strin
|
||||
}
|
||||
|
||||
/** Szczegóły wpisu jako naturalny tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */
|
||||
function detailsText(log: ActivityLog) {
|
||||
export function detailsText(log: ActivityLog) {
|
||||
const d = log.details;
|
||||
if (!d) return null;
|
||||
const parts = Object.entries(d)
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
FileText,
|
||||
Flame,
|
||||
History,
|
||||
LogIn,
|
||||
Pause,
|
||||
Pencil,
|
||||
Scale,
|
||||
@@ -18,12 +19,23 @@ import {
|
||||
} from 'lucide-react';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { api } from '../../api/client';
|
||||
import { BackButton, Badge, Card, ConfirmDialog, ErrorText, Loading } from '../../components/ui';
|
||||
import {
|
||||
BackButton,
|
||||
Badge,
|
||||
Card,
|
||||
ConfirmDialog,
|
||||
ErrorText,
|
||||
Loading,
|
||||
Muted,
|
||||
SectionHeader,
|
||||
} from '../../components/ui';
|
||||
import { Avatar } from '../../components/Avatar';
|
||||
import { displayName, fmtDate, fmtDateTime, fmtVolume } from '../../lib/format';
|
||||
import { actionColor, actionLabel, actorName, detailsText, formatLogDate } from '../Logs';
|
||||
import { UserRestrictionModal } from './UserRestrictionModal';
|
||||
import {
|
||||
useAdminUser,
|
||||
useUserActivity,
|
||||
useUserBodyParameters,
|
||||
useUserClaims,
|
||||
useUserExerciseProgress,
|
||||
@@ -117,6 +129,7 @@ export default function UserDetail() {
|
||||
const { data: ks } = useUserKillstreak(id);
|
||||
const { data: claimsData } = useUserClaims(id);
|
||||
const { data: progressData } = useUserExerciseProgress(id);
|
||||
const { data: activityData } = useUserActivity(id);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [removeError, setRemoveError] = useState('');
|
||||
@@ -213,6 +226,7 @@ export default function UserDetail() {
|
||||
: t('resolvedClaims', { count: claims.length });
|
||||
|
||||
const progressCount = (progressData?.exercises ?? []).length;
|
||||
const activityLogs = activityData?.logs ?? [];
|
||||
const progressSummary =
|
||||
progressCount > 0
|
||||
? `${progressCount} ${
|
||||
@@ -276,6 +290,11 @@ export default function UserDetail() {
|
||||
label={t('statSessions')}
|
||||
value={sessions.length > 0 ? String(sessions.length) : '—'}
|
||||
/>
|
||||
<MiniStat
|
||||
icon={LogIn}
|
||||
label={t('statLastLogin')}
|
||||
value={user.lastLoginAt ? fmtDateTime(user.lastLoginAt) : '—'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sekcje: wiersze-listy; mobile kolumna (divide-y), sm+ siatka 2 kol. */}
|
||||
@@ -331,6 +350,30 @@ export default function UserDetail() {
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Historia konta: logi audytu NA użytkowniku (logowania z IP, kto edytował dane, kary/bany) */}
|
||||
<Card className="mt-4">
|
||||
<SectionHeader title={t('accountHistory')} />
|
||||
{activityLogs.length === 0 ? (
|
||||
<Muted>{t('noActivity')}</Muted>
|
||||
) : (
|
||||
<div className="divide-y divide-line">
|
||||
{activityLogs.map((log) => {
|
||||
const details = detailsText(log);
|
||||
return (
|
||||
<div key={log.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5">
|
||||
<span className="font-display text-dim text-[0.8rem] tabular-nums">
|
||||
{formatLogDate(log.createdAt)}
|
||||
</span>
|
||||
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
|
||||
<span className="text-[0.875rem]">{t('byActor', { actor: actorName(log) })}</span>
|
||||
{details && <span className="text-[0.8rem] text-dim">{details}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmOpen}
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Badge, Card, EmptyState, ErrorText, ListRow, Loading } from '../../comp
|
||||
import { Avatar } from '../../components/Avatar';
|
||||
import { useListSearch } from '../../store/list-search';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { fmtDate } from '../../lib/format';
|
||||
import { userDisplayName } from './UserDetail';
|
||||
|
||||
export default function UsersList() {
|
||||
@@ -66,6 +67,9 @@ export default function UsersList() {
|
||||
<>
|
||||
{u.email}
|
||||
{u.age != null ? ` · ${t('ageWord', { age: u.age })}` : ''}
|
||||
{u.lastLoginAt
|
||||
? ` · ${t('lastLoginWord', { date: fmtDate(u.lastLoginAt) })}`
|
||||
: ''}
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '../../api/client';
|
||||
import type {
|
||||
ActivityLogPage,
|
||||
CircumferenceSeries,
|
||||
ExerciseProgress,
|
||||
Gym,
|
||||
@@ -85,3 +86,12 @@ export function useUserClaims(id?: string) {
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
/** Historia konta: logi audytu wykonane NA użytkowniku (logowania/IP, edycje, kary, role). */
|
||||
export function useUserActivity(id?: string, limit = 10) {
|
||||
return useQuery({
|
||||
queryKey: ['user-activity', id, limit],
|
||||
queryFn: () => api<ActivityLogPage>(`/admin/users/${id}/activity?limit=${limit}`),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
expect(await screen.findByText('Zablokowane')).toBeInTheDocument();
|
||||
@@ -123,6 +124,7 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
expect(await screen.findByText(/Zawieszone do/)).toBeInTheDocument();
|
||||
@@ -142,6 +144,7 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [{ id: 'e1' }] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
|
||||
@@ -186,12 +189,74 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
const row = await screen.findByRole('link', { name: /Członkostwa w siłowniach/ });
|
||||
expect(row).toHaveTextContent('Gym A');
|
||||
expect(row).toHaveTextContent('OWNER, TRAINER');
|
||||
});
|
||||
|
||||
it('kafel historii konta: aktor, akcja, IP logowania i kara z powodem', async () => {
|
||||
const logs = [
|
||||
{
|
||||
id: 'l1',
|
||||
action: 'user.status.changed',
|
||||
entityType: 'user',
|
||||
entityId: 'u1',
|
||||
details: { actorId: 'a1', status: 'BANNED', restrictionReason: 'Sprzedaż kont' },
|
||||
createdAt: '2026-10-20T08:00:00.000Z',
|
||||
actor: { id: 'a1', email: 'ada@test.local', firstName: 'Ada', lastName: 'Admin' },
|
||||
},
|
||||
{
|
||||
id: 'l2',
|
||||
action: 'user.logged_in',
|
||||
entityType: 'user',
|
||||
entityId: 'u1',
|
||||
details: { actorId: 'u1', client: 'app', ip: '203.0.113.9' },
|
||||
createdAt: '2026-10-19T18:30:00.000Z',
|
||||
actor: { id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' },
|
||||
},
|
||||
];
|
||||
mockFetchRoutes([
|
||||
['/admin/users', () => ({ users: [{ ...U1, lastLoginAt: '2026-10-19T18:30:00.000Z' }] })],
|
||||
['/killstreak', () => ({ killstreak: 0 })],
|
||||
['/body-parameters', () => ({ weight: [], circumferences: [] })],
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs, total: logs.length })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
|
||||
// mini-statystyka ostatniego logowania (ten sam dzień występuje też w wierszu logowania)
|
||||
expect(await screen.findByText('Ostatnie logowanie')).toBeInTheDocument();
|
||||
expect(screen.getAllByText(/19\.10\.2026/).length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// historia: kto (aktor-admin) wykonał akcję + szczegóły kary
|
||||
expect(screen.getByText('Historia konta')).toBeInTheDocument();
|
||||
expect(screen.getByText('przez Ada Admin')).toBeInTheDocument();
|
||||
expect(screen.getByText('Zmiana statusu konta')).toBeInTheDocument();
|
||||
expect(screen.getByText(/powód kary: Sprzedaż kont/)).toBeInTheDocument();
|
||||
// logowanie z adresem IP
|
||||
expect(screen.getByText('Logowanie')).toBeInTheDocument();
|
||||
expect(screen.getByText(/adres IP: 203\.0\.113\.9/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('kafel historii konta: stan pusty', async () => {
|
||||
mockFetchRoutes([
|
||||
['/admin/users', () => ({ users: [U1] })],
|
||||
['/killstreak', () => ({ killstreak: 0 })],
|
||||
['/body-parameters', () => ({ weight: [], circumferences: [] })],
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
expect(await screen.findByText('Historia konta')).toBeInTheDocument();
|
||||
expect(screen.getByText('Brak zdarzeń konta.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// tytuł sekcji → memberships | claims | info | body-parameters | history | progress
|
||||
|
||||
@@ -328,6 +328,50 @@ test('podstrony usera: topbar = Profil [nazwa], nazwa sekcji dopiero w treści (
|
||||
await expect(page.getByRole('heading', { name: 'Historia treningów' })).toHaveCount(1);
|
||||
});
|
||||
|
||||
test('historia konta: ostatnie logowanie, IP i kara z aktorem-adminem', async ({ page }) => {
|
||||
mockApi(page, {
|
||||
gyms: { gyms: [TEST_GYM] },
|
||||
users: {
|
||||
users: [{ ...TEST_USER, lastLoginAt: '2026-10-19T18:30:00.000Z' }],
|
||||
},
|
||||
activity: {
|
||||
logs: [
|
||||
{
|
||||
id: 'a-1',
|
||||
action: 'user.status.changed',
|
||||
entityType: 'user',
|
||||
entityId: 'user-1',
|
||||
details: { actorId: 'admin-1', status: 'BANNED', restrictionReason: 'Sprzedaż kont' },
|
||||
createdAt: '2026-10-20T08:00:00.000Z',
|
||||
actor: { id: 'admin-1', email: 'admin@fitos.pl', firstName: 'Admin', lastName: 'FitOS' },
|
||||
},
|
||||
{
|
||||
id: 'a-2',
|
||||
action: 'user.logged_in',
|
||||
entityType: 'user',
|
||||
entityId: 'user-1',
|
||||
details: { actorId: 'user-1', client: 'app', ip: '203.0.113.9' },
|
||||
createdAt: '2026-10-19T18:30:00.000Z',
|
||||
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
},
|
||||
});
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Użytkownicy' }).click();
|
||||
// lista: data ostatniego logowania przy wierszu użytkownika
|
||||
await expect(page.getByText(/log: 19\.10\.2026/)).toBeVisible();
|
||||
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
|
||||
|
||||
// mini-statystyka + kafel historii
|
||||
await expect(page.getByText('Ostatnie logowanie')).toBeVisible();
|
||||
await expect(page.getByText('Historia konta')).toBeVisible();
|
||||
await expect(page.getByText('przez Admin FitOS')).toBeVisible();
|
||||
await expect(page.getByText(/powód kary: Sprzedaż kont/)).toBeVisible();
|
||||
await expect(page.getByText(/adres IP: 203\.0\.113\.9/)).toBeVisible();
|
||||
});
|
||||
|
||||
test('kreator edycji: zapis bez zmian członkostw wysyła tylko PATCH konta', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM, TEST_GYM_2] }, users: { users: [TEST_USER] } });
|
||||
await loginAsAdmin(page);
|
||||
|
||||
@@ -250,6 +250,8 @@ export interface MockApiOptions {
|
||||
users?: unknown;
|
||||
/** Ciało odpowiedzi GET /admin/logs. */
|
||||
logs?: unknown;
|
||||
/** Ciało odpowiedzi GET /admin/users/:id/activity (historia konta). */
|
||||
activity?: unknown;
|
||||
/** Ciało odpowiedzi GET /admin/gyms/claims. */
|
||||
claims?: unknown;
|
||||
/** Startowy stan GET /admin/announcements (stateful CRUD w teście). */
|
||||
@@ -268,6 +270,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
gyms = { gyms: [] },
|
||||
users = { users: [] },
|
||||
logs = { logs: TEST_LOGS, total: TEST_LOGS.length },
|
||||
activity = { logs: [], total: 0 },
|
||||
claims = { claims: [] as GymClaim[] },
|
||||
announcements = [] as AdminAnnouncement[],
|
||||
} = opts;
|
||||
@@ -620,6 +623,14 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
}),
|
||||
);
|
||||
|
||||
page.route('**/api/v1/admin/users/*/activity*', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(activity ?? { logs: [], total: 0 }),
|
||||
}),
|
||||
);
|
||||
|
||||
page.route('**/api/v1/admin/users/*/history', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "lastLoginAt" TIMESTAMP(3);
|
||||
@@ -107,6 +107,8 @@ model User {
|
||||
status UserStatus @default(ACTIVE)
|
||||
suspensionUntil DateTime?
|
||||
restrictionReason String?
|
||||
/// Data ostatniego udanego logowania (login, nie odświeżanie tokenu).
|
||||
lastLoginAt DateTime?
|
||||
availability Json?
|
||||
priorities String?
|
||||
exclusions String?
|
||||
|
||||
@@ -22,6 +22,7 @@ export function publicUser(u: User) {
|
||||
status: u.status,
|
||||
suspensionUntil: u.suspensionUntil,
|
||||
restrictionReason: u.restrictionReason,
|
||||
lastLoginAt: u.lastLoginAt,
|
||||
createdAt: u.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1081,6 +1081,38 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
const userActivityQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(500).optional(),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/users/{id}/activity:
|
||||
* get:
|
||||
* summary: Account history — audit entries performed on the user (admin).
|
||||
* Logi o bycie `user` z jego ID: logowania (IP), edycje (admin/self), kary (status/reason), rola admina, utworzenie/usunięcie.
|
||||
* Query: limit (default 50, max 500), offset (default 0).
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { logs, total } }
|
||||
* 404: { description: User not found }
|
||||
*/
|
||||
router.get(
|
||||
'/users/:id/activity',
|
||||
validate(userActivityQuerySchema, 'query'),
|
||||
asyncHandler(async (req, res) => {
|
||||
await ensureUser(prisma, req.params.id);
|
||||
const q = req.query as z.infer<typeof userActivityQuerySchema>;
|
||||
const result = await listActivityLogs(prisma, {
|
||||
entityUserId: req.params.id,
|
||||
limit: q.limit ?? 50,
|
||||
offset: q.offset ?? 0,
|
||||
});
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
const logsQuerySchema = z.object({
|
||||
action: z.string().min(1).max(100).optional(),
|
||||
userId: z.string().min(1).max(100).optional(),
|
||||
|
||||
@@ -90,7 +90,7 @@ export function createAuthRoutes({ prisma }: AppDeps) {
|
||||
action: 'user.registered',
|
||||
entityType: 'user',
|
||||
entityId: result.user.id,
|
||||
details: { email: result.user.email },
|
||||
details: { email: result.user.email, ip: req.ip },
|
||||
});
|
||||
setRefreshCookie(res, result.refreshToken, isAdminClient(req));
|
||||
res.status(201).json({ user: result.user, accessToken: result.accessToken });
|
||||
@@ -119,7 +119,7 @@ export function createAuthRoutes({ prisma }: AppDeps) {
|
||||
action: 'user.logged_in',
|
||||
entityType: 'user',
|
||||
entityId: result.user.id,
|
||||
details: { client: isAdminClient(req) ? 'admin' : 'app' },
|
||||
details: { client: isAdminClient(req) ? 'admin' : 'app', ip: req.ip },
|
||||
});
|
||||
setRefreshCookie(res, result.refreshToken, isAdminClient(req));
|
||||
// Administrator logujacy sie przez aplikacje dostaje dodatkowo ciastko
|
||||
@@ -194,7 +194,7 @@ export function createAuthRoutes({ prisma }: AppDeps) {
|
||||
action: 'user.logged_out',
|
||||
entityType: 'user',
|
||||
entityId: payload.sub,
|
||||
details: { client: isAdminClient(req) ? 'admin' : 'app' },
|
||||
details: { client: isAdminClient(req) ? 'admin' : 'app', ip: req.ip },
|
||||
});
|
||||
} catch {
|
||||
// token nieważny — nie ma czego unieważniać
|
||||
|
||||
@@ -36,6 +36,8 @@ export async function logActivity(prisma: PrismaClient, input: ActivityLogInput)
|
||||
export interface ActivityLogFilters {
|
||||
action?: string;
|
||||
userId?: string;
|
||||
/** Historia operacji WYKONANYCH NA użytkowniku: logi o bycie `user` z jego ID jako entityId. */
|
||||
entityUserId?: string;
|
||||
/** Inclusive ISO date (YYYY-MM-DD). */
|
||||
from?: string;
|
||||
/** Inclusive ISO date (YYYY-MM-DD). */
|
||||
@@ -65,6 +67,7 @@ export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLo
|
||||
const where: Prisma.ActivityLogWhereInput = {
|
||||
...(filters.action ? { action: filters.action } : {}),
|
||||
...(filters.userId ? { actorId: filters.userId } : {}),
|
||||
...(filters.entityUserId ? { entityType: 'user', entityId: filters.entityUserId } : {}),
|
||||
// Granice dat w strefie serwera (jak reszta systemu), nie w UTC.
|
||||
createdAt:
|
||||
filters.from || filters.to
|
||||
|
||||
@@ -76,8 +76,13 @@ export async function login(prisma: PrismaClient, input: LoginInput): Promise<Au
|
||||
const ok = await bcrypt.compare(input.password, user?.passwordHash ?? DUMMY_HASH);
|
||||
if (!user || !ok) throw unauthorized('Invalid credentials');
|
||||
await assertUsable(prisma, user);
|
||||
// znakujemy ostatnie logowanie (refresh tokenu NIE odświeża tej wartości)
|
||||
const updated = await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { lastLoginAt: new Date() },
|
||||
});
|
||||
return {
|
||||
user: publicUser(user),
|
||||
user: publicUser(updated),
|
||||
accessToken: signAccessToken(user.id, user.tokenVersion),
|
||||
refreshToken: signRefreshToken(user.id, user.tokenVersion),
|
||||
};
|
||||
|
||||
@@ -44,7 +44,8 @@ export const openapi: Record<string, unknown> = {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Login',
|
||||
description: 'Writes an ActivityLog entry: user.logged_in (details: client = app|admin).',
|
||||
description:
|
||||
'Writes an ActivityLog entry: user.logged_in (details: client = app|admin, ip = request address). Updates user.lastLoginAt.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -89,7 +90,7 @@ export const openapi: Record<string, unknown> = {
|
||||
tags: ['Auth'],
|
||||
summary: 'Logout (clears refresh cookie)',
|
||||
description:
|
||||
'Writes an ActivityLog entry: user.logged_out (only when a refresh token is present).',
|
||||
'Writes an ActivityLog entry: user.logged_out (only when a refresh token is present; details: client, ip).',
|
||||
},
|
||||
},
|
||||
'/me': {
|
||||
@@ -1658,5 +1659,32 @@ export const openapi: Record<string, unknown> = {
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
},
|
||||
},
|
||||
'/admin/users/{id}/activity': {
|
||||
get: {
|
||||
tags: ['Admin'],
|
||||
summary:
|
||||
'Account history — audit entries performed on the user: logins (IP), edits, bans/suspensions, admin role, creation/deletion (admin)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{
|
||||
name: 'limit',
|
||||
in: 'query',
|
||||
required: false,
|
||||
schema: { type: 'integer', minimum: 1, maximum: 500, default: 50 },
|
||||
},
|
||||
{
|
||||
name: 'offset',
|
||||
in: 'query',
|
||||
required: false,
|
||||
schema: { type: 'integer', minimum: 0, default: 0 },
|
||||
},
|
||||
],
|
||||
responses: {
|
||||
200: { description: 'OK — { logs, total }, newest first' },
|
||||
404: { description: 'User not found' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -845,3 +845,89 @@ describe('admin: kary na koncie (status)', () => {
|
||||
expect(relogin.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin: historia konta (GET /admin/users/:id/activity)', () => {
|
||||
let adminToken: string;
|
||||
let adminId: string;
|
||||
let adminEmail: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { user } = await createUser({ isAdmin: true, firstName: 'Ada', lastName: 'Admin' });
|
||||
adminId = user.id;
|
||||
adminEmail = user.email;
|
||||
adminToken = (await loginViaApi(user.email, PASSWORD)).token;
|
||||
});
|
||||
|
||||
it('nieistniejący użytkownik → 404', async () => {
|
||||
const app = buildApp();
|
||||
const res = await app
|
||||
.get('/api/v1/admin/users/nope-123/activity')
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('zwraca wpisy wykonane NA użytkowniku z aktorem i szczegółami kary', async () => {
|
||||
const app = buildApp();
|
||||
const { user } = await createUser();
|
||||
|
||||
// logowanie celu (user.logged_in z ip) + edycja tożsamości przez admina + kara
|
||||
await loginViaApi(user.email, PASSWORD);
|
||||
const edit = await app
|
||||
.patch(`/api/v1/admin/users/${user.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ firstName: 'Zmieniony' });
|
||||
expect(edit.status).toBe(200);
|
||||
const ban = await app
|
||||
.patch(`/api/v1/admin/users/${user.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ status: 'BANNED', restrictionReason: 'Dystrybucja kont' });
|
||||
expect(ban.status).toBe(200);
|
||||
|
||||
const res = await app
|
||||
.get(`/api/v1/admin/users/${user.id}/activity`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
const actions: string[] = res.body.logs.map((l: { action: string }) => l.action);
|
||||
expect(actions).toContain('user.logged_in');
|
||||
expect(actions).toContain('user.updated');
|
||||
expect(actions).toContain('user.status.changed');
|
||||
|
||||
const banLog = res.body.logs.find(
|
||||
(l: { action: string }) => l.action === 'user.status.changed',
|
||||
);
|
||||
expect(banLog.entityId).toBe(user.id);
|
||||
expect(banLog.actor).toMatchObject({ id: adminId, email: adminEmail });
|
||||
expect(banLog.details).toMatchObject({ status: 'BANNED', restrictionReason: 'Dystrybucja kont' });
|
||||
|
||||
const editLog = res.body.logs.find((l: { action: string }) => l.action === 'user.updated');
|
||||
expect(editLog.details.fields).toEqual(['firstName']);
|
||||
|
||||
const loginLog = res.body.logs.find((l: { action: string }) => l.action === 'user.logged_in');
|
||||
expect(typeof loginLog.details.ip).toBe('string');
|
||||
expect(loginLog.details.ip!.length).toBeGreaterThan(0);
|
||||
|
||||
// nowość pierwsza + paginacja działa
|
||||
expect(res.body.total).toBeGreaterThanOrEqual(3);
|
||||
const paged = await app
|
||||
.get(`/api/v1/admin/users/${user.id}/activity?limit=2&offset=0`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(paged.body.logs).toHaveLength(2);
|
||||
expect(paged.body.logs[0].createdAt >= paged.body.logs[1].createdAt).toBe(true);
|
||||
});
|
||||
|
||||
it('filtr nie wycieka logami innych użytkowników', async () => {
|
||||
const app = buildApp();
|
||||
const { user: a } = await createUser();
|
||||
const { user: b } = await createUser();
|
||||
await app
|
||||
.patch(`/api/v1/admin/users/${a.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ status: 'BANNED', restrictionReason: 'Powód A' });
|
||||
|
||||
const res = await app
|
||||
.get(`/api/v1/admin/users/${b.id}/activity`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.logs.every((l: { entityId: string }) => l.entityId === b.id)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,6 +73,45 @@ describe('auth routes', () => {
|
||||
expect((res.headers['set-cookie'] ?? [])[0]).toContain('fitos_refresh=');
|
||||
});
|
||||
|
||||
it('login: stamps lastLoginAt and logs the client IP', async () => {
|
||||
const app = buildApp();
|
||||
const { user, password } = await createUser();
|
||||
const before = await prisma.user.findUnique({ where: { id: user.id } });
|
||||
expect(before?.lastLoginAt).toBeNull();
|
||||
const res = await app
|
||||
.post('/api/v1/auth/login')
|
||||
.set('X-Forwarded-For', '203.0.113.9')
|
||||
.send({ email: user.email, password });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user.lastLoginAt).toBeTruthy();
|
||||
|
||||
const db = await prisma.user.findUnique({ where: { id: user.id } });
|
||||
expect(db?.lastLoginAt).toBeInstanceOf(Date);
|
||||
|
||||
const log = await prisma.activityLog.findFirst({
|
||||
where: { action: 'user.logged_in', entityId: user.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
expect(log).not.toBeNull();
|
||||
expect((log!.details as Record<string, unknown>).ip).toBe('203.0.113.9');
|
||||
expect((log!.details as Record<string, unknown>).client).toBe('app');
|
||||
});
|
||||
|
||||
it('register: logs the client IP', async () => {
|
||||
const app = buildApp();
|
||||
const email = `ipreg-${rand()}@test.local`;
|
||||
const res = await app
|
||||
.post('/api/v1/auth/register')
|
||||
.set('X-Forwarded-For', '198.51.100.7')
|
||||
.send({ email, password: PASSWORD });
|
||||
expect(res.status).toBe(201);
|
||||
const log = await prisma.activityLog.findFirst({
|
||||
where: { action: 'user.registered', entityId: res.body.user.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
expect((log!.details as Record<string, unknown>).ip).toBe('198.51.100.7');
|
||||
});
|
||||
|
||||
it('login: rejects a wrong password with 401', async () => {
|
||||
const app = buildApp();
|
||||
const { user } = await createUser();
|
||||
|
||||
@@ -5,7 +5,14 @@ import { signRefreshToken } from '../../src/lib/jwt.js';
|
||||
|
||||
function mockPrisma() {
|
||||
return {
|
||||
user: { findUnique: vi.fn(), create: vi.fn() },
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(async ({ data }: { data: Record<string, unknown> }) => ({
|
||||
...userRow,
|
||||
...data,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -30,6 +37,7 @@ const userRow = {
|
||||
status: 'ACTIVE' as const,
|
||||
suspensionUntil: null,
|
||||
restrictionReason: null,
|
||||
lastLoginAt: null as Date | null,
|
||||
};
|
||||
|
||||
describe('register', () => {
|
||||
@@ -101,6 +109,19 @@ describe('login', () => {
|
||||
expect(result.accessToken).toBeTruthy();
|
||||
expect(result.refreshToken).toBeTruthy();
|
||||
});
|
||||
|
||||
it('znacza lastLoginAt przy udanym logowaniu', async () => {
|
||||
const prisma = mockPrisma();
|
||||
prisma.user.findUnique.mockResolvedValue({
|
||||
...userRow,
|
||||
passwordHash: bcrypt.hashSync('correct-pass', 10),
|
||||
});
|
||||
const result = await login(prisma, { email: 'test@test.local', password: 'correct-pass' });
|
||||
const call = prisma.user.update.mock.calls[0][0] as { where: { id: string }; data: Record<string, unknown> };
|
||||
expect(call.where).toEqual({ id: 'u1' });
|
||||
expect(call.data.lastLoginAt).toBeInstanceOf(Date);
|
||||
expect(result.user.lastLoginAt).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
|
||||
describe('refresh', () => {
|
||||
|
||||
Reference in New Issue
Block a user