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,100 +1,68 @@
|
|||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import User from '#models/user';
|
||||
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 hash from '@adonisjs/core/services/hash';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import TwoFactorAuthProvider from '#app/services/TwoFactorAuthProvider';
|
||||
// import { Authenticator } from '@adonisjs/auth';
|
||||
// import { LoginState } from 'Contracts/enums';
|
||||
// import { StatusCodes } from 'http-status-codes';
|
||||
import ActivityLogger from '#services/activity_logger';
|
||||
import logger from '@adonisjs/core/services/logger';
|
||||
|
||||
// interface MyHttpsContext extends HttpContext {
|
||||
// auth: Authenticator<User>
|
||||
// }
|
||||
export default class AuthController {
|
||||
// login function{ request, auth, response }:HttpContext
|
||||
public async login({ request, response, auth, session }: HttpContext) {
|
||||
// console.log({
|
||||
// registerBody: request.body(),
|
||||
// });
|
||||
// await request.validate(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']);
|
||||
|
||||
try {
|
||||
|
||||
await db.connection().rawQuery('SELECT 1')
|
||||
|
||||
|
||||
// // attempt to verify credential and login user
|
||||
// await auth.use('web').attempt(email, plainPassword);
|
||||
await db.connection().rawQuery('SELECT 1');
|
||||
|
||||
// const user = await auth.use('web').verifyCredentials(email, password);
|
||||
const user = await User.verifyCredentials(email, password);
|
||||
|
||||
if (user.isTwoFactorEnabled) {
|
||||
// session.put("login.id", user.id);
|
||||
// return view.render("pages/two-factor-challenge");
|
||||
|
||||
// Noch KEIN abgeschlossenes Login -> nicht loggen.
|
||||
session.flash('user_id', user.id);
|
||||
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);
|
||||
} 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') {
|
||||
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');
|
||||
return response.redirect().back();
|
||||
}
|
||||
|
||||
// otherwise, redirect todashboard
|
||||
response.redirect('/apps/dashboard');
|
||||
return response.redirect('/apps/dashboard');
|
||||
}
|
||||
|
||||
public async twoFactorChallenge({ request, session, auth, response }: HttpContext) {
|
||||
const { code, backup_code, login_id } = request.only(['code', 'backup_code', 'login_id']);
|
||||
const { code, backup_code, login_id } = request.only(['code', 'backup_code', 'login_id']);
|
||||
const user = await User.query().where('id', login_id).firstOrFail();
|
||||
|
||||
if (code) {
|
||||
const isValid = await TwoFactorAuthProvider.validate(user, code);
|
||||
if (isValid) {
|
||||
// login user and redirect to dashboard
|
||||
await auth.use('web').login(user);
|
||||
response.redirect('/apps/dashboard');
|
||||
} else {
|
||||
session.flash('message', 'Your two-factor code is incorrect');
|
||||
return response.redirect().back();
|
||||
this.recordAuthEvent('auth.login', { user, email: user.email, ip: request.ip(), method: '2fa_totp' });
|
||||
return response.redirect('/apps/dashboard');
|
||||
}
|
||||
} else if (backup_code) {
|
||||
const codes: BackupCode[] = await user.getBackupCodes();
|
||||
|
||||
// const verifiedBackupCodes = await Promise.all(
|
||||
// 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;
|
||||
session.flash('message', 'Your two-factor code is incorrect');
|
||||
return response.redirect().back();
|
||||
}
|
||||
|
||||
if (backup_code) {
|
||||
const codes: BackupCode[] = await user.getBackupCodes();
|
||||
|
||||
let backupCodeToDelete: BackupCode | null = null;
|
||||
for (const backupCode of codes) {
|
||||
const isVerified = await hash.verify(backupCode.code, backup_code);
|
||||
if (isVerified) {
|
||||
|
|
@ -103,29 +71,68 @@ export default class AuthController {
|
|||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
if (!backupCodeToDelete) {
|
||||
session.flash('message', 'BackupCode not found');
|
||||
return response.redirect().back();
|
||||
}
|
||||
}
|
||||
|
||||
if (backupCodeToDelete.used) {
|
||||
session.flash('message', 'BackupCode already used');
|
||||
return response.redirect().back();
|
||||
}
|
||||
|
||||
backupCodeToDelete.used = true;
|
||||
await backupCodeToDelete.save();
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
// logout function
|
||||
public async logout({ auth, response }: HttpContext) {
|
||||
// await auth.logout();
|
||||
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();
|
||||
|
||||
if (user) {
|
||||
this.recordAuthEvent('auth.logout', { user, email: user.email, ip: request.ip() });
|
||||
}
|
||||
|
||||
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`));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue