Evo.Auth/apps/api/src/account/account.controller.ts
2023-11-17 12:21:59 +03:00

103 lines
2.8 KiB
TypeScript

/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable class-methods-use-this */
/* eslint-disable import/no-extraneous-dependencies */
import { AccountService } from './account.service';
import { CreateAccountDto } from './dto/create-account.dto';
import {
Body,
Controller,
Delete,
Get,
HttpException,
HttpStatus,
Post,
Query,
Req,
Res,
UnauthorizedException,
} from '@nestjs/common';
import { ApiResponse, ApiTags } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify';
import { cookieOptions } from 'src/config/cookie';
import { env } from 'src/config/env';
import { Credentials } from 'src/dto/credentials';
import { Account } from 'src/schemas/account.schema';
@Controller('account')
@ApiTags('account')
export class AccountController {
constructor(private readonly accountService: AccountService) {}
private clearCookies(req, reply) {
if (req.cookies) {
Object.keys(req.cookies).forEach((cookieName) => {
reply.clearCookie(cookieName, {
path: '/',
});
});
}
}
@Post('/create')
@ApiResponse({
status: HttpStatus.CREATED,
type: Account,
})
async create(@Body() createAccountDto: CreateAccountDto, @Res() reply: FastifyReply) {
try {
const createdAccount = await this.accountService.create(createAccountDto);
return reply.status(HttpStatus.CREATED).send(createdAccount);
} catch (error) {
throw new HttpException(error, HttpStatus.BAD_REQUEST);
}
}
@Get()
async findAll() {
return this.accountService.findAll();
}
@Delete('/delete')
@ApiResponse({
status: HttpStatus.OK,
type: Account,
})
// @ApiQuery({ name: 'username', type: CreateAccountDto['username'] })
async delete(@Query('username') username: string) {
return this.accountService.delete(username);
}
@Post('/login')
async login(@Body() credentials: Credentials, @Res() reply: FastifyReply) {
try {
const token = await this.accountService.login(credentials);
return reply
.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions)
.status(200)
.send({ token });
} catch {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
}
@Get('/logout')
async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
this.clearCookies(req, reply);
return reply.status(302).redirect('/login');
}
@Get('/get-user')
async getUser(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
const token = req.cookies[env.COOKIE_TOKEN_NAME];
if (!token) throw new UnauthorizedException();
const account = await this.accountService.getUser(token);
if (!account) throw new UnauthorizedException('Account not found');
return reply.send(account);
}
}