At first lets us look th e way to authenticate Firebase without Pinia. Here we are not going to discuss how to install firebase,pinia,Vue,Tailwind. If you dont know please have a look at the previous blog
This is how your config.js file will look like i put it in a folder named firebase
Without Pinia
In Register.vue
Its a simple form and now in script part
auth,createUserWithEmailAndPassword is imported from firebase config files here from firebase/config.js files
Here we see in firebase dashboard panel
So now a user is registered
In Pinia
Now the understanding will be clear how easy things are in Pinia
in store useAuthStore.js
We see now the registration under actions
IN Register.vue
In template part in case
`<input type="text" v-model="store.email" class="border-b-2 border-gray-300 w-4/5 py-1" name="" id=""><br>
in place of `v-model="email"
the same will be in place of password
In script part i have put everything under
So we see we take the whole authStore import it and keep inside variable store.
The Login and Logout is shown as follows
In Login.vue
Same as Register.vue
In Navbar.vue
**IN script setup **
**onAuthStateChanged*-Check whether a user is authenticated or not
useAuthStore.js
In state declare a new object called user
then in actions define a function called init()
In App.vue We need to initialize init() function in unMounted hook
If user is logged in we set the user uid and email of the authenticated user
While you are logged in if you enter Vue devtools you will see this
While logged out
You will see its empty
Route protection
If now any route needs to be guarded that should be done like this just in that route write beforeEnter and the **requireAuth* like mentioned here
Top comments (3)
Thank you for the guide, it was incredibly useful!
I think that one small detail is missing, so I'm commenting in case someone else wants to follow this guide :
In your main.js, you have to import, create and use Pinia, or else it won't work. Here is the code to do it :
Thanks so much Oliver its really good to know that code still works.
Me again, another small suggestion for other users who might follow this code : the password from the login or signup forms is stored in Pinia's local storage, and it is erased only when the user logs out. But it stays as clear text in the local storage as long as the user is logged in, which might pose some security problem. This could be fixed with two possible solutions :
Changing
login()
andsignup()
tologin(email, password)
andsignup(email, password)
in useAuthStore.js, and removing thev-model="store.password"
from the login and signup inputs. This way, the password will never enter the local storage and will be passed as an argument instead.Adding a line with
this.password = ''
at the end oflogin()
andsignup()