-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthHelper.ts
More file actions
91 lines (78 loc) · 2.2 KB
/
Copy pathAuthHelper.ts
File metadata and controls
91 lines (78 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
export class AuthHelper {
constructor(private readonly app: INestApplication<App>) {}
/**
* Signs up a user through Better Auth API and returns session cookies
*/
async signUpUser(userData: {
email: string;
password: string;
name: string;
}): Promise<string[]> {
const response = await request(this.app.getHttpServer())
.post('/api/auth/sign-up/email')
.send(userData)
.expect(200);
const cookies = response.get('Set-Cookie');
if (!cookies) {
throw new Error('No cookies returned from sign up');
}
return cookies;
}
/**
* Signs in a user through Better Auth API and returns session cookies
*/
async signInUser(credentials: {
email: string;
password: string;
}): Promise<string[]> {
const response = await request(this.app.getHttpServer())
.post('/api/auth/sign-in/email')
.send(credentials)
.expect(200);
const cookies = response.get('Set-Cookie');
if (!cookies) {
throw new Error('No cookies returned from sign in');
}
return cookies;
}
/**
* Creates a test user and returns session cookies for authentication
*/
async createAuthenticatedUser(userData: {
email: string;
password: string;
name: string;
}): Promise<string[]> {
return await this.signUpUser(userData);
}
/**
* Extracts session token from Better Auth cookies
*/
extractSessionToken(cookies: string[]): string | null {
for (const cookie of cookies) {
if (cookie.includes('better-auth.session_token=')) {
const match = cookie.match(/better-auth\.session_token=([^;]+)/);
return match ? match[1] : null;
}
}
return null;
}
/**
* Makes an authenticated request with Better Auth session cookies
*/
makeAuthenticatedRequest(
method: 'get' | 'post' | 'put' | 'delete' | 'patch',
url: string,
cookies: string[],
) {
const req = request(this.app.getHttpServer())[method](url);
// Set all cookies from the response
cookies.forEach((cookie) => {
req.set('Cookie', cookie);
});
return req;
}
}