-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoginView.vue
More file actions
329 lines (292 loc) · 10.9 KB
/
Copy pathLoginView.vue
File metadata and controls
329 lines (292 loc) · 10.9 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
<template>
<section class="flex flex-col justify-between items-center h-screen w-screen">
<logo class="my-10" only-logo />
<template v-if="!isLogin">
<div class="text-center w-80">
<p class="text-gray-900 dark:text-white text-3xl">Welcome to Subturtle!</p>
<p class="text-gray-700 dark:text-gray-300 font-thin text-xs mt-2">
Choose your preferred method to log in or register.
</p>
</div>
<div class="mb-20 flex flex-col space-y-2">
<!-- Login with Chrome -->
<button
:disabled="!chromeUserRes || !chromeUserRes.token || pending"
class="flex items-center justify-center text-gray-900 dark:text-white bg-gray-100 dark:bg-gray-800 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
@click="loginWithChrome"
>
<div
class="p-2 py-3 flex justify-center items-center border-r-[1px] border-gray-300 dark:border-gray-700"
>
<span class="i-logos-chrome" />
</div>
<div class="flex-1 text-left px-4">With Current Chrome User</div>
</button>
<!-- Login with Google -->
<button
:disabled="pending"
@click="loginWithGoogle"
class="flex items-center justify-center text-gray-900 dark:text-white bg-gray-100 dark:bg-gray-800 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
<div
class="p-2 py-3 flex justify-center items-center border-r-[1px] border-gray-300 dark:border-gray-700"
>
<span class="i-flat-color-icons-google" />
</div>
<div class="flex-1 text-left px-4">With Google Account</div>
</button>
<!-- Login with Email & Password (dev/agent only, gated by ENABLE_PASSWORD_AUTH at build time) -->
<template v-if="enablePasswordAuth">
<button
v-if="!passwordFormOpen"
:disabled="pending"
@click="passwordFormOpen = true"
data-testid="open-password-form"
class="flex items-center justify-center text-gray-900 dark:text-white bg-gray-100 dark:bg-gray-800 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
<div
class="p-2 py-3 flex justify-center items-center border-r-[1px] border-gray-300 dark:border-gray-700"
>
<span class="i-flat-color-icons-key" />
</div>
<div class="flex-1 text-left px-4">With Email & Password</div>
</button>
<form
v-else
@submit.prevent="loginWithPassword"
data-testid="password-form"
class="flex flex-col space-y-2 bg-gray-100 dark:bg-gray-800 rounded-md p-3"
>
<input
v-model="passwordEmail"
type="email"
autocomplete="email"
required
placeholder="Email"
data-testid="password-email"
:disabled="pending"
class="px-3 py-2 rounded text-gray-900 dark:text-white bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
/>
<input
v-model="passwordValue"
type="password"
autocomplete="current-password"
required
placeholder="Password"
data-testid="password-value"
:disabled="pending"
class="px-3 py-2 rounded text-gray-900 dark:text-white bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
/>
<p
v-if="loginError"
data-testid="password-error"
class="text-red-600 dark:text-red-400 text-xs"
>
{{ loginError }}
</p>
<div class="flex space-x-2">
<button
type="button"
@click="closePasswordForm"
:disabled="pending"
data-testid="password-cancel"
class="px-3 py-2 rounded text-gray-700 dark:text-gray-200 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 disabled:opacity-50"
>
Back
</button>
<button
type="submit"
:disabled="pending || !isPasswordFormValid"
data-testid="password-submit"
class="flex-1 px-3 py-2 rounded text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ pending ? "Signing in…" : "Sign in" }}
</button>
</div>
</form>
</template>
</div>
</template>
<template v-else>
<div class="text-center w-80">
<p class="text-gray-900 dark:text-white text-3xl">Logged In Successfully!</p>
<p class="text-gray-700 dark:text-gray-300 font-thin text-base mt-4">
Go ahead and close this window, your adventure starts now!
</p>
</div>
<button class="mb-20 text-gray-700 dark:text-gray-200 mt-10 text-lg" @click="closeWindow">
Close
</button>
</template>
</section>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import {
GetCurrentChromeUserToken,
LoginStatusResponse,
StoreUserTokenMessage,
} from "../../common/types/messaging";
import { sendMessage, sendMessageToTabs } from "../../common/helper/massage";
import { analytic } from "../../plugins/mixpanel";
import { get } from "../helper/http";
import { joinToBaseUrl } from "../../common/helper/url";
import {
authentication,
loginWithLastSession,
isLogin,
} from "../../plugins/modular-rest";
const pending = ref(false);
const chromeUserRes = ref<LoginStatusResponse | null>();
// Build-flag gated: dev/agent-only password form. Stable/prod builds omit the
// key in .env.production so this resolves to false and the form is hidden.
const enablePasswordAuth = process.env.ENABLE_PASSWORD_AUTH === "true";
const passwordFormOpen = ref(false);
const passwordEmail = ref("");
const passwordValue = ref("");
const loginError = ref<string | null>(null);
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isPasswordFormValid = computed(
() =>
emailRegex.test(passwordEmail.value.trim()) &&
passwordValue.value.length >= 8
);
onMounted(async () => {
chromeUserRes.value = await sendMessage<LoginStatusResponse>(
new GetCurrentChromeUserToken()
).catch((err) => null);
});
async function loginWithChrome() {
pending.value = true;
if (GetCurrentChromeUserToken.checkResponse(chromeUserRes)) {
const url = joinToBaseUrl(
`/auth/google/token-login?token=${chromeUserRes.token}`
);
const { status, token } = await get(url, {
token: chromeUserRes.token,
}).catch((err) => {
console.log("err", err);
return { status: "error", token: null };
});
if (status == "success") {
await handleTokenLogin(token);
}
}
pending.value = false;
}
async function loginWithGoogle() {
pending.value = true;
await authorizeFromGoogleOAuthThroughAuthFlowAPI()
.then((accessToken) => {
return get(
joinToBaseUrl(
`/auth/google/access-token-login?access_token=${accessToken}`
)
);
})
.then(({ token }) => handleTokenLogin(token))
.catch((err) => {
console.log("err", err);
})
.finally(() => {
pending.value = false;
});
}
function authorizeFromGoogleOAuthThroughAuthFlowAPI() {
const redirectURL = chrome.identity.getRedirectURL();
console.log("redirectURL", redirectURL);
// Client ID of web application (from Google Developer Console), not google extension.
// Remove the ".apps.googleusercontent.com" part from the client ID
// Ref: https://developers.google.com/identity/sign-in/web/server-side-flow#step_3_initialize_the_googleauth_object
//
const clientID = process.env.GOOGLE_OAUTH_CLIENT_ID;
const scopes = ["openid", "email", "profile"];
let authURL = "https://accounts.google.com/o/oauth2/auth";
authURL += `?client_id=${clientID}`;
authURL += `&response_type=token`;
authURL += `&redirect_uri=${encodeURIComponent(redirectURL)}`;
authURL += `&scope=${encodeURIComponent(scopes.join(" "))}`;
return launchWebAuthFlow(authURL);
}
async function handleTokenLogin(token: string) {
const message = new StoreUserTokenMessage(token);
await sendMessage(message);
sendMessageToTabs(message);
await loginWithLastSession();
// Fired only on an explicit login from this view — session restores on
// startup do not pass through here.
analytic.track("user_logged-in");
}
function launchWebAuthFlow(authURL) {
return new Promise<string>((resolve, reject) => {
chrome.identity.launchWebAuthFlow(
{
interactive: true,
url: authURL,
},
(responseUrl) => {
console.log("responseUrl", responseUrl);
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(responseUrl as string);
}
}
);
}).then((responseUrl: string) => {
const url = new URL(responseUrl);
const hash = url.hash.substr(1);
const params = new URLSearchParams(hash);
const access_token = params.get("access_token");
if (access_token) {
return access_token;
} else {
throw new Error("No access_token found");
}
});
}
async function loginWithPassword() {
if (!isPasswordFormValid.value) return;
pending.value = true;
loginError.value = null;
try {
await authentication.login(
{
idType: "email",
id: passwordEmail.value.trim(),
password: passwordValue.value,
},
true
);
const token = authentication.getToken;
if (!token) {
loginError.value = "Invalid email or password.";
return;
}
await handleTokenLogin(token);
passwordValue.value = "";
} catch (err: any) {
// modular-rest rejects with the server response or a network error. We
// surface a generic message for the credential-mismatch case so we don't
// leak whether the email exists, and a network-specific message when the
// request never reached the server.
if (err instanceof TypeError || err?.message?.includes("Failed to fetch")) {
loginError.value = "Could not reach the server.";
} else if (err?.status === false || err?.error) {
loginError.value = "Invalid email or password.";
} else {
loginError.value = "Something went wrong. Please try again.";
}
} finally {
pending.value = false;
}
}
function closePasswordForm() {
passwordFormOpen.value = false;
passwordValue.value = "";
loginError.value = null;
}
function closeWindow() {
window.close();
}
</script>