-
Notifications
You must be signed in to change notification settings - Fork 0
auth.mjs
up2108272 edited this page May 8, 2024
·
6 revisions
- For authenticating logins and registrations through Firebase
export function createUser(fname, mname, lname, email, password, role, redirUrl) {
createUserWithEmailAndPassword(auth, email, password, redirUrl)
.then((userCredential) => {
setDbRole(role, userCredential);
alert(`${userCredential.user.email} Has been created.`);
let payload = [userCredential.user.uid, fname, mname, lname, email, role]
console.log(userCredential.user.uid);
fetch('/new-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
window.location.href = redirUrl;
})
.catch((error) => {
alert(`ERROR CODE: ${error.code} ERROR MESSAGE: ${error.message}`);
});
}- Takes in email, password and role as a string then creates the user with that information.
- Takes in url to login page/anywhere else.
async function setDbRole(_role, userCredential) {
await setDoc(doc(db, "users", userCredential.user.uid), {
role: _role,
});
}- Sets the role for the user within the database
export function signIn(email, password, redirectUrl) {
if (auth.currentUser) {
signOutFn('../index.html');
}
//sign in with auto redirect
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log(`Logged in as ${userCredential.user.uid}`);
window.location.href = redirectUrl;
})
.catch((error) => {
alert(`ERROR CODE: ${error.code} ERROR MESSAGE: ${error.message}`);
});
}- Signs user in with email and password and directs them to page specified by redirectUrl
export function signOutFn(redirectUrl) {
if (auth == null) {
return;
}
signOut(auth)
.then(() => {
window.location.href = redirectUrl;
console.log(auth.auth.currentUser);
})
.catch((error) => {
// An error happened.
});
}- Signs user out
export function userLoggedInQ() {
if (user) {
return true;
} else {
return false;
}
}- Checks whether user is logged in
learnforge wiki!