feat(api): API tokens for authentication

Create and managed simple API tokens for access to the API from external
tools.
This commit is contained in:
Julian Tölle 2023-02-19 16:16:34 +01:00
parent eda89716ef
commit 8f7eebb806
15 changed files with 614 additions and 154 deletions

View file

@ -1,19 +1,25 @@
import {
Body,
Controller,
Delete,
Get,
Post,
Res,
UseFilters,
UseGuards,
} from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { ApiBody, ApiTags } from "@nestjs/swagger";
import type { Response } from "express";
import { User } from "../users/user.entity";
import { ApiToken } from "./api-token.entity";
import { AuthSession } from "./auth-session.entity";
import { AuthService } from "./auth.service";
import { COOKIE_REFRESH_TOKEN } from "./constants";
import { AuthAccessToken } from "./decorators/auth-access-token.decorator";
import { ReqUser } from "./decorators/req-user.decorator";
import { CreateApiTokenRequestDto } from "./dto/create-api-token-request.dto";
import { RefreshAccessTokenResponseDto } from "./dto/refresh-access-token-response.dto";
import { RevokeApiTokenRequestDto } from "./dto/revoke-api-token-request.dto";
import {
RefreshTokenAuthGuard,
SpotifyAuthGuard,
@ -55,4 +61,30 @@ export class AuthController {
return { accessToken };
}
@Post("api-tokens")
@ApiBody({ type: CreateApiTokenRequestDto })
@AuthAccessToken()
async createApiToken(
@ReqUser() user: User,
@Body("description") description: string
): Promise<ApiToken> {
return this.authService.createApiToken(user, description);
}
@Get("api-tokens")
@AuthAccessToken()
async listApiTokens(@ReqUser() user: User): Promise<ApiToken[]> {
return this.authService.listApiTokens(user);
}
// This endpoint does not validate that the token belongs to the logged in user.
// Once the token is known, it does not matter which account makes the actual
// request to revoke it.
@Delete("api-tokens")
@ApiBody({ type: RevokeApiTokenRequestDto })
@AuthAccessToken()
async revokeApiToken(@Body("token") token: string): Promise<void> {
return this.authService.revokeApiToken(token);
}
}