-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase-utils.ts
153 lines (144 loc) · 4.34 KB
/
firebase-utils.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
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
sendPasswordResetEmail,
confirmPasswordReset
} from "firebase/auth";
import { IOpenNotificationProps } from "@/components/atoms/Notification/Notification";
import { auth } from "./firebase";
import { STORAGE_TOKEN } from "@/utils/constants/globalConstants";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { useAppStore } from "@/lib/store/store";
import { NotificationInstance } from "antd/es/notification/interface";
const getAuth = async (
email: string,
password: string,
router: AppRouterInstance,
isSignUp: any,
// eslint-disable-next-line no-unused-vars
openNotification: ({ api, title, message, placement }: IOpenNotificationProps) => void,
api: NotificationInstance
) => {
if (isSignUp) {
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCred) => {
const token = await userCred.user.getIdToken();
fetch("/api/auth", {
method: "POST",
headers: {
Authorization: `Bearer ${await userCred.user.getIdToken()}`
}
}).then((response) => {
localStorage.setItem(STORAGE_TOKEN, token);
if (response.status === 200) {
router.push("/");
}
});
})
.catch((error) => {
alert(`Sign up failed: ${error.message} - ${error.code}`);
});
} else {
signInWithEmailAndPassword(auth, email.trim(), password)
.then(async (userCred) => {
// Check email verification
//cuando se active la verificación de correo, descomentar
// if (!userCred.user.emailVerified) {
// // Sign out the user
// await signOut(auth);
// openNotification({
// api: api,
// type: "warning",
// title: "Email no verificado",
// message:
// "Por favor verifica tu correo electrónico antes de iniciar sesión. Se ha enviado un nuevo correo de verificación."
// });
// return;
// }
const token = await userCred.user.getIdToken();
fetch("/api/auth", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
tokenExm: `${JSON.stringify(userCred)}`
}
}).then((response) => {
if (response.status === 200) {
localStorage.setItem(STORAGE_TOKEN, token);
router.push("/clientes/all");
}
});
})
.catch((error) => {
console.error({ error });
openNotification({
api: api,
type: "error",
title: "Error",
message: "Usuario o contraseña incorrectos"
});
});
}
};
const logOut = (router: AppRouterInstance) => {
window.location.href = "/auth/login";
signOut(auth);
localStorage.removeItem(STORAGE_TOKEN);
const { resetStore } = useAppStore.getState();
resetStore();
};
const sendEmailResetPassword = async (email: string) => {
try {
await sendPasswordResetEmail(auth, email);
} catch (error) {
handleError(error);
}
};
const resetPassword = async (oobCode: string, newPassword: string) => {
try {
await confirmPasswordReset(auth, oobCode, newPassword);
} catch (error) {
handleError(error);
}
};
// New helper function to check email verification
const checkEmailVerification = async (): Promise<boolean> => {
if (!auth.currentUser) return false;
await auth.currentUser.reload();
return auth.currentUser.emailVerified;
};
// New function to resend verification email
const resendVerificationEmail = async (
openNotification: ({ api, title, message, placement }: IOpenNotificationProps) => void,
api: NotificationInstance
) => {
try {
if (auth.currentUser) {
openNotification({
api: api,
type: "success",
title: "Correo enviado",
message: "Se ha enviado un nuevo correo de verificación"
});
}
} catch (error) {
handleError(error);
}
};
function handleError(error: unknown): void {
if (error instanceof Error) {
console.error(`Error: ${error.message}`);
} else {
console.error("An unknown error occurred:", error);
}
throw error;
}
export {
getAuth,
logOut,
sendEmailResetPassword,
resetPassword,
checkEmailVerification,
resendVerificationEmail
};