You need to have 3 functions:
FIRST
You need to check the initial load of the page if the browser still have that cookie using the initAuth()
function below.
SECOND
You need to make the login/register method to make your user have their token.
THIRD
You need to let the user logout.
It should look something like this:
authenticateUser(content, authData) {
let authUrl =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" +
process.env.fbAPIKey;
if (!authData.isLogin) {
authUrl =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=" +
process.env.fbAPIKey;
}
return this.$axios
.$post(authUrl, {
email: authData.email,
password: authData.password,
returnSecureToken: true
})
.then(result => {
content.commit("setToken", result.idToken);
localStorage.setItem("token", result.idToken);
localStorage.setItem(
"tokenExpiration",
new Date().getTime() + Number.parseInt(result.expiresIn) * 1000
);
Cookie.set("jwt", result.idToken);
Cookie.set(
"expirationDate",
new Date().getTime() + Number.parseInt(result.expiresIn) * 1000
);
return this.$axios.$post('http://localhost:3000/api/track-data', {data: 'Authenticated!'})
})
.catch(e => console.log(e));
}
initAuth(content, req) {
let token;
let expirationDate;
if (req) {
if (!req.headers.cookie) {
return;
}
const jwtCookie = req.headers.cookie
.split(";")
.find(c => c.trim().startsWith("jwt="));
if (!jwtCookie) {
return;
}
token = jwtCookie.split("=")[1];
expirationDate = req.headers.cookie
.split(";")
.find(c => c.trim().startsWith("expirationDate="))
.split("=")[1];
} else if (process.client) {
token = localStorage.getItem("token");
expirationDate = localStorage.getItem("tokenExpiration");
}
if (new Date().getTime() > +expirationDate || !token) {
console.log("No token or invalid token");
content.dispatch("logout");
return;
}
content.commit("setToken", token);
}
logout(content) {
content.commit("clearToken");
Cookie.remove("jwt");
Cookie.remove("expirationDate");
if (process.client) {
localStorage.removeItem("token");
localStorage.removeItem("tokenExpiration");
}
}
MIDDLEWARE
Then you can call your middleware look like this:
Check for Token first:
context.store.dispatch("initAuth", context.req);
if (!context.store.getters.isAuthenticated) {
context.redirect("/admin/login");
}
This is only my point of view and my sample code.