Skip to content

Instantly share code, notes, and snippets.

@oxcode-dev
Last active October 1, 2023 12:44
Show Gist options
  • Save oxcode-dev/462cd3af0642216c0d29fc5378ca94c5 to your computer and use it in GitHub Desktop.
Save oxcode-dev/462cd3af0642216c0d29fc5378ca94c5 to your computer and use it in GitHub Desktop.
Vue Composables Firebase Authentication Hook
import { signOut, signInWithEmailAndPassword, createUserWithEmailAndPassword, updatePassword, updateEmail, deleteUser } from "firebase/auth"
import { auth } from "../firebase.config"
import { errorResponse } from '../helpers/FirebaseErrorResponse';
import { ref } from "vue";
import router from "../router";
export const useFirebaseAuth = () => {
const user = auth.currentUser;
const isLoading = ref(false)
const error = ref('')
const handleSignOut = async() => {
await signOut(auth).then(() => {
location.href = '/auth'
}).catch((error) => {
console.log(errorResponse(error.code))
});
}
const handleSignIn = async (email, password) => {
isLoading.value = true
let result = null
try {
result = await signInWithEmailAndPassword(auth, email, password);
isLoading.value = false
console.log(result.user)
router.push('/')
} catch (e) {
error.value = errorResponse(e.code);
isLoading.value = false
}
}
const handleSignUp = async (email, password) => {
isLoading.value = true
let result = null
try {
result = await createUserWithEmailAndPassword(auth, email, password);
isLoading.value = false
console.log(result.user)
router.push('/')
} catch (e) {
error.value = e.code;
isLoading.value = false
}
}
const handleChangePassword = (password) => {
isLoading.value = true
updatePassword(user, password).then(() => {
isLoading.value = false
alert('Password Updated Successfully!!!')
})
.catch((error) => {
isLoading.value = false
if(error.code === 'auth/requires-recent-login') {
error.value = e.code;
handleSignOut()
}
error.value = e.code;
});
}
const handleUpdateUserEmail = email => {
isLoading.value = true
updateEmail(auth.currentUser, email).then(() => {
isLoading.value = false
alert('Email Updated Successfully!!!')
}).catch((error) => {
isLoading.value = false
if(error.code === 'auth/requires-recent-login') {
error.value = e.code;
handleSignOut()
}
error.value = e.code;
});
}
const handleDeleteUser = () => {
deleteUser(user).then(() => {
alert('Account Deleted')
handleSignOut()
}).catch((error) => {
if(error.code === 'auth/requires-recent-login') {
error.value = e.code;
handleSignOut()
}
error.value = e.code;
});
}
return {
handleSignUp, handleSignIn, handleSignOut, handleChangePassword,
handleUpdateUserEmail, handleDeleteUser, isLoading, error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment