aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Effect/authCookie.ts
blob: f407216ee2f66090ea8b8def64e6a5e542e27585 (plain) (blame)
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
import type { AniListAuthorisation } from "$lib/Data/AniList/identity";
import { Effect, Result, Schema } from "effect";

const UserCookieSchema = Schema.Struct({
	token_type: Schema.NonEmptyString,
	expires_in: Schema.Number,
	access_token: Schema.NonEmptyString,
	refresh_token: Schema.NonEmptyString,
});

export const decodeAuthCookieEffect = (cookie: string) =>
	Effect.gen(function* () {
		const parsedCookie = yield* Effect.try({
			try: () => JSON.parse(cookie) as unknown,
			catch: (cause) => new Error("Invalid user cookie JSON", { cause }),
		});
		const decodedCookie = yield* Effect.try({
			try: () => Schema.decodeUnknownSync(UserCookieSchema)(parsedCookie),
			catch: (cause) => new Error("Invalid user cookie payload", { cause }),
		});

		return {
			tokenType: decodedCookie.token_type,
			expiresIn: decodedCookie.expires_in,
			accessToken: decodedCookie.access_token,
			refreshToken: decodedCookie.refresh_token,
		} as AniListAuthorisation;
	});

export const decodeAuthCookieEither = (cookie: string) =>
	Result.try({
		try: () => Effect.runSync(decodeAuthCookieEffect(cookie)),
		catch: (cause) =>
			cause instanceof Error
				? cause
				: new Error("Failed to decode user cookie", { cause }),
	});

export const decodeAuthCookieOrThrow = (
	cookie: string,
): AniListAuthorisation => {
	const decoded = decodeAuthCookieEither(cookie);

	return Result.getOrThrow(decoded);
};

export const decodeAuthCookieOrNull = (
	cookie: string,
): AniListAuthorisation | null => {
	const decoded = decodeAuthCookieEither(cookie);

	return Result.isSuccess(decoded) ? decoded.success : null;
};