-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase.js
299 lines (260 loc) · 9.83 KB
/
firebase.js
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
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-analytics.js";
import { getAuth, sendPasswordResetEmail, signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged, signOut, GoogleAuthProvider, signInWithPopup } from 'https://www.gstatic.com/firebasejs/10.14.1/firebase-auth.js';
import { getFirestore, doc, setDoc, getDoc } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-firestore.js";
const provider = new GoogleAuthProvider();
export async function signInWithPopupMethod() {
try {
const result = await signInWithPopup(auth, provider);
currentUser = result.user;
console.log('User signed in:', currentUser);
return currentUser;
} catch (error) {
console.error('Error during sign in with popup:', error);
throw error;
}
}
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCfZVAvR8bDfk3E0MCzmTxhNGonV3lJkB8",
authDomain: "grammar-of-english.firebaseapp.com",
projectId: "grammar-of-english",
storageBucket: "grammar-of-english.appspot.com",
messagingSenderId: "691355325894",
appId: "1:691355325894:web:51edad1e0e76361f30cec7",
measurementId: "G-78LYTLBM7M"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const auth = getAuth(app);
export let currentUser = null;
export function getCurrentUser() {
return new Promise((resolve, reject) => {
onAuthStateChanged(auth, (user) => {
if (user) {
currentUser = user;
resolve(currentUser);
} else {
currentUser = null;
reject("No authenticated user");
}
});
});
}
// Функция регистрации
export async function signUp(email, password) {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
currentUser = userCredential.user;
console.log('User signed up:', currentUser);
return currentUser;
} catch (error) {
console.error('Error signing up:', error);
throw error;
}
}
// Функция входа
/*export async function signIn(email, password) {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
currentUser = userCredential.user;
console.log('User signed in:', currentUser);
return currentUser;
} catch (error) {
console.error('Error signing in:', error);
throw error;
}
}*/
/*
// Функция сброса пароля
export async function resetPassword(email) {
try {
await sendPasswordResetEmail(auth, email);
console.log('Password reset email sent!');
alert('Password reset email sent! Check your inbox.');
} catch (error) {
console.error('Error sending password reset email:', error);
alert('Error sending password reset email. Please try again.');
}
}*/
// Функция выхода из аккаунта
export async function logOut() {
try {
await signOut(auth);
console.log("User signed out");
} catch (error) {
console.error("Sign out error: ", error);
}
}
async function click_sign_up_btn(){
const email = document.getElementById('email-input').value;
const password = document.getElementById('password-input').value;
if (!email) {
alert('Please enter your email address.');
return;
}
if (!password) {
alert('Please enter password.');
return;
}
signUp(email, password);
}
async function click_logout_btn(loginBlock){
await logOut();
add_input_login(loginBlock);
}
async function click_sign_in_btn(loginBlock) {
try {
const user = await signInWithPopupMethod(); // Используем signInWithPopupMethod вместо signIn
loginBlock.innerHTML = `
<p>Welcome, ${user.email.split('@')[0]}</p>
<button id="logout-btn">Log Out</button>
`;
document.getElementById('logout-btn').addEventListener('click', async () => {
click_logout_btn(loginBlock);
});
} catch (error) {
console.error('Error during sign in:', error);
}
}
/*async function click_sign_in_btn(loginBlock){
const email = document.getElementById('email-input').value;
const password = document.getElementById('password-input').value;
try {
const user = await signIn(email, password);
loginBlock.innerHTML = `
<p>Welcome, ${user.email.split('@')[0]}</p>
<button id="logout-btn">Log Out</button>
`;
document.getElementById('logout-btn').addEventListener('click', async () => {
click_logout_btn();
});
} catch (error) {
console.error('Error during sign in:', error);
}
}*/
function add_input_login(loginBlock) {
loginBlock.innerHTML = `
<button id="google-sign-in-btn">Sign In with Google</button>
`;
document.getElementById('google-sign-in-btn').addEventListener('click', async () => {
try {
await click_sign_in_btn(loginBlock); // Вход через Google
} catch (error) {
console.error('Error during Google sign in:', error);
}
});
}
/*function add_input_login(loginBlock){
// Пользователь не авторизован, показываем форму регистрации и входа
loginBlock.innerHTML = `
<input type="email" id="email-input" placeholder="Email" required>
<input type="password" id="password-input" placeholder="Password">
<button id="sign-up-btn">Register</button>
<button id="sign-in-btn">Sign In</button>
<button id="reset-password-btn">Reset Password</button>
`;
// Добавляем события для регистрации и входа
document.getElementById('sign-up-btn').addEventListener('touchstart', () => {
click_sign_up_btn();
});
document.getElementById('sign-up-btn').addEventListener('click', () => {
click_sign_up_btn();
});
const signInBtn = document.getElementById('sign-in-btn');
signInBtn.style.pointerEvents = 'auto';
document.getElementById('sign-in-btn').addEventListener('touchstart', () => {
click_sign_in_btn(loginBlock);
});
document.getElementById('sign-in-btn').addEventListener('click', async () => {
click_sign_in_btn(loginBlock);
});
document.getElementById('reset-password-btn').addEventListener('touchstart', async () => {
const email = document.getElementById('email-input').value;
if (!email) {
alert('Please enter your email address.');
return;
}
await resetPassword(email);
});
document.getElementById('reset-password-btn').addEventListener('click', async () => {
const email = document.getElementById('email-input').value;
if (!email) {
alert('Please enter your email address.');
return;
}
await resetPassword(email);
});
}*/
// Функция для проверки авторизации и модификации страницы
function checkAuthAndModifyPage() {
const loginBlock = document.getElementById('login-block');
if (!loginBlock) {
console.error("Element with class 'login-block' not found.");
return;
}
onAuthStateChanged(auth, (user) => {
if (user) {
currentUser = user;
loginBlock.innerHTML = `
<p>Welcome, ${user.email.split('@')[0]}</p>
<button id="logout-btn">Log Out</button>
`;
document.getElementById('logout-btn').addEventListener('click', () => {
click_logout_btn(loginBlock);
});
document.getElementById('logout-btn').addEventListener('touchstart', () => {
click_logout_btn(loginBlock);
});
currentUser = user;
} else {
currentUser = null;
add_input_login(loginBlock);
}
});
}
document.addEventListener('DOMContentLoaded', () => {
checkAuthAndModifyPage();
});
//----------------------------------------------------------------------------------
// Функция для сохранения результатов упражнений
/*
const userId = "user123"; // Например, ID пользователя
const results = { score: 85, completedAt: new Date() };
saveExerciseResults(userId, results);
*/
async function saveExerciseResults(userId, results) {
const db = getFirestore(); // Получение экземпляра Firestore
try {
await setDoc(doc(db, 'exerciseResults', userId), {
results: results
});
console.log('Results saved successfully');
} catch (error) {
console.error('Error saving results:', error);
}
}
// Функция для получения результатов упражнений
/*
const userId = "user123";
getExerciseResults(userId);
*/
async function getExerciseResults(userId) {
const db = getFirestore(); // Получение экземпляра Firestore
try {
const docRef = doc(db, 'exerciseResults', userId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log('Results:', docSnap.data().results);
} else {
console.log('No such document!');
}
} catch (error) {
console.error('Error getting document:', error);
}
}