I use node js and express js. I want to make sure that if app.get is without a token parameter, then upload an html file with js that will pass the token. And if the token was passed, then show another html file.
But I do not know how to make a redirect from the client with the transfer of a header with a token
Server:
app.get("/admin-cp/:page", function (req, res) {
const idToken = req.headers.authorization;
if (!idToken)
{
return res.sendFile(path.join(initial_path, "admin-cp/loader.html"));
//return res.status(401).send("Unauthorized")
}
const sessionCookie = req.cookies.session || "";
admin
.auth()
.verifySessionCookie(sessionCookie, true )
.then((userData) => {
console.log("Logged in:", userData.email)
console.log('Авторизован. Доступ в админ панель открыт')
admin
.auth()
.verifyIdToken(idToken)
.then((claims) =>
{
if (claims.admin === true)
{
console.log('Зашёл с правами администратора', req.params.page);
if (req.params.page === 'analytics')
{
console.log("Open analytics");
res.sendFile(path.join(initial_path, "admin-cp/main-admin_cp.html"));
//res.render(path.join(initial_path, "admin-cp/main-admin_cp.html"));
//res.redirect('/admin-cp/home');
}
}
else if (claims.admin === false)
{
console.log('Зашёл без прав администратора');
//res.sendFile(path.join(initial_path, "admin-cp/global_not_permission.html"));
res.redirect('/');
}
});
})
.catch((error) => {
console.log('Не авторизован. Ошибка', error, ' отсутвует userData')
res.redirect("/login");
});
});
I tried to do with "fetch":
const res = await fetch('/admin-cp/analytics', { headers: { authorization: idToken }, redirect: 'follow' })
.then(res => {
console.log(res);
if (res.redirected) {
document.location = res.url;
}
})
But after all the actions res.sendFile is not updated
help with any advice. please
The sequence of events goes like this.
fetch request, including an authorization header, to the URLfetch request to the new URL (I've no idea if it include the authorization header again here)fetch was redirected todocument.location causing the browser to make a new GET request to that URL (definitely without an authorization header).res.sendFile(path.join(initial_path, "admin-cp/loader.html")) because there is no authorization header.You can't make the browser navigate and include an authorization header.
If you want to do authentication while navigating: Use cookies instead.