forked from mtusi2026/mtusi2026lab2
feat: add basic auth
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
|
||||
export const PASSWORD = 'Correct-Horse-Battery-42';
|
||||
|
||||
export interface TestUser {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export async function createTestApp(): Promise<{
|
||||
app: INestApplication;
|
||||
server: any;
|
||||
}> {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
const app = moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
configureApp(app);
|
||||
await app.listen(0, '127.0.0.1');
|
||||
return { app, server: app.getHttpServer() };
|
||||
}
|
||||
|
||||
export function basic(username: string, password: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
export function bearer(user: TestUser): string {
|
||||
return `Bearer ${user.token}`;
|
||||
}
|
||||
|
||||
export async function login(
|
||||
server: any,
|
||||
username: string,
|
||||
password = PASSWORD,
|
||||
): Promise<string> {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(username, password))
|
||||
.expect(201);
|
||||
return res.body.token;
|
||||
}
|
||||
|
||||
export async function registerUser(
|
||||
server: any,
|
||||
label: string,
|
||||
): Promise<TestUser> {
|
||||
const username = `u_${label}_${randomUUID().slice(0, 8)}`;
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: `User ${label}`, password: PASSWORD })
|
||||
.expect(201);
|
||||
return { id: res.body.id, username, token: await login(server, username) };
|
||||
}
|
||||
Reference in New Issue
Block a user