59 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-08-17 21:59:51 +02:00
import {
BadRequestException,
Body,
Controller,
HttpCode,
Post,
Request,
UseGuards
} from '@nestjs/common';
import { AuthService } from '../services/auth';
import { AuthGuard } from '@nestjs/passport';
import { Public } from '../authguards';
import {
BaseResponse,
ErrorResponse,
LoginResponse,
RefreshResponse
} from 'dto';
@Controller('api/auth')
export default class AuthController {
constructor(private authService: AuthService) {}
@Public()
@UseGuards(AuthGuard('local'))
@Post('login')
@HttpCode(200)
async login(@Request() req): Promise<LoginResponse> {
return {
statusCode: 200,
jwt: await this.authService.login(req.user)
};
}
@Public()
@Post('signup')
async signup(
@Body('username') username,
@Body('password') password
): Promise<BaseResponse | ErrorResponse> {
if ((await this.authService.findUser(username)) != null)
throw new BadRequestException('Username already taken');
await this.authService.signup(username, password);
return {
statusCode: 200
};
}
@Post('refresh')
async refresh(@Request() req): Promise<RefreshResponse | ErrorResponse> {
const token = await this.authService.login(req.user);
await this.authService.revoke(req.token);
return {
statusCode: 200,
jwt: token
};
}
}