-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathauth.helpers.ts
More file actions
84 lines (72 loc) · 2.14 KB
/
Copy pathauth.helpers.ts
File metadata and controls
84 lines (72 loc) · 2.14 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
import type { AuthenticationResponse, User } from "@workos-inc/node";
import { APIError } from "encore.dev/api";
import { getAuthData } from "~encore/auth";
import { hasPermission, mapRole, type Permission } from "./permissions";
export interface UserInfo {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
profilePictureUrl: string | null;
}
export function toUserInfo(user: User): UserInfo {
return {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
profilePictureUrl: user.profilePictureUrl,
};
}
export function toAuthResult(response: AuthenticationResponse) {
return {
accessToken: response.accessToken,
refreshToken: response.refreshToken,
user: toUserInfo(response.user),
};
}
interface OauthError extends Error {
name: "OauthException";
error?: string;
rawData?: Record<string, unknown>;
}
export function isOauthException(error: unknown): error is OauthError {
return error instanceof Error && error.name === "OauthException";
}
export function getPendingToken(error: OauthError): string | undefined {
return error.rawData?.pending_authentication_token as string | undefined;
}
export function handleWorkOSError(
error: unknown,
fallbackMessage: string,
): never {
if (error instanceof APIError) {
throw error;
}
if (error instanceof Error && "status" in error) {
const status = (error as Error & { status?: number }).status;
if (status === 401) {
throw APIError.unauthenticated("Invalid email or password");
}
if (status === 409) {
throw APIError.alreadyExists("A user with this email already exists");
}
if (status === 422) {
throw APIError.invalidArgument(error.message);
}
if (status === 429) {
throw APIError.resourceExhausted("Too many requests");
}
}
throw APIError.internal(fallbackMessage);
}
export function requirePermission(permission: Permission): void {
const authData = getAuthData();
if (!authData) {
throw APIError.unauthenticated("Not authenticated");
}
const role = mapRole(authData.role);
if (!hasPermission(role, permission)) {
throw APIError.permissionDenied(`Missing permission: ${permission}`);
}
}