76 lines
2.0 KiB
TypeScript
76 lines
2.0 KiB
TypeScript
import {
|
|
BadRequestException,
|
|
Controller,
|
|
Get,
|
|
Post,
|
|
Redirect,
|
|
Render,
|
|
Req,
|
|
Session,
|
|
UploadedFile,
|
|
UseInterceptors,
|
|
} from '@nestjs/common';
|
|
import { FileInterceptor } from '@nestjs/platform-express';
|
|
import { Request } from 'express';
|
|
import { SessionData } from 'express-session';
|
|
import { unlink } from 'fs/promises';
|
|
import { UploadService } from 'src/modules/objects/upload/upload.service';
|
|
import { UserService } from 'src/modules/objects/user/user.service';
|
|
import { FormUtilityService } from 'src/modules/utility/services/form-utility.service';
|
|
import { SettingsService } from './settings.service';
|
|
|
|
@Controller('/account')
|
|
export class SettingsController {
|
|
constructor(
|
|
private readonly _service: SettingsService,
|
|
private readonly _form: FormUtilityService,
|
|
private readonly _upload: UploadService,
|
|
private readonly _user: UserService,
|
|
) {}
|
|
|
|
@Get()
|
|
@Redirect('/account/general')
|
|
public redirectGeneral() {
|
|
return;
|
|
}
|
|
|
|
@Get('general')
|
|
@Render('settings/general')
|
|
public general(@Req() req: Request, @Session() sess: SessionData) {
|
|
return this._form.populateTemplate(req, sess, { user: req.user });
|
|
}
|
|
|
|
@Post('avatar')
|
|
@UseInterceptors(FileInterceptor('file'))
|
|
async uploadAvatarFile(
|
|
@Req() req: Request,
|
|
@UploadedFile() file: Express.Multer.File,
|
|
) {
|
|
if (req.body.csrf !== req.session.csrf) {
|
|
throw new BadRequestException('Invalid session. Please try again.');
|
|
}
|
|
|
|
if (!file) {
|
|
throw new BadRequestException('Avatar upload failed');
|
|
}
|
|
|
|
try {
|
|
const matches = await this._upload.checkImageAspect(file);
|
|
if (!matches) {
|
|
throw new BadRequestException(
|
|
'Avatar should be with a 1:1 aspect ratio.',
|
|
);
|
|
}
|
|
} catch (e) {
|
|
await unlink(file.path);
|
|
throw e;
|
|
}
|
|
|
|
const upload = await this._upload.registerUploadedFile(file, req.user);
|
|
await this._user.updateAvatar(req.user, upload);
|
|
return {
|
|
file: upload.file,
|
|
};
|
|
}
|
|
}
|