-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogin+api.ts
More file actions
85 lines (74 loc) · 2.05 KB
/
login+api.ts
File metadata and controls
85 lines (74 loc) · 2.05 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
import crypto from 'node:crypto';
import bcrypt from 'bcryptjs';
import { createSessionInsecure } from '../../../database/sessions';
import { getUserWithPasswordHashInsecure } from '../../../database/users';
import { ExpoApiResponse } from '../../../ExpoApiResponse';
import {
type User,
userSchemaLogin,
} from '../../../migrations/00002-createTableUsers';
import { createSerializedSessionTokenCookie } from '../../../util/cookies';
import { getCombinedErrorMessage } from '../../../util/validation';
export type LoginResponseBodyPost =
| {
user: User;
}
| {
error: string;
};
export async function POST(
request: Request,
): Promise<ExpoApiResponse<LoginResponseBodyPost>> {
const requestBody = await request.json();
const result = userSchemaLogin.safeParse(requestBody);
if (!result.success) {
return ExpoApiResponse.json(
{ error: getCombinedErrorMessage(result.error.issues) },
{ status: 400 },
);
}
const userWithPasswordHash = await getUserWithPasswordHashInsecure(
result.data.user.username,
);
if (!userWithPasswordHash) {
return ExpoApiResponse.json(
{ error: 'Username or password invalid' },
{ status: 401 },
);
}
const isPasswordValid = await bcrypt.compare(
result.data.user.password,
userWithPasswordHash.passwordHash,
);
userWithPasswordHash.passwordHash = '';
if (!isPasswordValid) {
return ExpoApiResponse.json(
{ error: 'Username or password invalid' },
{ status: 401 },
);
}
const sessionToken = crypto.randomBytes(100).toString('base64');
const session = await createSessionInsecure(
sessionToken,
userWithPasswordHash.id,
);
if (!session) {
return ExpoApiResponse.json(
{ error: 'Session creation failed' },
{ status: 500 },
);
}
return ExpoApiResponse.json(
{
user: {
id: userWithPasswordHash.id,
username: userWithPasswordHash.username,
},
},
{
headers: {
'Set-Cookie': createSerializedSessionTokenCookie(session.token),
},
},
);
}