-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path+page.server.ts
57 lines (52 loc) · 2 KB
/
+page.server.ts
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
import { CONTENTFUL_MANAGEMENT_API_ENDPOINT } from "$env/static/private";
import tokenDuration from "$lib/constants/tokenDuration.js";
import getContentfulManagementClient from "$lib/services/server/contentfulManagement";
import getErrorMessage from "$lib/util/getErrorMessage.js";
import { error, fail } from "@sveltejs/kit";
export const actions = {
default: async ({ request, locals, cookies, fetch }) => {
const data = await request.formData();
if (cookies.get("ldafUserToken")) {
return fail(400, { success: false, message: "You are already logged in!" });
}
const managementAPIToken = data.get("token");
if (typeof managementAPIToken !== "string") {
return fail(400, { success: false, message: "Token must be a string" });
}
const { getKVClient } = locals;
const contentfulManagementClient = getContentfulManagementClient({
fetch,
token: managementAPIToken,
apiEndpoint: CONTENTFUL_MANAGEMENT_API_ENDPOINT,
});
try {
const [kvClient, currentUser] = await Promise.all([
getKVClient(),
contentfulManagementClient.getCurrentUser(),
]);
if (!kvClient) {
const message = "Could not log in: Redis client failed to initialize";
throw error(500, { message, status: 500 });
}
locals.currentUser = currentUser;
const ldafUserToken = crypto.randomUUID();
await kvClient.setUserInfoByToken(ldafUserToken, {
...locals.currentUser,
managementAPIToken,
});
cookies.set("ldafUserToken", ldafUserToken, {
maxAge: tokenDuration,
sameSite: "none",
path: "/",
});
return { success: true, currentUser: locals.currentUser };
} catch (err) {
const message = `Could not save token: ${getErrorMessage(err) ?? "unknown error"}`;
const status =
err && typeof err === "object" && "status" in err && typeof err.status === "number"
? err.status
: 500;
throw error(status, { message, status });
}
},
};