Feeling a bit puzzled with your mention of API data and JSON pages, but the solution lies in creating middleware to protect your page.
Consider setting up a middleware called auth.js:
export default async function ({ store, $axios, redirect }) {
let valid = await $axios.$post('/api/checktoken')
if (!valid) {
redirect('/')
}
}
To secure your page, establish an API for token verification. Storing the token in a cookie can simplify this process as cookies are automatically included in HTTP requests.
Next, apply the auth middleware to a specific page:
<script>
export default {
middleware: "auth"
}
</script>
If safeguarding backend routes is necessary, create another middleware:
async authenticate(req, res, next) {
let token = await cookieService.getTokenFromCookie(req)
if (!token) return errorService.resError(res, 400, 'Authorization failed')
let tokenValid = await tokenService.verifyToken(token)
if (!tokenValid)
return errorService.resError(res, 400, 'Authorization failed')
let decodedData = tokenService.decode(token)
if (!decodedData)
return errorService.resError(res, 400, 'Authorization failed')
res.locals.userId = decodedData.userId
res.locals.role = decodedData.role
next()
}
This method involves extracting the token from a cookie, verifying its validity, and decoding it for access to its information. The data can then be stored in res.locals
for subsequent middleware or endpoints.
Remember to call next()
to proceed to the next middleware or endpoint:
function endpoint(req, res) {
let { userId, role } = res.locals
// Perform actions....
}
Apply the authentication middleware to relevant API endpoints:
app.use("/some/api/point", authenticate, endpoint)
By using authenticate
in various API routes, you ensure consistent protection across different parts of your application.