-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUserAuthContext.jsx
178 lines (155 loc) · 5.38 KB
/
UserAuthContext.jsx
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
import { useContext, createContext, useEffect, useState } from "react"
import { AuthErrorCodes, createUserWithEmailAndPassword, onAuthStateChanged,signInWithEmailAndPassword,sendEmailVerification } from "firebase/auth";
import { auth, db,app } from "../firebase";
import { collection, doc, setDoc,getDoc, updateDoc} from "firebase/firestore";
import { getPremiumStatus } from "../assets/Subscription/getPremiumStatus";
const userContext = createContext();
//REFERENC TO ACCESS CODE.-----------------------------------------
export const useAuth = () => { return useContext(userContext) }
const UserAuthContext = ({ children }) => {
//<******************************VARIABLESS*******************************>
//CURRENT USER DATA
const [currentuser, setuser] = useState()
const [error, setError] = useState("")
const [isPremium,setIsPremium] = useState(false)
const [userData, setUserData] = useState([]);
//<******************************FUNCTIONS*******************************>
//PREMUIM STATE TOGGLE
useEffect(() => {
if(currentuser){
const userRef= doc(db,"users",currentuser.uid)
updateDoc(userRef,{
subscription: isPremium
})
}
}, [isPremium]);
//CHECKING FOR AUTHENTICATED USER AND GET DATA
useEffect(() => {
onAuthStateChanged(auth, user => {
console.log(user)
if (user) {
setuser(user)
console.log("u are logged in")
if(window.location.pathname == "/login" && window.location.pathname == "/register"){
window.location.href = "/"
}
}
else {
if(window.location.pathname != "/login" && window.location.pathname != "/register" && window.location.pathname != "/support/contact-us" && window.location.pathname != "/support/feedback" && window.location.pathname != "/policies/legal" && window.location.pathname != "/policies/legal/terms" && window.location.pathname != "/policies/legal/cookie-policy" && window.location.pathname != "/policies/legal/privacy-policy" && window.location.pathname != "/policies/legal/acceptable-use-policy" && window.location.pathname != "/policies/security" && window.location.pathname != "/landing" && window.location.pathname != "/policies"){
window.location.href = "/landing"
}
}
})
//PREMIUM STATE AND USER DATA FETCH
const checkPremium = async () => {
const newPremiumStatus = auth.currentUser
? await getPremiumStatus(app)
: false;
setIsPremium(newPremiumStatus);
};
const fetchData = async () => {
try {
if (currentuser) {
const currentUserId = currentuser.uid;
const userDocRef = doc(db, "users", currentUserId);
const docSnapshot = await getDoc(userDocRef);
if (docSnapshot.exists()) {
// Document exists, retrieve its data
const elementData = docSnapshot.data();
setUserData(elementData);
checkPremium()
} else {
console.log("Document does not exist.");
setUserData(null); // Set to null or handle accordingly
}
}
} catch (error) {
console.error("Error getting document: ", error);
}
};
fetchData()
}, [currentuser]);
//LOGIN
const Login = async (email,password) => {
const logEmail = email;
const logPass = password
try{
await signInWithEmailAndPassword(auth,logEmail,logPass)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log(user)
window.location.href = "/"
})
}catch(error){
console.log(error)
alert("Wrong Email or Password")
}
}
//REGISTRATION
const SignUp = async (email, password, FullName) => {
const userName = FullName;
const regEmail = email;
const userPassword = password;
try {
const result = await createUserWithEmailAndPassword(auth, regEmail, userPassword);
//RESULT == USER DATA
const signeduser = result.user;
//Setting Fresh Registrated user To the Document
const userId = signeduser.uid;
const colRef = collection(db, "users");
const tagRef = collection(db, "users", userId, "Tags");
//const newTagRef = doc(tagRef);
console.log(userId);
//SETTING USER DOCUMENT TO FIRESTORE
try {
await setDoc(doc(colRef, userId),{
id: userId,
fullname: userName,
email: regEmail,
subscription: false,
storage_take:0,
profilePictureURL: "",
recent:"",
user_since: new Date().toLocaleDateString(),
});
await setDoc(doc(tagRef,userId),{
tags:[
"None"
]
});
console.log("Document successfully added!");
} catch (error) {
console.error("Error adding document: ", error);
};
alert("Wellcome new User create successfully");
await sendEmailVerification(signeduser)
window.location.href = "/"
} catch(err) {
//ERROR IF ITS IN ALREADY USE
if (err.code === "auth/email-already-in-use") {
alert("Email already in use, try another email");
setTimeout(() => {
setError("");
}, 5000);
} else if (err.code === AuthErrorCodes.WEAK_PASSWORD) {
alert("Password must be at least 6 characters");
setTimeout(() => {
setError("");
}, 5000);
} else {
setError(err.message);
}
}
}
//END VALUES ACCES To ALL JSX
const value = {
SignUp,
error,
currentuser,
Login,
}
return (
<userContext.Provider value={value}>{children}</userContext.Provider>
)}
export default UserAuthContext