98 lines
2.6 KiB
TypeScript
98 lines
2.6 KiB
TypeScript
|
import {
|
||
|
Body,
|
||
|
Controller,
|
||
|
Get,
|
||
|
Post,
|
||
|
Query,
|
||
|
Render,
|
||
|
Req,
|
||
|
Res,
|
||
|
Session,
|
||
|
} from '@nestjs/common';
|
||
|
import { Request, Response } from 'express';
|
||
|
import { SessionData } from 'express-session';
|
||
|
import { UserService } from 'src/modules/objects/user/user.service';
|
||
|
import { FormUtilityService } from 'src/modules/utility/services/form-utility.service';
|
||
|
import { RegisterDto } from './register.interfaces';
|
||
|
|
||
|
@Controller('/register')
|
||
|
export class RegisterController {
|
||
|
constructor(
|
||
|
private readonly userService: UserService,
|
||
|
private readonly formUtil: FormUtilityService,
|
||
|
) {}
|
||
|
|
||
|
@Get()
|
||
|
@Render('register')
|
||
|
public registerView(
|
||
|
@Session() session: SessionData,
|
||
|
@Req() req: Request,
|
||
|
): Record<string, any> {
|
||
|
return this.formUtil.populateTemplate(req, session);
|
||
|
}
|
||
|
|
||
|
@Post()
|
||
|
public async registerRequest(
|
||
|
@Req() req: Request,
|
||
|
@Res() res: Response,
|
||
|
@Body() body: RegisterDto,
|
||
|
@Query() query: { redirectTo?: string },
|
||
|
) {
|
||
|
const { username, display_name, email, password, password_repeat } = body;
|
||
|
|
||
|
try {
|
||
|
if (
|
||
|
!username ||
|
||
|
!display_name ||
|
||
|
!email ||
|
||
|
!password ||
|
||
|
!password_repeat
|
||
|
) {
|
||
|
throw new Error('Please fill out all of the fields!');
|
||
|
}
|
||
|
|
||
|
if (!username || !username.match(this.formUtil.usernameRegex)) {
|
||
|
throw new Error(
|
||
|
'Username must be alphanumeric and between 3 to 26 characters long (_, - and . are also allowed)',
|
||
|
);
|
||
|
}
|
||
|
|
||
|
if (display_name.length < 3 || display_name.length > 32) {
|
||
|
throw new Error(
|
||
|
'Display name must be between 3 and 32 characters long.',
|
||
|
);
|
||
|
}
|
||
|
|
||
|
// https://stackoverflow.com/a/21456918
|
||
|
if (!password.match(this.formUtil.passwordRegex)) {
|
||
|
throw new Error(
|
||
|
'Password must be at least 8 characters long, contain a capital and lowercase letter and a number',
|
||
|
);
|
||
|
}
|
||
|
|
||
|
if (!email.match(this.formUtil.emailRegex)) {
|
||
|
throw new Error('Invalid email address!');
|
||
|
}
|
||
|
|
||
|
if (password !== password_repeat) {
|
||
|
throw new Error('The passwords do not match!');
|
||
|
}
|
||
|
|
||
|
await this.userService.userRegistration(body);
|
||
|
|
||
|
req.flash('message', {
|
||
|
error: false,
|
||
|
text: `An activation email has been sent to ${email}!`,
|
||
|
});
|
||
|
|
||
|
res.redirect(
|
||
|
'/login' + (query.redirectTo ? '?redirectTo=' + query.redirectTo : ''),
|
||
|
);
|
||
|
} catch (e: any) {
|
||
|
req.flash('message', { error: true, text: e.message });
|
||
|
req.flash('form', { ...body, password_repeat: undefined });
|
||
|
res.redirect(req.originalUrl);
|
||
|
}
|
||
|
}
|
||
|
}
|