52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
import {
|
|
Controller,
|
|
Delete,
|
|
Headers,
|
|
HttpCode,
|
|
Post,
|
|
Req,
|
|
UseGuards,
|
|
} from '@nestjs/common';
|
|
import { FastifyRequest } from 'fastify';
|
|
import { ApiError } from '../common/filters/api-error';
|
|
import { toUserResponse, UserResponse } from '../users/dto/user.response';
|
|
import { AuthGuard } from './auth.guard';
|
|
import { AuthService } from './auth.service';
|
|
|
|
interface SessionResponse {
|
|
token: string;
|
|
token_type: 'Bearer';
|
|
expires_at: string;
|
|
user: UserResponse;
|
|
}
|
|
|
|
@Controller('api/v1/auth/sessions')
|
|
export class AuthController {
|
|
constructor(private readonly auth: AuthService) {}
|
|
|
|
@Post()
|
|
@HttpCode(201)
|
|
async create(
|
|
@Headers('authorization') authorization: string | undefined,
|
|
@Req() request: FastifyRequest,
|
|
): Promise<SessionResponse> {
|
|
if (request.body !== undefined) {
|
|
throw new ApiError('invalid_request', 'request body is not allowed');
|
|
}
|
|
const session = await this.auth.login(authorization);
|
|
return {
|
|
token: session.token,
|
|
token_type: 'Bearer',
|
|
expires_at: session.expiresAt.toISOString(),
|
|
user: toUserResponse(session.user),
|
|
};
|
|
}
|
|
|
|
@Delete('current')
|
|
@HttpCode(204)
|
|
@UseGuards(AuthGuard)
|
|
async revoke(@Req() request: FastifyRequest): Promise<void> {
|
|
await this.auth.revoke(request.sessionTokenHash!);
|
|
}
|
|
}
|