- aded npm packages @types/qrcode, qrcode and node-f2a
Some checks failed
CI Pipeline / japa-tests (push) Failing after 53s

- corrected UsersController.ts and RoleController.ts with correct routes for settings
- added migration script and ui and Controller for 2 Factor Authentication
- npm updates
This commit is contained in:
Kaimbacher 2023-12-29 15:54:49 +01:00
parent 87e9314b00
commit c70fa4a0d8
16 changed files with 1098 additions and 417 deletions

View file

@ -129,7 +129,7 @@ export default class RoleController {
}
session.flash('message', 'Role has been updated successfully');
return response.redirect().toRoute('role.index');
return response.redirect().toRoute('settings.role.index');
}
public async destroy({ request, response, session }: HttpContextContract) {

View file

@ -151,7 +151,7 @@ export default class UsersController {
}
session.flash('message', 'User has been updated successfully');
return response.redirect().toRoute('user.index');
return response.redirect().toRoute('settings.user.index');
}
public async destroy({ request, response, session }: HttpContextContract) {
@ -222,13 +222,13 @@ export default class UsersController {
const { old_password, new_password } = request.only(['old_password', 'new_password']);
// if (!(old_password && new_password && confirm_password)) {
// return response.status(400).send({ message: 'Old password and new password are required.' });
// return response.status(400).send({ warning: 'Old password and new password are required.' });
// }
// Verify if the provided old password matches the user's current password
const isSame = await Hash.verify(user.password, old_password);
if (!isSame) {
return response.flash({ message: 'Old password is incorrect.' }).redirect().back();
return response.flash({ warning: 'Old password is incorrect.' }).redirect().back();
}
// Hash the new password before updating the user's password
@ -237,7 +237,7 @@ export default class UsersController {
// return response.status(200).send({ message: 'Password updated successfully.' });
session.flash('Password updated successfully.');
return response.redirect().toRoute('settings.user');
return response.redirect().toRoute('settings.user.index');
} catch (error) {
// return response.status(500).send({ message: 'Internal server error.' });
return response.flash('warning', `Invalid server state. Internal server error.`).redirect().back();

View file

@ -0,0 +1,78 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import User from 'App/Models/User';
// import Hash from '@ioc:Adonis/Core/Hash';
// import InvalidCredentialException from 'App/Exceptions/InvalidCredentialException';
// import AuthValidator from 'App/Validators/AuthValidator';
import { RenderResponse } from '@ioc:EidelLev/Inertia';
import TwoFactorAuthProvider from 'App/Services/TwoFactorAuthProvider';
// Here we are generating secret and recovery codes for the user thats enabling 2FA and storing them to our database.
export default class UserController {
/**
* Show the user a form to change their personal information & password.
*
* @return \Inertia\Response
*/
public async accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
// const user = auth.user;
const user = (await User.find(auth.user?.id)) as User;
// const id = request.param('id');
// const user = await User.query().where('id', id).firstOrFail();
return inertia.render('Auth/AccountInfo', {
user: user,
twoFactorEnabled: user.isTwoFactorEnabled,
code: await TwoFactorAuthProvider.generateQrCode(user),
});
}
public async enableTwoFactorAuthentication({ auth, response, session }: HttpContextContract): Promise<void> {
// const user: User | undefined = auth?.user;
const user = (await User.find(auth.user?.id)) as User;
user.twoFactorSecret = TwoFactorAuthProvider.generateSecret(user);
user.twoFactorRecoveryCodes = await TwoFactorAuthProvider.generateRecoveryCodes();
await user.save();
session.flash('message', 'Two factor authentication enabled.');
return response.redirect().back();
// return inertia.render('Auth/AccountInfo', {
// // status: {
// // type: 'success',
// // message: 'Two factor authentication enabled.',
// // },
// user: user,
// twoFactorEnabled: user.isTwoFactorEnabled,
// code: await TwoFactorAuthProvider.generateQrCode(user),
// recoveryCodes: user.twoFactorRecoveryCodes,
// });
}
public async disableTwoFactorAuthentication({ auth, response, session }): Promise<void> {
const user = auth?.user;
user.twoFactorSecret = null;
user.twoFactorRecoveryCodes = null;
await user.save();
session.flash('message', 'Two factor authentication disabled.');
return response.redirect().back();
// return inertia.render('Auth/AccountInfo', {
// // status: {
// // type: 'success',
// // message: 'Two factor authentication disabled.',
// // },
// user: user,
// twoFactorEnabled: user.isTwoFactorEnabled,
// });
}
// public async fetchRecoveryCodes({ auth, view }) {
// const user = auth?.user;
// return view.render('pages/settings', {
// twoFactorEnabled: user.isTwoFactorEnabled,
// recoveryCodes: user.twoFactorRecoveryCodes,
// });
// }
}

View file

@ -6,6 +6,7 @@ import Database from '@ioc:Adonis/Lucid/Database';
import Config from '@ioc:Adonis/Core/Config';
import Dataset from './Dataset';
import BaseModel from './BaseModel';
import Encryption from '@ioc:Adonis/Core/Encryption';
// export default interface IUser {
// id: number;
@ -44,6 +45,22 @@ export default class User extends BaseModel {
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime;
// serializeAs: null removes the model properties from the serialized output.
@column({
serializeAs: null,
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '{}') : null),
prepare: (value: string) => Encryption.encrypt(JSON.stringify(value)),
})
public twoFactorSecret?: string;
// serializeAs: null removes the model properties from the serialized output.
@column({
serializeAs: null,
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '[]') : []),
prepare: (value: string[]) => Encryption.encrypt(JSON.stringify(value)),
})
public twoFactorRecoveryCodes?: string[];
@beforeSave()
public static async hashPassword(user) {
if (user.$dirty.password) {
@ -51,6 +68,10 @@ export default class User extends BaseModel {
}
}
public get isTwoFactorEnabled() {
return Boolean(this?.twoFactorSecret);
}
@manyToMany(() => Role, {
pivotForeignKey: 'account_id',
pivotRelatedForeignKey: 'role_id',

View file

@ -0,0 +1,89 @@
import Config from '@ioc:Adonis/Core/Config';
import User from 'App/Models/User';
import { generateSecret } from 'node-2fa/dist/index';
// import cryptoRandomString from 'crypto-random-string';
import QRCode from 'qrcode';
import crypto from 'crypto';
// npm install node-2fa --save
// npm install crypto-random-string --save
// import { cryptoRandomStringAsync } from 'crypto-random-string/index';
// npm install qrcode --save
// npm i --save-dev @types/qrcode
class TwoFactorAuthProvider {
private issuer = Config.get('twoFactorAuthConfig.app.name') || 'TethysCloud';
/**
* generateSecret will generate a user-specific 32-character secret.
* Were providing the name of the app and the users email as parameters for the function.
* This secret key will be used to verify whether the token provided by the user during authentication is valid or not.
*
* Return the default global focus trap stack *
* @param {User} user user for the secrect
* @return {string}
*/
public generateSecret(user: User) {
const secret = generateSecret({
name: this.issuer,
account: user.email,
});
return secret.secret;
}
/**
* We also generated recovery codes which can be used in case were unable to retrieve tokens from 2FA applications.
* We assign the user a list of recovery codes and each code can be used only once during the authentication process.
* The recovery codes are random strings generated using the cryptoRandomString library.
*
* Return recovery codes
* @return {string[]}
*/
public generateRecoveryCodes() {
const recoveryCodeLimit: number = 8;
const codes: string[] = [];
for (let i = 0; i < recoveryCodeLimit; i++) {
const recoveryCode: string = `${this.secureRandomString()}-${this.secureRandomString()}`;
codes.push(recoveryCode);
}
return codes;
}
private secureRandomString() {
// return await cryptoRandomString.async({ length: 10, type: 'hex' });
return this.generateRandomString(10, 'hex');
}
private generateRandomString(length: number, type: 'hex' | 'base64' | 'numeric' = 'hex'): string {
const byteLength = Math.ceil(length * 0.5); // For hex encoding, each byte generates 2 characters
const randomBytes = crypto.randomBytes(byteLength);
switch (type) {
case 'hex':
return randomBytes.toString('hex').slice(0, length);
case 'base64':
return randomBytes.toString('base64').slice(0, length);
case 'numeric':
return randomBytes
.toString('hex')
.replace(/[a-fA-F]/g, '') // Remove non-numeric characters
.slice(0, length);
default:
throw new Error('Invalid type specified');
}
}
public async generateQrCode(user: User) : Promise<{svg: string; url: string; }> {
const issuer = encodeURIComponent(this.issuer); // 'TethysCloud'
// const userName = encodeURIComponent(user.email); // 'rrqx9472%40tethys.at'
const label = `${this.issuer}:${user.email}`;
const algorithm = encodeURIComponent("SHA256");
const query = `?secret=${user.twoFactorSecret}&issuer=${issuer}&algorithm=${algorithm}&digits=6`; // '?secret=FEYCLOSO627CB7SMLX6QQ7BP75L7SJ54&issuer=TethysCloud'
const url = `otpauth://totp/${label}${query}`; // 'otpauth://totp/rrqx9472%40tethys.at?secret=FEYCLOSO627CB7SMLX6QQ7BP75L7SJ54&issuer=TethysCloud'
const svg = await QRCode.toDataURL(url);
return { svg, url };
}
}
export default new TwoFactorAuthProvider();