Hi guys,
I’m new here to the ionic world, and I have trouble with auth persistence using capacitor storage. My main problem is the retrieval of the token from capacitor storage since it is async function and i’m only used to using localStorage synchronously. here is my authentication flow:
1- user enters username/password in and clicks login button LoginPage.vue
2- once button is clicked, vuex
action called login
will be dispatched. here is the action:
login({commit}, payload) {
alert("reached login");
axios.post('https://myapp.test/api/sanctum/token', {
email: payload.email,
password: payload.password,
device_name: 'someranddd'
}).then((response) => {
commit("updateToken", response.data.split("|")[1])
}).catch((error) => {
alert(error);
})
router.push('/')
},
3- using axios, I request token from laravel
backend which returns the token string and I store it in state. as well as capacitor storage using a mutation. here is the code in the mutation
mutations: {
updateToken(state, nuToken) {
state.token = nuToken;
const setToken = async () => {
await Storage.set({
key: "userToken",
value: nuToken,
});
};
setToken().then(() => {
})
},
},
4- all the steps up to this point work flawlessly, and capacitor storage does work. now in router/index.js
I implemented router.beforeEach()
and it works fine except when I start looking for the stored token in capacitor storage. here is the code in index.js
const protectedRoutes = ['invoicesTab','itemsTab','settingsTab','Home'];
router.beforeEach((to,from, next) => {
if(protectedRoutes.includes(to.name) && store.getters.getToken === null) // my problem is in this line
next({name: 'Login'})
else
next();
});
here is what i have tried:
- write async action in the store to fetch the token, but that renders a blank page.
- use the async function listed in Capacitor - build cross platform apps with the web to fetch the token and put
router.beforeEach
inside it, but that returns a blank page as well.
please let me know what I’m missing, because i cannot use localStorage since this is going to be native application.
thanks in a advance.
2 posts - 2 participants