-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
234 lines (200 loc) · 5.46 KB
/
auth.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
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
signOut,
} from "firebase/auth"
import {
getFirestore,
doc,
setDoc,
getDoc,
getDocs,
onSnapshot,
collection,
query,
where,
arrayUnion,
addDoc
} from "firebase/firestore"
import { db } from "./firebase"
import { updateDoc } from "firebase/firestore"
import Alert from "@mui/material/Alert"
// import { db } from './firebaseConfig';
import { app } from "./firebaseConfig"
const auth = getAuth(app)
const firestore = getFirestore(app)
const googleProvider = new GoogleAuthProvider()
export const waitList=async(email)=>{
await addDoc(collection(firestore, "waitList"), {
email: email,
createdAt: new Date().toDateString()
});
}
export const readTokens = async (user) => {
const userRef = doc(firestore, "users", user.uid)
const userDoc = await userRef.get()
const userData = userDoc.data()
if (userData) {
return userData.tokens
}
return null
}
export const getRealTimeToken = async (user) => {
let value
const tokenRef = doc(firestore, "users", user.uid)
await onSnapshot(tokenRef, (snapshot) => {
value = snapshot.data().tokens
})
return value
// if (doc1.exists) {
// console.log("this is real time data "+doc1.data().tokens)
// return doc1
// } else {
// return null;
// }
}
export const generateRealTimeToken = (user) => {
// Get the current user's token
if (!user) return null
let token = getUserToken(user)
const tokenRef = doc(firestore, "users", user.uid)
// Listen for changes to the token
onSnapshot(tokenRef, (newToken) => {
// Update the token if it has changed
if (newToken !== token) {
token = newToken
}
})
// Return the current token
return token
}
export const getUserToken = async (user) => {
if (!user) return null
const tokenRef = doc(firestore, "users", user.uid)
const doc1 = await getDoc(tokenRef)
if (doc1.exists) {
return doc1.data().tokens
} else {
return null
}
}
export const updateTokens = async (user, newTokenValue) => {
const userRef = doc(firestore, "users", user.uid)
await updateDoc(userRef, { tokens: newTokenValue })
}
export const updateModel = async (user, newModelValue) => {
const userRef = doc(firestore, "users", user.uid)
await updateDoc(userRef, { model: newModelValue })
}
export const addDraft = async (user, data, platform) => {
const userRef = doc(db, "users", user.uid)
const newObject = {draft:data, platform: user}
const CurrentDate = new Date();
try {
const userDoc = await getDoc(userRef)
if (userDoc.exists()) {
await updateDoc(userRef, {
draft: arrayUnion({draft:data, platform: platform, date: CurrentDate}),
})
;<Alert severity="success">This is a success alert — check it out!</Alert>
} else {
alert("User document not found")
}
} catch (error) {
alert("Error:", error)
console.log(error)
}
}
export const addToWaitList = async ( email) => {
db.collection("waitList").add({
email: email,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
export const fetchUserDrafts = async (user) => {
const userRef = doc(firestore, "users", user.uid)
try {
const docSnap = await getDoc(userRef)
if (docSnap.exists()) {
const userData = docSnap.data()
const userDrafts = userData.draft || []
return userDrafts
} else {
throw new Error("User document not found")
}
} catch (error) {
throw new Error("Error fetching drafts: " + error.message)
}
}
export const createUserWithEmail = async (email, password) => {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
if (user.email && user.uid) {
const userData = {
email: user.email,
tokens: 100,
model: "text-davinci-002",
isNewUser: true,
uid: user.uid,
drafts: [],
}
await setDoc(doc(firestore, "users", user.uid), userData)
}
}
export const signInWithEmail = async (email, password) => {
try {
const { user } = await signInWithEmailAndPassword(auth, email, password)
return user
} catch (error) {
if (error.code === "auth/user-not-found") {
throw new Error("User does not exist")
} else {
throw error
}
}
}
export const Logout = async () => {
try {
await signOut(auth)
} catch (err) {
console.error(err)
}
}
export const signInWithGoogle = async () => {
const googleProvider = new GoogleAuthProvider()
const { user } = await signInWithPopup(auth, googleProvider)
const userRef = collection(db, "users")
const q = query(userRef, where("email", "==", user.email))
const querySnapshot = await getDocs(q)
let checkUser = []
querySnapshot.forEach((doc) => {
checkUser.push({ id: doc.id, ...doc.data() })
})
if (checkUser.length > 0) return
const userData = {
email: user.email,
tokens: 100,
model: "text-davinci-002",
isNewUser: true,
uid: user.uid,
}
await setDoc(doc(firestore, "users", user.uid), userData, { merge: true })
return user
}
export const onUserSignedIn = async (user, router) => {
const userDoc = await doc(firestore, "users", user.uid).get()
const isNewUser = userDoc.data().isNewUser
if (isNewUser) {
router.push("/")
} else {
router.push("/")
}
}