feat: implement activity logging for user actions and create activities table
All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 44s
All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 44s
This commit is contained in:
parent
6c75efbc28
commit
7e2f320b4f
12 changed files with 420 additions and 160 deletions
|
|
@ -1,70 +1,46 @@
|
||||||
import type { HttpContext } from '@adonisjs/core/http';
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
import User from '#models/user';
|
import User from '#models/user';
|
||||||
import BackupCode from '#models/backup_code';
|
import BackupCode from '#models/backup_code';
|
||||||
// import Hash from '@ioc:Adonis/Core/Hash';
|
|
||||||
// import InvalidCredentialException from 'App/Exceptions/InvalidCredentialException';
|
|
||||||
import { authValidator } from '#validators/auth';
|
import { authValidator } from '#validators/auth';
|
||||||
import hash from '@adonisjs/core/services/hash';
|
import hash from '@adonisjs/core/services/hash';
|
||||||
import db from '@adonisjs/lucid/services/db';
|
import db from '@adonisjs/lucid/services/db';
|
||||||
import TwoFactorAuthProvider from '#app/services/TwoFactorAuthProvider';
|
import TwoFactorAuthProvider from '#app/services/TwoFactorAuthProvider';
|
||||||
// import { Authenticator } from '@adonisjs/auth';
|
import ActivityLogger from '#services/activity_logger';
|
||||||
// import { LoginState } from 'Contracts/enums';
|
import logger from '@adonisjs/core/services/logger';
|
||||||
// import { StatusCodes } from 'http-status-codes';
|
|
||||||
|
|
||||||
// interface MyHttpsContext extends HttpContext {
|
|
||||||
// auth: Authenticator<User>
|
|
||||||
// }
|
|
||||||
export default class AuthController {
|
export default class AuthController {
|
||||||
// login function{ request, auth, response }:HttpContext
|
|
||||||
public async login({ request, response, auth, session }: HttpContext) {
|
public async login({ request, response, auth, session }: HttpContext) {
|
||||||
// console.log({
|
|
||||||
// registerBody: request.body(),
|
|
||||||
// });
|
|
||||||
// await request.validate(AuthValidator);
|
|
||||||
await request.validateUsing(authValidator);
|
await request.validateUsing(authValidator);
|
||||||
|
|
||||||
// const plainPassword = await request.input('password');
|
|
||||||
// const email = await request.input('email');
|
|
||||||
// grab uid and password values off request body
|
|
||||||
const { email, password } = request.only(['email', 'password']);
|
const { email, password } = request.only(['email', 'password']);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
await db.connection().rawQuery('SELECT 1');
|
||||||
|
|
||||||
await db.connection().rawQuery('SELECT 1')
|
|
||||||
|
|
||||||
|
|
||||||
// // attempt to verify credential and login user
|
|
||||||
// await auth.use('web').attempt(email, plainPassword);
|
|
||||||
|
|
||||||
// const user = await auth.use('web').verifyCredentials(email, password);
|
|
||||||
const user = await User.verifyCredentials(email, password);
|
const user = await User.verifyCredentials(email, password);
|
||||||
|
|
||||||
if (user.isTwoFactorEnabled) {
|
if (user.isTwoFactorEnabled) {
|
||||||
// session.put("login.id", user.id);
|
// Noch KEIN abgeschlossenes Login -> nicht loggen.
|
||||||
// return view.render("pages/two-factor-challenge");
|
|
||||||
|
|
||||||
session.flash('user_id', user.id);
|
session.flash('user_id', user.id);
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
|
|
||||||
// let state = LoginState.STATE_VALIDATED;
|
|
||||||
// return response.status(StatusCodes.OK).json({
|
|
||||||
// state: state,
|
|
||||||
// new_user_id: user.id,
|
|
||||||
// });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await auth.use('web').login(user);
|
await auth.use('web').login(user);
|
||||||
} catch (error) {
|
this.recordAuthEvent('auth.login', { user, ip: request.ip() });
|
||||||
|
} catch (error: any) {
|
||||||
|
// DB nicht erreichbar -> kein fehlgeschlagener Login-Versuch, weiterwerfen
|
||||||
if (error.code === 'ECONNREFUSED') {
|
if (error.code === 'ECONNREFUSED') {
|
||||||
throw error
|
throw error;
|
||||||
}
|
}
|
||||||
// if login fails, return vague form message and redirect back
|
|
||||||
|
// Echter Credential-Fehler -> als fehlgeschlagenen Versuch protokollieren
|
||||||
|
this.recordAuthEvent('auth.login_failed', { email, ip: request.ip() });
|
||||||
|
|
||||||
session.flash('message', 'Your username, email, or password is incorrect');
|
session.flash('message', 'Your username, email, or password is incorrect');
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
|
|
||||||
// otherwise, redirect todashboard
|
return response.redirect('/apps/dashboard');
|
||||||
response.redirect('/apps/dashboard');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async twoFactorChallenge({ request, session, auth, response }: HttpContext) {
|
public async twoFactorChallenge({ request, session, auth, response }: HttpContext) {
|
||||||
|
|
@ -74,27 +50,19 @@ export default class AuthController {
|
||||||
if (code) {
|
if (code) {
|
||||||
const isValid = await TwoFactorAuthProvider.validate(user, code);
|
const isValid = await TwoFactorAuthProvider.validate(user, code);
|
||||||
if (isValid) {
|
if (isValid) {
|
||||||
// login user and redirect to dashboard
|
|
||||||
await auth.use('web').login(user);
|
await auth.use('web').login(user);
|
||||||
response.redirect('/apps/dashboard');
|
this.recordAuthEvent('auth.login', { user, email: user.email, ip: request.ip(), method: '2fa_totp' });
|
||||||
} else {
|
return response.redirect('/apps/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
session.flash('message', 'Your two-factor code is incorrect');
|
session.flash('message', 'Your two-factor code is incorrect');
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
} else if (backup_code) {
|
|
||||||
|
if (backup_code) {
|
||||||
const codes: BackupCode[] = await user.getBackupCodes();
|
const codes: BackupCode[] = await user.getBackupCodes();
|
||||||
|
|
||||||
// const verifiedBackupCodes = await Promise.all(
|
let backupCodeToDelete: BackupCode | null = null;
|
||||||
// codes.map(async (backupCode) => {
|
|
||||||
// let isVerified = await hash.verify(backupCode.code, backup_code);
|
|
||||||
// if (isVerified) {
|
|
||||||
// return backupCode;
|
|
||||||
// }
|
|
||||||
// }),
|
|
||||||
// );
|
|
||||||
// const backupCodeToDelete = verifiedBackupCodes.find(Boolean);
|
|
||||||
|
|
||||||
let backupCodeToDelete = null;
|
|
||||||
for (const backupCode of codes) {
|
for (const backupCode of codes) {
|
||||||
const isVerified = await hash.verify(backupCode.code, backup_code);
|
const isVerified = await hash.verify(backupCode.code, backup_code);
|
||||||
if (isVerified) {
|
if (isVerified) {
|
||||||
|
|
@ -103,29 +71,68 @@ export default class AuthController {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (backupCodeToDelete) {
|
if (!backupCodeToDelete) {
|
||||||
if (backupCodeToDelete.used === false) {
|
|
||||||
backupCodeToDelete.used = true;
|
|
||||||
await backupCodeToDelete.save();
|
|
||||||
console.log(`BackupCode with id ${backupCodeToDelete.id} has been marked as used.`);
|
|
||||||
await auth.use('web').login(user);
|
|
||||||
response.redirect('/apps/dashboard');
|
|
||||||
} else {
|
|
||||||
session.flash('message', 'BackupCode already used');
|
|
||||||
return response.redirect().back();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
session.flash('message', 'BackupCode not found');
|
session.flash('message', 'BackupCode not found');
|
||||||
return response.redirect().back();
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
if (backupCodeToDelete.used) {
|
||||||
|
session.flash('message', 'BackupCode already used');
|
||||||
|
return response.redirect().back();
|
||||||
}
|
}
|
||||||
|
|
||||||
// logout function
|
backupCodeToDelete.used = true;
|
||||||
public async logout({ auth, response }: HttpContext) {
|
await backupCodeToDelete.save();
|
||||||
// await auth.logout();
|
|
||||||
|
await auth.use('web').login(user);
|
||||||
|
this.recordAuthEvent('auth.login', { user, email: user.email, ip: request.ip(), method: '2fa_backup_code' });
|
||||||
|
|
||||||
|
return response.redirect('/apps/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Weder code noch backup_code übergeben
|
||||||
|
session.flash('message', 'No verification code provided');
|
||||||
|
return response.redirect().back();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async logout({ auth, request, response }: HttpContext) {
|
||||||
|
// Session auflösen -> füllt auth.user, falls eingeloggt
|
||||||
|
await auth.use('web').check();
|
||||||
|
const user = auth.use('web').user;
|
||||||
|
|
||||||
await auth.use('web').logout();
|
await auth.use('web').logout();
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
this.recordAuthEvent('auth.logout', { user, email: user.email, ip: request.ip() });
|
||||||
|
}
|
||||||
|
|
||||||
return response.redirect('/app/login');
|
return response.redirect('/app/login');
|
||||||
// return response.status(200);
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zentraler Audit-Logger für Auth-Events.
|
||||||
|
* Fire-and-forget: ein Fehler beim Schreiben darf Login/Logout nie blockieren.
|
||||||
|
*/
|
||||||
|
private recordAuthEvent(
|
||||||
|
type: 'auth.login' | 'auth.logout' | 'auth.login_failed',
|
||||||
|
opts: { user?: User; email?: string; ip: string; method?: string },
|
||||||
|
) {
|
||||||
|
const { user, email, ip, method } = opts;
|
||||||
|
|
||||||
|
const description =
|
||||||
|
type === 'auth.login'
|
||||||
|
? `${user!.firstName} ${user!.lastName} signed in`
|
||||||
|
: type === 'auth.logout'
|
||||||
|
? `${user!.firstName} ${user!.lastName} signed out`
|
||||||
|
: `Failed login attempt for ${email ?? 'unknown'}`;
|
||||||
|
|
||||||
|
void ActivityLogger.log({
|
||||||
|
type,
|
||||||
|
description,
|
||||||
|
userId: user?.id ?? null,
|
||||||
|
subjectType: user ? 'User' : null,
|
||||||
|
subjectId: user?.id ?? null,
|
||||||
|
properties: { ip, ...(method ? { method } : {}) },
|
||||||
|
}).catch((err) => logger.error({ err }, `failed to record ${type} activity`));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,8 @@ import type { Multipart } from '@adonisjs/bodyparser';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { parseBytesSize, getConfigFor, getTmpPath, formatBytes, errorMessage } from '#app/utils/utility-functions';
|
import { parseBytesSize, getConfigFor, getTmpPath, formatBytes, errorMessage } from '#app/utils/utility-functions';
|
||||||
import validation from '#services/validation_service';
|
import validation from '#services/validation_service';
|
||||||
|
import ActivityLogger from '#services/activity_logger';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
|
||||||
interface Dictionary {
|
interface Dictionary {
|
||||||
[index: string]: string;
|
[index: string]: string;
|
||||||
|
|
@ -469,9 +471,7 @@ export default class DatasetController {
|
||||||
console.error('Error cleaning up temporary file:', cleanupError);
|
console.error('Error cleaning up temporary file:', cleanupError);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
request.multipart.abort(
|
request.multipart.abort(validation.make('files', `Upload limit of ${formatBytes(aggregatedLimit)} exceeded.`, 'limit'));
|
||||||
validation.make('files', `Upload limit of ${formatBytes(aggregatedLimit)} exceeded.`, 'limit')
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -513,10 +513,21 @@ export default class DatasetController {
|
||||||
trx = await db.transaction();
|
trx = await db.transaction();
|
||||||
const user = (await User.find(auth.user?.id)) as User;
|
const user = (await User.find(auth.user?.id)) as User;
|
||||||
|
|
||||||
await this.createDatasetAndAssociations(user, request, trx);
|
// await this.createDatasetAndAssociations(user, request, trx);
|
||||||
|
const { dataset, mainTitle } = await this.createDatasetAndAssociations(user, request, trx);
|
||||||
|
|
||||||
await trx.commit();
|
await trx.commit();
|
||||||
console.log('Dataset and related models created successfully');
|
console.log('Dataset and related models created successfully');
|
||||||
|
|
||||||
|
// NACH dem Commit: Dataset ist garantiert persistiert, keine Waisen-Gefahr.
|
||||||
|
// Fire-and-forget, damit ein Log-Fehler den bereits erfolgreichen Upload nicht kippt.
|
||||||
|
void ActivityLogger.log({
|
||||||
|
type: 'dataset.uploaded',
|
||||||
|
description: `New publication uploaded: ${mainTitle ?? 'Untitled'}`,
|
||||||
|
userId: user.id,
|
||||||
|
subjectType: 'Dataset',
|
||||||
|
subjectId: dataset.id,
|
||||||
|
}).catch((err) => logger.error({ err }, 'failed to record dataset.uploaded activity'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Clean up temporary files if validation or later steps fail
|
// Clean up temporary files if validation or later steps fail
|
||||||
uploadedTmpFiles.forEach((tmpPath) => {
|
uploadedTmpFiles.forEach((tmpPath) => {
|
||||||
|
|
@ -564,6 +575,15 @@ export default class DatasetController {
|
||||||
await this.savePersons(dataset, request.input('contributors', []), 'contributor', trx);
|
await this.savePersons(dataset, request.input('contributors', []), 'contributor', trx);
|
||||||
|
|
||||||
//save main and additional titles
|
//save main and additional titles
|
||||||
|
// const titles = request.input('titles', []);
|
||||||
|
// for (const titleData of titles) {
|
||||||
|
// const title = new Title();
|
||||||
|
// title.value = titleData.value;
|
||||||
|
// title.language = titleData.language;
|
||||||
|
// title.type = titleData.type;
|
||||||
|
// await dataset.useTransaction(trx).related('titles').save(title);
|
||||||
|
// }
|
||||||
|
let mainTitle: string | null = null;
|
||||||
const titles = request.input('titles', []);
|
const titles = request.input('titles', []);
|
||||||
for (const titleData of titles) {
|
for (const titleData of titles) {
|
||||||
const title = new Title();
|
const title = new Title();
|
||||||
|
|
@ -571,6 +591,11 @@ export default class DatasetController {
|
||||||
title.language = titleData.language;
|
title.language = titleData.language;
|
||||||
title.type = titleData.type;
|
title.type = titleData.type;
|
||||||
await dataset.useTransaction(trx).related('titles').save(title);
|
await dataset.useTransaction(trx).related('titles').save(title);
|
||||||
|
|
||||||
|
if (titleData.type === 'Main') {
|
||||||
|
// <-- an eure Typ-Konvention anpassen
|
||||||
|
mainTitle = titleData.value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// save descriptions
|
// save descriptions
|
||||||
|
|
@ -664,6 +689,8 @@ export default class DatasetController {
|
||||||
await dataset.useTransaction(trx).related('files').save(newFile);
|
await dataset.useTransaction(trx).related('files').save(newFile);
|
||||||
await newFile.createHashValues(trx);
|
await newFile.createHashValues(trx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return { dataset, mainTitle }; // <-- statt void
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateRandomString(length: number): string {
|
private generateRandomString(length: number): string {
|
||||||
|
|
@ -1095,7 +1122,7 @@ export default class DatasetController {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const error = new errors.E_VALIDATION_ERROR({
|
const error = new errors.E_VALIDATION_ERROR({
|
||||||
'files': `Aggregated upload limit of ${formatBytes(aggregatedLimit)} exceeded. The total size of files being uploaded would exceed the limit.`,
|
files: `Aggregated upload limit of ${formatBytes(aggregatedLimit)} exceeded. The total size of files being uploaded would exceed the limit.`,
|
||||||
});
|
});
|
||||||
request.multipart.abort(error);
|
request.multipart.abort(error);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
43
app/controllers/activities_controller.ts
Normal file
43
app/controllers/activities_controller.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
// app/controllers/activities_controller.ts
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import Activity from '#models/activity';
|
||||||
|
|
||||||
|
export default class ActivitiesController {
|
||||||
|
async index({ response }: HttpContext) {
|
||||||
|
// const activities = await Activity.query()
|
||||||
|
// .preload('user', (q) => q.select('id', 'login'))
|
||||||
|
// .orderBy('created_at', 'desc')
|
||||||
|
// .limit(10);
|
||||||
|
|
||||||
|
// return response.json(
|
||||||
|
// activities.map((a) => ({
|
||||||
|
// id: a.id,
|
||||||
|
// type: a.type,
|
||||||
|
// description: a.description,
|
||||||
|
// user: a.user?.login ?? null,
|
||||||
|
// created_at: a.createdAt.toISO(), // relativeTime() expects ISO
|
||||||
|
// })),
|
||||||
|
// );
|
||||||
|
try {
|
||||||
|
const activities = await Activity.query()
|
||||||
|
.preload('user', (q) => q.select('id', 'login'))
|
||||||
|
.orderBy('created_at', 'desc')
|
||||||
|
.limit(10);
|
||||||
|
|
||||||
|
return response.json(
|
||||||
|
activities.map((a) => ({
|
||||||
|
id: a.id,
|
||||||
|
type: a.type,
|
||||||
|
description: a.description,
|
||||||
|
user: a.user?.login ?? null,
|
||||||
|
created_at: a.createdAt.toISO(), // relativeTime() expects ISO
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching activities:', error);
|
||||||
|
return response.status(500).json({ error: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
57
app/models/activity.ts
Normal file
57
app/models/activity.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
// app/models/activity.ts
|
||||||
|
import { DateTime } from 'luxon';
|
||||||
|
import { belongsTo, column } from '@adonisjs/lucid/orm';
|
||||||
|
import BaseModel from './base_model.js';
|
||||||
|
import type { BelongsTo } from '@adonisjs/lucid/types/relations';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||||
|
|
||||||
|
export default class Activity extends BaseModel {
|
||||||
|
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||||
|
public static primaryKey = 'id';
|
||||||
|
public static table = 'activities';
|
||||||
|
|
||||||
|
@column({ isPrimary: true })
|
||||||
|
declare id: number;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare type: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare userId: number | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare subjectType: string | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare subjectId: number | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare description: string;
|
||||||
|
|
||||||
|
// Manual JSON (de)serialization keeps this working on SQLite/MySQL.
|
||||||
|
// On Postgres json/jsonb the driver already parses — drop the `consume`
|
||||||
|
// JSON.parse there to avoid double-handling.
|
||||||
|
// @column({
|
||||||
|
// prepare: (value: Record<string, any> | null) => (value ? JSON.stringify(value) : null),
|
||||||
|
// consume: (value: string | null) => (value ? JSON.parse(value) : null),
|
||||||
|
// })
|
||||||
|
// declare properties: Record<string, any> | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare properties: Record<string, any> | null;
|
||||||
|
|
||||||
|
@column.dateTime({ autoCreate: true })
|
||||||
|
declare createdAt: DateTime;
|
||||||
|
|
||||||
|
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||||
|
declare updatedAt: DateTime;
|
||||||
|
|
||||||
|
// @belongsTo(() => User)
|
||||||
|
// declare user: BelongsTo<typeof User>;
|
||||||
|
|
||||||
|
@belongsTo(() => User, {
|
||||||
|
foreignKey: 'userId',
|
||||||
|
})
|
||||||
|
declare user: BelongsTo<typeof User>;
|
||||||
|
}
|
||||||
|
|
@ -5,7 +5,10 @@ import {
|
||||||
belongsTo,
|
belongsTo,
|
||||||
hasMany,
|
hasMany,
|
||||||
computed,
|
computed,
|
||||||
hasOne
|
hasOne,
|
||||||
|
afterCreate,
|
||||||
|
beforeUpdate,
|
||||||
|
afterUpdate,
|
||||||
} from '@adonisjs/lucid/orm';
|
} from '@adonisjs/lucid/orm';
|
||||||
import { DateTime } from 'luxon';
|
import { DateTime } from 'luxon';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
|
|
@ -23,10 +26,11 @@ import DatasetIdentifier from './dataset_identifier.js';
|
||||||
import Project from './project.js';
|
import Project from './project.js';
|
||||||
import DocumentXmlCache from './DocumentXmlCache.js';
|
import DocumentXmlCache from './DocumentXmlCache.js';
|
||||||
import DatasetExtension from '#models/traits/dataset_extension';
|
import DatasetExtension from '#models/traits/dataset_extension';
|
||||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
import type { ManyToMany } from '@adonisjs/lucid/types/relations';
|
||||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
import type { BelongsTo } from '@adonisjs/lucid/types/relations';
|
||||||
import type { HasMany } from "@adonisjs/lucid/types/relations";
|
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
import type { HasOne } from "@adonisjs/lucid/types/relations";
|
import type { HasOne } from '@adonisjs/lucid/types/relations';
|
||||||
|
import ActivityLogger from '#services/activity_logger';
|
||||||
|
|
||||||
export default class Dataset extends DatasetExtension {
|
export default class Dataset extends DatasetExtension {
|
||||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||||
|
|
@ -267,7 +271,9 @@ export default class Dataset extends DatasetExtension {
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getMax(column: string) {
|
static async getMax(column: string) {
|
||||||
let dataset = await this.query().max(column + ' as max_publish_id').firstOrFail();
|
let dataset = await this.query()
|
||||||
|
.max(column + ' as max_publish_id')
|
||||||
|
.firstOrFail();
|
||||||
return dataset.$extras.max_publish_id;
|
return dataset.$extras.max_publish_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -284,4 +290,34 @@ export default class Dataset extends DatasetExtension {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @afterCreate()
|
||||||
|
// static async logUploaded(dataset: Dataset) {
|
||||||
|
// await dataset.preload('titles');
|
||||||
|
|
||||||
|
// await ActivityLogger.log({
|
||||||
|
// type: 'dataset.uploaded',
|
||||||
|
// description: `New publication uploaded: ${dataset.mainTitle ?? 'Untitled'}`,
|
||||||
|
// subjectType: 'Dataset',
|
||||||
|
// subjectId: dataset.id,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
@beforeUpdate()
|
||||||
|
static capturePublish(dataset: Dataset) {
|
||||||
|
// $dirty is populated here, before persistence
|
||||||
|
(dataset as any).$becamePublished = dataset.$dirty.status !== undefined && dataset.status === 'published';
|
||||||
|
}
|
||||||
|
|
||||||
|
@afterUpdate()
|
||||||
|
static async logPublished(dataset: Dataset) {
|
||||||
|
if ((dataset as any).$becamePublished) {
|
||||||
|
await ActivityLogger.log({
|
||||||
|
type: 'dataset.published',
|
||||||
|
description: `Publication published: ${dataset.mainTitle}`,
|
||||||
|
subjectType: 'Dataset',
|
||||||
|
subjectId: dataset.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import type { ManyToMany } from '@adonisjs/lucid/types/relations';
|
||||||
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
import { compose } from '@adonisjs/core/helpers';
|
import { compose } from '@adonisjs/core/helpers';
|
||||||
import BackupCode from './backup_code.js';
|
import BackupCode from './backup_code.js';
|
||||||
|
import Activity from './activity.js';
|
||||||
|
|
||||||
const AuthFinder = withAuthFinder(() => hash.use('laravel'), {
|
const AuthFinder = withAuthFinder(() => hash.use('laravel'), {
|
||||||
uids: ['email'],
|
uids: ['email'],
|
||||||
|
|
@ -111,6 +112,11 @@ export default class User extends compose(BaseModel, AuthFinder) {
|
||||||
})
|
})
|
||||||
public backupcodes: HasMany<typeof BackupCode>;
|
public backupcodes: HasMany<typeof BackupCode>;
|
||||||
|
|
||||||
|
@hasMany(() => Activity, {
|
||||||
|
foreignKey: 'user_id',
|
||||||
|
})
|
||||||
|
public activities: HasMany<typeof Activity>;
|
||||||
|
|
||||||
@computed({
|
@computed({
|
||||||
serializeAs: 'is_admin',
|
serializeAs: 'is_admin',
|
||||||
})
|
})
|
||||||
|
|
|
||||||
27
app/services/activity_logger.ts
Normal file
27
app/services/activity_logger.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
// app/services/activity_logger.ts
|
||||||
|
import Activity from '#models/activity'
|
||||||
|
|
||||||
|
interface LogOptions {
|
||||||
|
type: string
|
||||||
|
description: string
|
||||||
|
userId?: number | null
|
||||||
|
subjectType?: string | null
|
||||||
|
subjectId?: number | string | null
|
||||||
|
properties?: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class ActivityLogger {
|
||||||
|
static async log(options: LogOptions): Promise<void> {
|
||||||
|
await Activity.create({
|
||||||
|
type: options.type,
|
||||||
|
description: options.description,
|
||||||
|
userId: options.userId ?? null,
|
||||||
|
subjectType: options.subjectType ?? null,
|
||||||
|
subjectId: options.subjectId != null ? Number(options.subjectId) : null,
|
||||||
|
properties: options.properties ?? null,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Invalidate the cache if you add one (see Redis section).
|
||||||
|
// await redis.del('activities:recent')
|
||||||
|
}
|
||||||
|
}
|
||||||
25
database/migrations/1782294801884_create_activities_table.ts
Normal file
25
database/migrations/1782294801884_create_activities_table.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class extends BaseSchema {
|
||||||
|
protected tableName = 'activities';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.createTable(this.tableName, (table) => {
|
||||||
|
table.increments('id');
|
||||||
|
table.string('type').notNullable().index(); // 'dataset.uploaded', 'auth.login'
|
||||||
|
table.integer('user_id').unsigned().nullable().references('id').inTable('accounts').onDelete('SET NULL');
|
||||||
|
table.string('subject_type').nullable(); // manual morph: model name
|
||||||
|
table.bigInteger('subject_id').unsigned().nullable();
|
||||||
|
table.string('description').notNullable();
|
||||||
|
table.json('properties').nullable();
|
||||||
|
table.timestamp('created_at');
|
||||||
|
table.timestamp('updated_at');
|
||||||
|
table.index(['subject_type', 'subject_id'])
|
||||||
|
table.index('created_at')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.dropTable(this.tableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -210,3 +210,12 @@ export interface Identifier {
|
||||||
// STATE_VALIDATED = 1,
|
// STATE_VALIDATED = 1,
|
||||||
// STATE_2FA_AUTHENTICATED = 1,
|
// STATE_2FA_AUTHENTICATED = 1,
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// resources/js/Dataset.ts (oder wo User definiert ist)
|
||||||
|
export interface Activity {
|
||||||
|
id: number | string;
|
||||||
|
type: string;
|
||||||
|
description: string;
|
||||||
|
user: string | null;
|
||||||
|
created_at: string; // ISO-String, relativeTime() erwartet das
|
||||||
|
}
|
||||||
|
|
@ -32,6 +32,7 @@ import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.
|
||||||
import CardBoxDataset from '@/Components/CardBoxDataset.vue';
|
import CardBoxDataset from '@/Components/CardBoxDataset.vue';
|
||||||
import type { User } from '@/Dataset';
|
import type { User } from '@/Dataset';
|
||||||
import { stardust } from '@eidellev/adonis-stardust/client';
|
import { stardust } from '@eidellev/adonis-stardust/client';
|
||||||
|
import type { Activity } from '@/Dataset';
|
||||||
|
|
||||||
const mainService = MainService();
|
const mainService = MainService();
|
||||||
|
|
||||||
|
|
@ -65,6 +66,7 @@ onMounted(async () => {
|
||||||
mainService.fetchApi('clients'),
|
mainService.fetchApi('clients'),
|
||||||
mainService.fetchApi('authors'),
|
mainService.fetchApi('authors'),
|
||||||
mainService.fetchApi('datasets'),
|
mainService.fetchApi('datasets'),
|
||||||
|
mainService.fetchApi('activities'),
|
||||||
loadChart(),
|
loadChart(),
|
||||||
]);
|
]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
@ -176,16 +178,16 @@ const quickActions = [
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
type Activity = {
|
// type Activity = {
|
||||||
id: number | string;
|
// id: number | string;
|
||||||
description: string;
|
// description: string;
|
||||||
user?: string;
|
// user?: string;
|
||||||
created_at: string;
|
// created_at: string;
|
||||||
};
|
// };
|
||||||
|
|
||||||
// Reads from the store if your backend provides it; otherwise renders an empty
|
// Reads from the store if your backend provides it; otherwise renders an empty
|
||||||
// state. Populate via e.g. mainService.fetchApi('activities') in onMounted.
|
// state. Populate via e.g. mainService.fetchApi('activities') in onMounted.
|
||||||
const recentActivity = computed<Activity[]>(() => (mainService as any).activities ?? []);
|
const recentActivity = computed<Activity[]>(() => mainService.activities);
|
||||||
|
|
||||||
const relativeTime = (iso: string): string => {
|
const relativeTime = (iso: string): string => {
|
||||||
const then = new Date(iso).getTime();
|
const then = new Date(iso).getTime();
|
||||||
|
|
@ -235,67 +237,6 @@ const relativeTime = (iso: string): string => {
|
||||||
{{ loadError }}
|
{{ loadError }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Stats Grid -->
|
|
||||||
<div class="reveal reveal-1 grid grid-cols-1 gap-6 lg:grid-cols-3 mb-8">
|
|
||||||
<div
|
|
||||||
class="rounded-xl border-l-4 border-emerald-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
|
||||||
>
|
|
||||||
<CardBoxWidget color="text-emerald-500" :icon="mdiAccountMultiple" :number="authors.length" label="Authors" />
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="rounded-xl border-l-4 border-blue-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
|
||||||
>
|
|
||||||
<CardBoxWidget color="text-blue-500" :icon="mdiDatabaseOutline" :number="datasets.length" label="Publications" />
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="rounded-xl border-l-4 border-purple-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
|
||||||
>
|
|
||||||
<CardBoxWidget color="text-purple-500" :icon="mdiChartTimelineVariant" :number="submitters.length" label="Submitters" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Recent Datasets Section -->
|
|
||||||
<div v-if="recentDatasets.length > 0" class="reveal reveal-2 mb-8">
|
|
||||||
<SectionTitleLineWithButton :icon="mdiTrendingUp" title="Recent Publications">
|
|
||||||
<span class="text-sm text-gray-500 dark:text-gray-400"> Latest {{ recentDatasets.length }} publications </span>
|
|
||||||
</SectionTitleLineWithButton>
|
|
||||||
|
|
||||||
<div class="grid grid-cols-1 gap-4">
|
|
||||||
<CardBoxDataset
|
|
||||||
v-for="dataset in recentDatasets"
|
|
||||||
:key="dataset.id"
|
|
||||||
:dataset="dataset"
|
|
||||||
class="hover:shadow-md transition-all duration-300"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Chart Section -->
|
|
||||||
<SectionTitleLineWithButton :icon="mdiChartPie" title="Trends Overview" class="reveal reveal-3 mt-8">
|
|
||||||
<span class="text-sm text-gray-500 dark:text-gray-400">Publications per month</span>
|
|
||||||
</SectionTitleLineWithButton>
|
|
||||||
|
|
||||||
<CardBox
|
|
||||||
title="Performance"
|
|
||||||
:icon="mdiFinance"
|
|
||||||
:header-icon="mdiReload"
|
|
||||||
class="reveal reveal-3 mb-6 shadow-lg"
|
|
||||||
@header-icon-click="loadChart"
|
|
||||||
>
|
|
||||||
<div v-if="isLoadingChart" role="status" aria-live="polite" class="flex items-center justify-center h-96">
|
|
||||||
<div class="flex flex-col items-center gap-3">
|
|
||||||
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
|
|
||||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading chart data...</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-else-if="chartData" class="relative">
|
|
||||||
<line-chart :data="chartData" class="h-96" />
|
|
||||||
</div>
|
|
||||||
<div v-else class="flex items-center justify-center h-96 text-gray-500 dark:text-gray-400">
|
|
||||||
<p>No chart data available</p>
|
|
||||||
</div>
|
|
||||||
</CardBox>
|
|
||||||
|
|
||||||
<!-- ============================== Admin ============================== -->
|
<!-- ============================== Admin ============================== -->
|
||||||
<template v-if="isAdmin">
|
<template v-if="isAdmin">
|
||||||
<SectionTitleLineWithButton :icon="mdiShieldCrownOutline" title="Admin Overview" class="mt-10">
|
<SectionTitleLineWithButton :icon="mdiShieldCrownOutline" title="Admin Overview" class="mt-10">
|
||||||
|
|
@ -330,7 +271,12 @@ const relativeTime = (iso: string): string => {
|
||||||
<!-- Quick actions + Recent activity -->
|
<!-- Quick actions + Recent activity -->
|
||||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
|
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
|
||||||
<!-- Quick actions -->
|
<!-- Quick actions -->
|
||||||
<CardBox :icon="mdiLightningBoltOutline" :show-header-icon="false" title="Quick Actions" class="lg:col-span-1 shadow-lg">
|
<CardBox
|
||||||
|
:icon="mdiLightningBoltOutline"
|
||||||
|
:show-header-icon="false"
|
||||||
|
title="Quick Actions"
|
||||||
|
class="lg:col-span-1 shadow-lg"
|
||||||
|
>
|
||||||
<div class="grid gap-3">
|
<div class="grid gap-3">
|
||||||
<Link
|
<Link
|
||||||
v-for="action in quickActions"
|
v-for="action in quickActions"
|
||||||
|
|
@ -398,6 +344,67 @@ const relativeTime = (iso: string): string => {
|
||||||
<TableSampleClients />
|
<TableSampleClients />
|
||||||
</CardBox>
|
</CardBox>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- Stats Grid -->
|
||||||
|
<!-- <div class="reveal reveal-1 grid grid-cols-1 gap-6 lg:grid-cols-3 mb-8">
|
||||||
|
<div
|
||||||
|
class="rounded-xl border-l-4 border-emerald-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<CardBoxWidget color="text-emerald-500" :icon="mdiAccountMultiple" :number="authors.length" label="Authors" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="rounded-xl border-l-4 border-blue-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<CardBoxWidget color="text-blue-500" :icon="mdiDatabaseOutline" :number="datasets.length" label="Publications" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="rounded-xl border-l-4 border-purple-500 bg-white dark:bg-slate-900/40 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<CardBoxWidget color="text-purple-500" :icon="mdiChartTimelineVariant" :number="submitters.length" label="Submitters" />
|
||||||
|
</div>
|
||||||
|
</div> -->
|
||||||
|
|
||||||
|
<!-- Recent Datasets Section -->
|
||||||
|
<div v-if="recentDatasets.length > 0" class="reveal reveal-2 mb-8">
|
||||||
|
<SectionTitleLineWithButton :icon="mdiTrendingUp" title="Recent Publications">
|
||||||
|
<span class="text-sm text-gray-500 dark:text-gray-400"> Latest {{ recentDatasets.length }} publications </span>
|
||||||
|
</SectionTitleLineWithButton>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 gap-4">
|
||||||
|
<CardBoxDataset
|
||||||
|
v-for="dataset in recentDatasets"
|
||||||
|
:key="dataset.id"
|
||||||
|
:dataset="dataset"
|
||||||
|
class="hover:shadow-md transition-all duration-300"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Chart Section -->
|
||||||
|
<SectionTitleLineWithButton :icon="mdiChartPie" title="Trends Overview" class="reveal reveal-3 mt-8">
|
||||||
|
<span class="text-sm text-gray-500 dark:text-gray-400">Publications per month</span>
|
||||||
|
</SectionTitleLineWithButton>
|
||||||
|
|
||||||
|
<CardBox
|
||||||
|
title="Performance"
|
||||||
|
:icon="mdiFinance"
|
||||||
|
:header-icon="mdiReload"
|
||||||
|
class="reveal reveal-3 mb-6 shadow-lg"
|
||||||
|
@header-icon-click="loadChart"
|
||||||
|
>
|
||||||
|
<div v-if="isLoadingChart" role="status" aria-live="polite" class="flex items-center justify-center h-96">
|
||||||
|
<div class="flex flex-col items-center gap-3">
|
||||||
|
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
|
||||||
|
<p class="text-sm text-gray-500 dark:text-gray-400">Loading chart data...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="chartData" class="relative">
|
||||||
|
<line-chart :data="chartData" class="h-96" />
|
||||||
|
</div>
|
||||||
|
<div v-else class="flex items-center justify-center h-96 text-gray-500 dark:text-gray-400">
|
||||||
|
<p>No chart data available</p>
|
||||||
|
</div>
|
||||||
|
</CardBox>
|
||||||
</SectionMain>
|
</SectionMain>
|
||||||
</LayoutAuthenticated>
|
</LayoutAuthenticated>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { defineStore } from 'pinia';
|
import { defineStore } from 'pinia';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { Dataset } from '@/Dataset';
|
import { Activity, Dataset } from '@/Dataset';
|
||||||
import menu from '@/menu';
|
import menu from '@/menu';
|
||||||
// import type Person from '#models/person';
|
// import type Person from '#models/person';
|
||||||
|
|
||||||
|
|
@ -133,6 +133,8 @@ export const MainService = defineStore('main', {
|
||||||
used: 0,
|
used: 0,
|
||||||
codes: [],
|
codes: [],
|
||||||
|
|
||||||
|
activities: [] as Array<Activity>, // <-- neu
|
||||||
|
|
||||||
graphData: {},
|
graphData: {},
|
||||||
}),
|
}),
|
||||||
actions: {
|
actions: {
|
||||||
|
|
@ -203,6 +205,17 @@ export const MainService = defineStore('main', {
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// async fetchApi(resource: string) {
|
||||||
|
// try {
|
||||||
|
// const { data } = await axios.get(`/api/${resource}`);
|
||||||
|
// // @ts-ignore – dynamischer Key
|
||||||
|
// this[resource] = data;
|
||||||
|
// } catch (error) {
|
||||||
|
// console.error(`Failed to fetch ${resource}`, error);
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
|
||||||
|
|
||||||
setState(state: any) {
|
setState(state: any) {
|
||||||
this.totpState = state;
|
this.totpState = state;
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -8,12 +8,15 @@ import AvatarController from '#controllers/Http/Api/AvatarController';
|
||||||
import UserController from '#controllers/Http/Api/UserController';
|
import UserController from '#controllers/Http/Api/UserController';
|
||||||
import CollectionsController from '#controllers/Http/Api/collections_controller';
|
import CollectionsController from '#controllers/Http/Api/collections_controller';
|
||||||
import { middleware } from '../kernel.js';
|
import { middleware } from '../kernel.js';
|
||||||
|
import ActivitiesController from '#app/controllers/activities_controller';
|
||||||
|
|
||||||
// Clean DOI URL routes (no /api prefix)
|
// Clean DOI URL routes (no /api prefix)
|
||||||
|
|
||||||
// API routes with /api prefix
|
// API routes with /api prefix
|
||||||
router
|
router
|
||||||
.group(() => {
|
.group(() => {
|
||||||
|
router.get('activities', [ActivitiesController, 'index']).as('activities.index');
|
||||||
|
|
||||||
router.get('clients', [UserController, 'getSubmitters']).as('client.index').use(middleware.auth());
|
router.get('clients', [UserController, 'getSubmitters']).as('client.index').use(middleware.auth());
|
||||||
router.get('authors', [AuthorsController, 'index']).as('author.index').use(middleware.auth());
|
router.get('authors', [AuthorsController, 'index']).as('author.index').use(middleware.auth());
|
||||||
router.get('datasets', [DatasetController, 'index']).as('dataset.index');
|
router.get('datasets', [DatasetController, 'index']).as('dataset.index');
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue