This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
/
google.ts
156 lines (123 loc) · 4.22 KB
/
google.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
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
import { decodeBase64Url } from 'std/encoding/base64url.ts';
import 'std/dotenv/load.ts';
import { baseUrl, isRunningLocally, PORT } from '/lib/utils.ts';
import { createNewUser, getUserByEmail } from '/lib/data-utils.ts';
import { createSession, dataToText } from '/lib/auth.ts';
const GOOGLE_OAUTH_CLIENT_ID = Deno.env.get('GOOGLE_OAUTH_CLIENT_ID') || '';
const GOOGLE_OAUTH_CLIENT_SECRET = Deno.env.get('GOOGLE_OAUTH_CLIENT_SECRET') || '';
interface GoogleOauthExtraState {
redirectTo?: string;
}
interface OAuthUrlOptions {
requestPermissions: string[];
match: URLPatternResult;
redirectUrlPath?: string;
requestingForOfflineUse?: boolean;
extraState?: GoogleOauthExtraState;
}
export function getGoogleOauthUrl(
{
requestPermissions,
match,
redirectUrlPath = '/oauth/google/callback',
requestingForOfflineUse = false,
extraState = {},
}: OAuthUrlOptions,
) {
const state = {
...extraState,
random: Math.random(),
};
const redirectUrl = `${isRunningLocally(match) ? `http://localhost:${PORT}` : baseUrl}${redirectUrlPath}`;
// NOTE: More info on the parameters at https://developers.google.com/identity/protocols/oauth2/native-app
const params = {
client_id: GOOGLE_OAUTH_CLIENT_ID,
redirect_uri: redirectUrl,
response_type: 'code',
include_granted_scopes: 'true',
prompt: 'select_account',
access_type: requestingForOfflineUse ? 'offline' : 'online',
state: btoa(JSON.stringify(state)),
scope: requestPermissions.join(' '),
};
const searchParams = new URLSearchParams(params);
const googleOauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${searchParams.toString()}`;
return googleOauthUrl;
}
interface GoogleJwtIdToken {
email?: string;
name?: string;
picture?: string;
locale?: string;
sub?: string;
email_verified?: boolean;
given_name?: string;
family_name?: string;
}
interface GoogleOAuthResponse {
access_token: string;
refresh_token?: string; // We only get it on the first "offline" authorization
expires_in: number;
token_type: 'Bearer';
scope: string;
id_token: string;
}
function decodeGoogleJwt(jwt: string) {
const jwtParts = jwt.split('.');
if (jwtParts.length !== 3) {
throw new Error('Malformed JWT');
}
return JSON.parse(dataToText(decodeBase64Url(jwtParts[1]))) as GoogleJwtIdToken;
}
function parseGoogleOauthState(state: string) {
let stateParams: GoogleOauthExtraState = {};
try {
stateParams = JSON.parse(atob(state));
} catch (error) {
console.log(`Failed to parse Google OAuth state: ${error}`);
console.error(error);
}
return stateParams;
}
export async function validateGoogleOauthAndCreateSession(request: Request, match: URLPatternResult) {
const urlSearchParams = new URL(request.url).searchParams;
const code = urlSearchParams.get('code');
if (!code) {
throw new Error('Missing OAuth "code" parameter');
}
const redirectUrl = `${isRunningLocally(match) ? `http://localhost:${PORT}` : baseUrl}/oauth/google/callback`;
const params = {
code,
client_id: GOOGLE_OAUTH_CLIENT_ID,
client_secret: GOOGLE_OAUTH_CLIENT_SECRET,
redirect_uri: redirectUrl,
grant_type: 'authorization_code',
};
const searchParams = new URLSearchParams(params);
// Get info from Google
const googleOauthResponse = await fetch(`https://oauth2.googleapis.com/token?${searchParams.toString()}`, {
method: 'POST',
});
const { id_token } = (await googleOauthResponse.json()) as GoogleOAuthResponse;
if (!id_token) {
throw new Error('Invalid Google OAuth Response');
}
const { email, name, given_name, family_name } = decodeGoogleJwt(id_token);
if (!email) {
throw new Error('Missing user/email');
}
const normalizedEmail = email.toLowerCase().trim();
// Confirm the user exists (or signup)
let user = await getUserByEmail(normalizedEmail);
if (!user) {
user = await createNewUser(normalizedEmail, name || `${given_name} ${family_name}`);
}
let urlToRedirectTo = '/dashboard';
if (urlSearchParams.has('state')) {
const state = parseGoogleOauthState(urlSearchParams.get('state')!);
if (state.redirectTo) {
urlToRedirectTo = state.redirectTo;
}
}
return createSession(request, match, user, { urlToRedirectTo });
}