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 {
|
|
|
|
ErrorResponse,
|
|
|
|
LoginResponse,
|
2022-08-23 22:15:01 +02:00
|
|
|
RefreshResponse,
|
|
|
|
SignupResponse
|
2022-08-17 21:59:51 +02:00
|
|
|
} 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
|
2022-08-23 22:15:01 +02:00
|
|
|
): Promise<SignupResponse | ErrorResponse> {
|
2022-08-17 21:59:51 +02:00
|
|
|
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
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|