- npm updates
All checks were successful
CI Pipeline / japa-tests (push) Successful in 55s

- removed all controller methods from 'app/Controlles/Http/Admin/UsersControllers.ts'
- merged all authentication methods inside 'app/Controllers/Http/Auth/UserController.ts'
This commit is contained in:
Kaimbacher 2024-02-06 16:39:33 +01:00
parent 68928b5e07
commit 4efa53673f
7 changed files with 133 additions and 187 deletions

View file

@ -4,10 +4,10 @@ import Role from 'App/Models/Role';
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
import CreateUserValidator from 'App/Validators/CreateUserValidator';
import UpdateUserValidator from 'App/Validators/UpdateUserValidator';
import { RenderResponse } from '@ioc:EidelLev/Inertia';
// import { RenderResponse } from '@ioc:EidelLev/Inertia';
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
// import Hash from '@ioc:Adonis/Core/Hash';
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
import Hash from '@ioc:Adonis/Core/Hash';
import { schema, rules } from '@ioc:Adonis/Core/Validator';
export default class UsersController {
public async index({ auth, request, inertia }: HttpContextContract) {
@ -163,87 +163,6 @@ export default class UsersController {
return response.redirect().toRoute('user.index');
}
/**
* Show the user a form to change their personal information & password.
*
* @return \Inertia\Response
*/
public accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
const user = auth.user;
// const id = request.param('id');
// const user = await User.query().where('id', id).firstOrFail();
return inertia.render('Admin/User/AccountInfo', {
user: user,
});
}
/**
* Save the modified personal information for a user.
*
* @param HttpContextContract ctx
* @return : RedirectContract
*/
public async accountInfoStoreOld({ request, response, auth, session }: HttpContextContract) {
// validate update form
await request.validate(UpdateUserValidator);
const payload = request.only(['login', 'email']);
auth.user?.merge(payload);
const user = await auth.user?.save();
// $user = \Auth::user()->update($request->except(['_token']));
let message;
if (user) {
message = 'Account updated successfully.';
} else {
message = 'Error while saving. Please try again.';
}
session.flash(message);
return response.redirect().toRoute('admin.account.info');
//->with('message', __($message));
}
public async accountInfoStore({ auth, request, response, session }) {
const passwordSchema = schema.create({
old_password: schema.string({ trim: true }, [rules.required()]),
new_password: schema.string({ trim: true }, [rules.minLength(8), rules.maxLength(255), rules.confirmed('confirm_password')]),
confirm_password: schema.string({ trim: true }, [rules.required()]),
});
try {
await request.validate({ schema: passwordSchema });
} catch (error) {
// return response.badRequest(error.messages);
throw error;
}
try {
const user = await auth.user;
const { old_password, new_password } = request.only(['old_password', 'new_password']);
// if (!(old_password && new_password && confirm_password)) {
// 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({ warning: 'Old password is incorrect.' }).redirect().back();
}
// Hash the new password before updating the user's password
user.password = new_password;
await user.save();
// return response.status(200).send({ message: 'Password updated successfully.' });
session.flash('Password updated successfully.');
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();
}
}
// private async syncRoles(userId: number, roleIds: Array<number>) {
// const user = await User.findOrFail(userId)
// // const roles: Role[] = await Role.query().whereIn('id', roleIds);

View file

@ -1,10 +1,9 @@
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';
import Hash from '@ioc:Adonis/Core/Hash';
import { schema, rules } from '@ioc:Adonis/Core/Validator';
// Here we are generating secret and recovery codes for the user thats enabling 2FA and storing them to our database.
export default class UserController {
@ -26,6 +25,46 @@ export default class UserController {
});
}
public async accountInfoStore({ auth, request, response, session }) {
const passwordSchema = schema.create({
old_password: schema.string({ trim: true }, [rules.required()]),
new_password: schema.string({ trim: true }, [rules.minLength(8), rules.maxLength(255), rules.confirmed('confirm_password')]),
confirm_password: schema.string({ trim: true }, [rules.required()]),
});
try {
await request.validate({ schema: passwordSchema });
} catch (error) {
// return response.badRequest(error.messages);
throw error;
}
try {
const user = await auth.user;
const { old_password, new_password } = request.only(['old_password', 'new_password']);
// if (!(old_password && new_password && confirm_password)) {
// 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({ warning: 'Old password is incorrect.' }).redirect().back();
}
// Hash the new password before updating the user's password
user.password = new_password;
await user.save();
// return response.status(200).send({ message: 'Password updated successfully.' });
session.flash('Password updated successfully.');
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();
}
}
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;

View file

@ -1,48 +1,3 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<Dataset>
<Rdr_Dataset Id="306" PublisherName="GeoSphere Austria" PublishId="213"
CreatingCorporation="Tethys RDR" Language="en" ServerState="published"
Type="measurementdata">
<CreatedAt Year="2023" Month="11" Day="30" Hour="10" Minute="20" Second="58"
UnixTimestamp="1701336058" Timezone="Europe/Berlin" />
<ServerDateModified Year="2024" Month="1" Day="22" Hour="12" Minute="28" Second="17"
UnixTimestamp="1705922897" Timezone="Europe/Berlin" />
<ServerDatePublished Year="2024" Month="1" Day="22" Hour="12" Minute="28" Second="8"
UnixTimestamp="1705922888" Timezone="Europe/Berlin" />
<TitleMain Id="682" DocumentId="306" Type="Main" Value="rewerewr" Language="en" />
<TitleAbstract Id="1017" DocumentId="306" Type="Abstract" Value="rewrewr" Language="en" />
<Licence Id="1" Active="true"
LinkLicence="https://creativecommons.org/licenses/by/4.0/deed.en"
LinkLogo="https://licensebuttons.net/l/by/4.0/88x31.png"
NameLong="Creative Commons Attribution 4.0 International (CC BY 4.0)"
Name="CC-BY-4.0" SortOrder="1" />
<PersonAuthor Id="1" Email="m.moser@univie.ac.at" FirstName="Michael" LastName="Moser"
Status="true" NameType="Personal" Role="author" SortOrder="1"
AllowEmailContact="false" />
<PersonContributor Id="28" Email="juergen.reitner@geologie.ac.at" FirstName="Jürgen"
LastName="Reitner" Status="false" NameType="Personal" Role="contributor"
SortOrder="1" AllowEmailContact="false" />
<Subject Id="143" Language="de" Type="Geoera" Value="Aletshausen-Langenneufnach Störung"
CreatedAt="2023-11-21 17:17:43" UpdatedAt="2023-11-21 17:17:43" />
<Subject Id="164" Language="de" Type="Geoera" Value="Wolfersberg-Moosach Störung"
ExternalKey="https://data.geoscience.earth/ncl/geoera/hotLime/faults/3503"
CreatedAt="2023-11-30 10:20:58" UpdatedAt="2023-11-30 10:20:58" />
<Subject Id="165" Language="en" Type="Uncontrolled" Value="wefwef"
CreatedAt="2023-11-30 10:20:58" UpdatedAt="2023-11-30 10:20:58" />
<File Id="1037" DocumentId="306" PathName="files/306/file-clpkzkkgq0001nds14fua5um6.png"
Label="freieIP.png" MimeType="image/png" FileSize="112237" VisibleInFrontdoor="true"
VisibleInOai="true" SortOrder="0" CreatedAt="2023-11-30 10:21:14"
UpdatedAt="2023-11-30 10:21:14" />
<Coverage Id="284" DatasetId="306" XMin="11.71142578125" XMax="14.414062500000002"
YMin="46.58906908309185" YMax="47.45780853075031" CreatedAt="2023-11-30 10:20:58"
UpdatedAt="2023-11-30 10:20:58" />
<Collection Id="21" RoleId="3" Number="551" Name="Geology, hydrology, meteorology"
ParentId="20" Visible="true" VisiblePublish="true" />
</Rdr_Dataset>
</Dataset>
</root>
<?xml version="1.0" encoding="utf-8"?>
<resource xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/"

View file

@ -35,6 +35,7 @@ import { ValidationException } from '@ioc:Adonis/Core/Validator';
import Drive from '@ioc:Adonis/Core/Drive';
import { Exception } from '@adonisjs/core/build/standalone';
import { MultipartFileContract } from '@ioc:Adonis/Core/BodyParser';
import * as crypto from 'crypto';
export default class DatasetController {
public async index({ auth, request, inertia }: HttpContextContract) {
@ -432,8 +433,9 @@ export default class DatasetController {
}
// clientName: 'Gehaltsschema.png'
// extname: 'png'
// fieldName: 'file'
const fileName = `file-${cuid()}.${file.extname}`;
// fieldName: 'file'
// const fileName = `file-${this.generateRandomString(32)}.${file.extname}`;
const fileName = this.generateFilename(file.extname as string);
const mimeType = file.headers['content-type'] || 'application/octet-stream'; // Fallback to a default MIME type
const datasetFolder = `files/${dataset.id}`;
// const size = file.size;
@ -460,6 +462,20 @@ export default class DatasetController {
}
}
private generateRandomString(length: number): string {
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
}
private generateFilename(extension: string): string {
const randomString1 = this.generateRandomString(8);
const randomString2 = this.generateRandomString(4);
const randomString3 = this.generateRandomString(4);
const randomString4 = this.generateRandomString(4);
const randomString5 = this.generateRandomString(12);
return `file-${randomString1}-${randomString2}-${randomString3}-${randomString4}-${randomString5}.${extension}`;
}
private async scanFileForViruses(filePath, host?: string, port?: number): Promise<void> {
// const clamscan = await (new ClamScan().init());
const opts: ClamScan.Options = {