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:
@@ -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