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:
@@ -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' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user