forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirebaseAuth.vue
More file actions
491 lines (463 loc) · 12 KB
/
Copy pathFirebaseAuth.vue
File metadata and controls
491 lines (463 loc) · 12 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<script setup lang="ts">
import {
getAuth,
signInWithPopup,
GoogleAuthProvider,
GithubAuthProvider,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
sendPasswordResetEmail,
} from 'firebase/auth'
import { mdiGoogle, mdiGithub, mdiEmail } from '@mdi/js'
import type { User as FirebaseUser } from 'firebase/auth'
import { ErrorMessages } from '~/utils/errors'
const props = withDefaults(
defineProps<{
to?: string
}>(),
{ to: '/' },
)
const router = useRouter()
const authStore = useAuthStore()
const notificationsStore = useNotificationsStore()
const appStore = useAppStore()
const loading = ref(false)
const showEmailForm = ref(false)
const isSignUp = ref(false)
const showForgotPassword = ref(false)
const resetEmailSent = ref(false)
const email = ref('')
const password = ref('')
const generalError = ref('')
const errorMessages = ref(new ErrorMessages())
type LoginMethod = 'google' | 'github' | 'email'
const LAST_LOGIN_METHOD_KEY = 'httpsms_last_login_method'
const lastUsedMethod = ref<LoginMethod | null>(null)
onMounted(() => {
try {
const stored = localStorage.getItem(LAST_LOGIN_METHOD_KEY)
if (stored === 'google' || stored === 'github' || stored === 'email') {
lastUsedMethod.value = stored
}
} catch (error) {
console.error(error)
}
})
function clearErrors() {
errorMessages.value = new ErrorMessages()
generalError.value = ''
}
function validateEmail(): boolean {
clearErrors()
if (!email.value.trim()) {
errorMessages.value.add('email', 'Please provide an email address')
return false
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(email.value.trim())) {
errorMessages.value.add('email', 'Please enter a valid email address')
return false
}
return true
}
function validateLoginForm(): boolean {
clearErrors()
let valid = true
if (!email.value.trim()) {
errorMessages.value.add('email', 'Please provide an email address')
valid = false
} else {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(email.value.trim())) {
errorMessages.value.add('email', 'Please enter a valid email address')
valid = false
}
}
if (!password.value) {
errorMessages.value.add('password', 'Please enter your password')
valid = false
}
return valid
}
async function signInWithGoogle() {
loading.value = true
try {
const auth = getAuth()
const result = await signInWithPopup(auth, new GoogleAuthProvider())
onSuccess(result.user, 'google')
} catch (error: unknown) {
handleError(error, true)
} finally {
loading.value = false
}
}
async function signInWithGithub() {
loading.value = true
try {
const auth = getAuth()
const result = await signInWithPopup(auth, new GithubAuthProvider())
onSuccess(result.user, 'github')
} catch (error: unknown) {
handleError(error, true)
} finally {
loading.value = false
}
}
async function submitEmail() {
if (!validateLoginForm()) return
loading.value = true
try {
const auth = getAuth()
let result
if (isSignUp.value) {
result = await createUserWithEmailAndPassword(
auth,
email.value.trim(),
password.value,
)
} else {
result = await signInWithEmailAndPassword(
auth,
email.value.trim(),
password.value,
)
}
onSuccess(result.user, 'email')
} catch (error: unknown) {
handleError(error)
} finally {
loading.value = false
}
}
async function submitPasswordReset() {
if (!validateEmail()) return
loading.value = true
try {
const auth = getAuth()
await sendPasswordResetEmail(auth, email.value.trim())
resetEmailSent.value = true
} catch (error: unknown) {
handleError(error)
} finally {
loading.value = false
}
}
function showForgotPasswordForm() {
clearErrors()
resetEmailSent.value = false
showForgotPassword.value = true
}
function backToSignIn() {
clearErrors()
resetEmailSent.value = false
showForgotPassword.value = false
}
function onSuccess(user: FirebaseUser, method: LoginMethod) {
try {
localStorage.setItem(LAST_LOGIN_METHOD_KEY, method)
} catch (error) {
console.error(error)
}
notificationsStore.addNotification({
message: 'Login successful!',
type: 'success',
})
authStore.onAuthStateChanged(user)
router.push({ path: props.to })
}
function handleError(error: unknown, isSocial = false) {
const firebaseError = error as { code?: string; message?: string }
const code = firebaseError.code || ''
if (
code === 'auth/popup-closed-by-user' ||
code === 'auth/cancelled-popup-request'
) {
return
}
if (isSocial) {
const message = getGeneralErrorMessage(code, firebaseError.message)
notificationsStore.addNotification({ message, type: 'error' })
return
}
clearErrors()
switch (code) {
case 'auth/wrong-password':
errorMessages.value.add('password', 'Incorrect password')
break
case 'auth/invalid-credential':
errorMessages.value.add('email', 'Invalid email or password')
errorMessages.value.add('password', 'Invalid email or password')
break
case 'auth/user-not-found':
errorMessages.value.add(
'email',
'No account found with this email address',
)
break
case 'auth/invalid-email':
errorMessages.value.add('email', 'Please enter a valid email address')
break
case 'auth/email-already-in-use':
errorMessages.value.add(
'email',
'An account already exists with this email',
)
break
case 'auth/weak-password':
errorMessages.value.add(
'password',
'Password should be at least 6 characters',
)
break
case 'auth/user-disabled':
errorMessages.value.add('email', 'This account has been disabled')
break
case 'auth/too-many-requests':
generalError.value = 'Too many failed attempts. Please try again later'
break
case 'auth/network-request-failed':
generalError.value =
'Unable to connect to the server. Please check your internet connection'
break
case 'auth/missing-email':
errorMessages.value.add('email', 'Please provide an email address')
break
default:
generalError.value =
firebaseError.message || 'An unexpected error occurred'
}
}
function getGeneralErrorMessage(
code: string,
fallback: string | undefined,
): string {
switch (code) {
case 'auth/user-not-found':
return 'No account found with this email address'
case 'auth/wrong-password':
case 'auth/invalid-credential':
return 'The provided credentials are invalid.'
case 'auth/user-disabled':
return 'This account has been disabled'
case 'auth/too-many-requests':
return 'Too many failed attempts. Please try again later'
case 'auth/network-request-failed':
return 'Unable to connect to the server. Please check your internet connection'
default:
return fallback || 'An unexpected error occurred'
}
}
</script>
<template>
<div>
<v-btn
block
color="white"
size="large"
class="mb-3 position-relative"
:loading="loading"
:disabled="loading"
@click="signInWithGoogle"
>
<v-chip
v-if="lastUsedMethod === 'google'"
size="x-small"
color="primary"
label
variant="flat"
class="position-absolute last-used-chip"
>
Last Used
</v-chip>
<v-icon color="red" :icon="mdiGoogle" class="mr-2" />
Continue with Google
</v-btn>
<v-btn
block
size="large"
variant="flat"
color="black"
class="mb-3 position-relative"
:loading="loading"
:disabled="loading"
@click="signInWithGithub"
>
<v-chip
v-if="lastUsedMethod === 'github'"
label
size="x-small"
color="primary"
variant="flat"
class="position-absolute last-used-chip"
>
Last Used
</v-chip>
<v-icon :icon="mdiGithub" class="mr-2" />
Continue with GitHub
</v-btn>
<v-btn
v-if="!showEmailForm"
block
size="large"
variant="flat"
color="red"
class="mb-3 position-relative"
:disabled="loading"
@click="showEmailForm = true"
>
<v-chip
v-if="lastUsedMethod === 'email'"
label
size="x-small"
color="primary"
variant="flat"
class="position-absolute last-used-chip"
>
Last Used
</v-chip>
<v-icon :icon="mdiEmail" class="mr-2" />
Continue with email
</v-btn>
<!-- Forgot Password Form -->
<v-form
v-if="showEmailForm && showForgotPassword"
class="mt-4"
@submit.prevent="submitPasswordReset"
>
<template v-if="!resetEmailSent">
<p class="text-body-medium text-medium-emphasis mb-4">
Enter your email address to reset your password
</p>
<v-text-field
v-model="email"
label="Email Address"
color="primary"
type="email"
variant="outlined"
density="comfortable"
class="mb-2"
:error="errorMessages.has('email')"
:error-messages="errorMessages.get('email')"
/>
<v-alert
v-if="generalError"
type="error"
density="compact"
class="mb-3"
>
{{ generalError }}
</v-alert>
<v-btn
block
size="large"
color="primary"
type="submit"
:loading="loading"
>
Send Reset Link
</v-btn>
</template>
<template v-else>
<v-alert type="success" density="compact" class="mb-3">
Check your email for password reset instructions
</v-alert>
</template>
<v-btn
block
variant="text"
size="small"
color="warning"
class="mt-2"
@click="backToSignIn"
>
Back to Sign In
</v-btn>
</v-form>
<!-- Sign In / Sign Up Form -->
<v-form
v-if="showEmailForm && !showForgotPassword"
class="mt-4"
@submit.prevent="submitEmail"
>
<v-text-field
v-model="email"
label="Email Address"
color="primary"
type="email"
variant="outlined"
density="comfortable"
class="mb-2"
:error="errorMessages.has('email')"
:error-messages="errorMessages.get('email')"
/>
<v-text-field
v-model="password"
label="Password"
type="password"
color="primary"
variant="outlined"
density="comfortable"
class="mb-2"
:error="errorMessages.has('password')"
:error-messages="errorMessages.get('password')"
/>
<v-alert v-if="generalError" type="error" density="compact" class="mb-3">
{{ generalError }}
</v-alert>
<v-btn
v-if="!isSignUp"
variant="plain"
size="small"
color="primary"
class="mb-3 px-0 mt-n4"
@click="showForgotPasswordForm"
>
Forgot Password?
</v-btn>
<v-btn
block
size="large"
color="primary"
type="submit"
:loading="loading"
>
{{ isSignUp ? 'Sign Up' : 'Sign In' }}
</v-btn>
<v-btn
block
variant="plain"
size="small"
color="primary"
class="mt-2"
@click="isSignUp = !isSignUp"
>
{{
isSignUp ? 'Already have an account? Sign In' : 'No account? Sign Up'
}}
</v-btn>
</v-form>
<p class="text-body-small text-medium-emphasis mt-4">
By continuing, you are indicating that you accept our
<a
:href="appStore.appData.url + '/terms-and-conditions'"
class="text-decoration-none"
>
Terms of Service
</a>
and
<a
:href="appStore.appData.url + '/privacy-policy'"
class="text-decoration-none"
>
Privacy Policy.</a
>
</p>
</div>
</template>
<style scoped>
.last-used-chip {
top: -8px;
left: -8px;
z-index: 1;
}
</style>