-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.ts
More file actions
166 lines (147 loc) · 4.1 KB
/
Copy pathauth.ts
File metadata and controls
166 lines (147 loc) · 4.1 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
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
signOut,
type User,
} from 'firebase/auth'
import {
doc,
setDoc,
getDoc,
getDocs,
updateDoc,
addDoc,
collection,
query,
where,
limit,
arrayUnion,
FirestoreError,
type FirestoreDataConverter,
} from 'firebase/firestore'
import { FirebaseError } from 'firebase/app'
import { auth, db } from './firebase'
const googleProvider = new GoogleAuthProvider()
interface UserDoc {
email: string | null
tokens: number
model: string
isNewUser: boolean
uid: string
// Stored entries use `date`, while the Draft types in the UI expect `time`.
draft?: any[]
}
const userConverter: FirestoreDataConverter<UserDoc> = {
toFirestore: (data) => data,
fromFirestore: (snapshot) => snapshot.data() as UserDoc,
}
const userRef = (user: User | null) => {
if (!user) throw new Error('User not signed in')
return doc(db, 'users', user.uid).withConverter(userConverter)
}
export const waitList = async (email: string) => {
await addDoc(collection(db, 'waitList'), {
email: email,
createdAt: new Date().toDateString(),
})
}
export const getUserToken = async (user: User | null) => {
if (!user) return null
const snapshot = await getDoc(userRef(user))
return snapshot.exists() ? snapshot.data().tokens : null
}
export const updateTokens = async (
user: User | null,
newTokenValue: number
) => {
await updateDoc(userRef(user), { tokens: newTokenValue })
}
export const updateModel = async (user: User | null, newModelValue: string) => {
await updateDoc(userRef(user), { model: newModelValue })
}
export const addDraft = async (
user: User | null,
data: string,
platform: string
) => {
const ref = userRef(user)
try {
await updateDoc(ref, {
draft: arrayUnion({ draft: data, platform, date: new Date() }),
})
} catch (error) {
if (error instanceof FirestoreError && error.code === 'not-found') {
alert('User document not found')
} else {
alert('Error occured')
console.log(error)
}
}
}
export const fetchUserDrafts = async (user: User | null) => {
const ref = userRef(user)
try {
const snapshot = await getDoc(ref)
if (!snapshot.exists()) throw new Error('User document not found')
return snapshot.data().draft || []
} catch (error) {
throw new Error('Error fetching drafts: ' + (error as Error).message)
}
}
export const createUserWithEmail = async (email: string, password: string) => {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
if (user.email) {
const userData = {
email: user.email,
tokens: 100,
model: 'text-davinci-002',
isNewUser: true,
uid: user.uid,
drafts: [],
}
await setDoc(userRef(user), userData)
}
}
export const signInWithEmail = async (email: string, password: string) => {
try {
const { user } = await signInWithEmailAndPassword(auth, email, password)
return user
} catch (error) {
if (
error instanceof FirebaseError &&
error.code === 'auth/user-not-found'
) {
throw new Error('User does not exist')
}
throw error
}
}
export const Logout = async () => {
try {
await signOut(auth)
} catch (err) {
console.error(err)
}
}
export const signInWithGoogle = async () => {
const { user } = await signInWithPopup(auth, googleProvider)
const existingUsers = await getDocs(
query(
collection(db, 'users'),
where('email', '==', user.email),
limit(1)
)
)
if (!existingUsers.empty) return
const userData = {
email: user.email,
tokens: 100,
model: 'text-davinci-002',
isNewUser: true,
uid: user.uid,
}
await setDoc(userRef(user), userData, { merge: true })
return user
}