-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcomplete-google-authorization.ts
More file actions
172 lines (146 loc) · 4.49 KB
/
complete-google-authorization.ts
File metadata and controls
172 lines (146 loc) · 4.49 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { Status } from "@core/errors/status.codes";
import {
type GoogleAuthCodeRequest,
GoogleConnectErrorResponseSchema,
} from "@core/types/auth.types";
import { type ApiError } from "@web/common/apis/api.types";
import { ROOT_ROUTES } from "@web/common/constants/routes";
import {
GOOGLE_AUTH_SCOPES_REQUIRED,
GOOGLE_AUTHORIZATION_ERROR_MESSAGE,
MISSING_GOOGLE_SCOPES_ERROR_MESSAGE,
} from "./google-authorization.constants";
import {
clearGoogleAuthorizationIntent,
readGoogleAuthorizationIntent,
} from "./google-authorization.storage";
import {
buildGoogleAuthCallbackUrl,
buildGoogleAuthCodePayload,
} from "./google-authorization.util";
type CompleteAuthentication = (input: {
email?: string;
onComplete?: () => void;
}) => Promise<void>;
export type GoogleAuthorizationAuthAdapter = {
connectGoogle(data: GoogleAuthCodeRequest): Promise<unknown>;
loginOrSignup(data: GoogleAuthCodeRequest): Promise<{
user: { emails?: string[] };
}>;
};
export type CompleteGoogleAuthorizationOptions = {
authApi: GoogleAuthorizationAuthAdapter;
completeAuthentication: CompleteAuthentication;
doesSessionExist?: () => Promise<boolean>;
refreshUserMetadata: () => Promise<void> | void;
requestEventFetch?: () => void;
search: string;
};
export type CompleteGoogleAuthorizationResult =
| {
returnPath: string;
status: "completed";
}
| {
message: string;
returnPath: string;
status: "failed";
};
const fail = (
message = GOOGLE_AUTHORIZATION_ERROR_MESSAGE,
returnPath = ROOT_ROUTES.DAY,
): CompleteGoogleAuthorizationResult => ({
message,
returnPath,
status: "failed",
});
const getApiError = (error: unknown): ApiError | undefined => {
if (typeof error !== "object" || error === null || !("response" in error)) {
return undefined;
}
return error as ApiError;
};
const parseGoogleConnectErrorMessage = (error: unknown): string | undefined => {
const data = getApiError(error)?.response?.data;
const parsed = GoogleConnectErrorResponseSchema.safeParse(data);
return parsed.success ? parsed.data.message : undefined;
};
const isUnauthorizedSessionError = (error: unknown): boolean => {
return getApiError(error)?.response?.status === Status.UNAUTHORIZED;
};
export async function completeGoogleAuthorization({
authApi,
completeAuthentication,
doesSessionExist,
refreshUserMetadata,
requestEventFetch,
search,
}: CompleteGoogleAuthorizationOptions): Promise<CompleteGoogleAuthorizationResult> {
const params = new URLSearchParams(search);
const state = params.get("state");
if (!state) {
return fail();
}
const savedIntent = readGoogleAuthorizationIntent(state);
clearGoogleAuthorizationIntent(state);
const returnPath = savedIntent?.returnPath ?? ROOT_ROUTES.DAY;
if (!savedIntent || params.get("error")) {
return fail(GOOGLE_AUTHORIZATION_ERROR_MESSAGE, returnPath);
}
const code = params.get("code");
if (!code) {
return fail(GOOGLE_AUTHORIZATION_ERROR_MESSAGE, returnPath);
}
const grantedScopes = new Set((params.get("scope") ?? "").split(" "));
const isMissingRequiredScope = GOOGLE_AUTH_SCOPES_REQUIRED.some(
(scope) => !grantedScopes.has(scope),
);
if (isMissingRequiredScope) {
return fail(MISSING_GOOGLE_SCOPES_ERROR_MESSAGE, returnPath);
}
const payload = buildGoogleAuthCodePayload({
code,
scope: params.get("scope") ?? undefined,
state,
redirectUri: buildGoogleAuthCallbackUrl(),
});
const completeGoogleSignIn = async () => {
const result = await authApi.loginOrSignup(payload);
await completeAuthentication({
email: result.user.emails?.[0],
});
};
try {
if (savedIntent.intent === "signIn") {
await completeGoogleSignIn();
} else {
const hasActiveSession = doesSessionExist
? await doesSessionExist()
: true;
if (!hasActiveSession) {
await completeGoogleSignIn();
} else {
try {
await authApi.connectGoogle(payload);
await refreshUserMetadata();
requestEventFetch?.();
} catch (error) {
if (!isUnauthorizedSessionError(error)) {
throw error;
}
await completeGoogleSignIn();
}
}
}
return {
returnPath,
status: "completed",
};
} catch (error) {
const parsedMessage = parseGoogleConnectErrorMessage(error);
if (parsedMessage) {
return fail(parsedMessage, returnPath);
}
return fail(GOOGLE_AUTHORIZATION_ERROR_MESSAGE, returnPath);
}
}