Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  200] [ 5]  / answers: 1 / hits: 5193  / 3 Years ago, tue, march 16, 2021, 12:00:00

My goal is redirect to the main page "/"

but "/" page is attached with Middleware checking user has TOKEN


I want to redirect to "/" with Bearer TOKEN header

WITHOUT AJAX


So, I made a new path "/loginDetour" on the server

and use FETCH to this path with TOKEN Header

then, "/loginDetour"server made page redirect to the "/"


but....it is not working..

Here is my codes



Main Router



const express = require('express');
const app = express();
const hbs = require('express-handlebars');
const path = require('path');
const PORT = process.env.PORT || 5000;

const layoutsDir = path.join(__dirname, './views/layouts');
const partialsDir = path.join(__dirname, './views/partials');
const publicPath = path.join(__dirname, './public');

const authRouter = require('./server/routes/authRouter');
const weatherRouter = require('./server/routes/weatherRouter');
const todoRouter = require('./server/routes/todoRouter');

app.set('view engine', 'hbs');
app.engine(
'hbs',
hbs({
extname: 'hbs',
defaultLayout: 'layout',
layoutsDir,
partialsDir,
})
);
if (process.env.NODE_ENV === 'production') {
app.get('view cache');
}

app.use(express.static(publicPath));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const checkAuth = require('./server/middleware');
app.use(authRouter.routes);
app.use('/weather', checkAuth, weatherRouter.routes);
app.use('/todo', checkAuth, todoRouter.routes);

app.get('/', checkAuth, (req, res) => {
res.render('index');
});

app.listen(PORT, () => {
console.log(`Server started on Port ${PORT}`);
});


Login Router



router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
await auth.signInWithEmailAndPassword(email, password);
const token = await auth.currentUser.getIdToken(true);

return res.json(token)

} catch (err) {
res.status(400).render('login', {
err: err.message,
style: 'login',
isRegister: false,
type: 'Login',
});
}
});

router.get('/loginDetour', async (req, res) => {
try {
const tokenBearered = req.headers.authorization;
res.setHeader('Authorization', tokenBearered);
return res.status(302).redirect('/');
} catch (err) {
res.status(400).json({ errMsg: error.message });
}
});


Middleware



const checkAuth = async (req, res, next) => {
if (!req.headers.authorization) {
return res.redirect('/login');
}
const token = req.headers.authorization.split('Bearer ')[1];
const decoded = await admin.auth().verifyIdToken(token);

if (!decoded.uid) {
return res.redirect('/login');
}
// const userRecord = await admin.auth().getUser(decoded.uid);
// console.log(userRecord.toJSON());
req.uid = decoded.uid;
next();
};

module.exports = checkAuth;


Front (Login)

1.login

2.fetch to the POST'/login'

3.Server gives TOKEN & Save to the local

4.fetch to the GET'/loginDetour' with token header

3.Server redirect to the '/'



<script type="module">
import { errAlert } from './js/errAlert.js'
import { defaultHeader }from './js/auth/auth.js'

const form = document.querySelector('.login-form')
const isRegister = {{isRegister}}

const authHandler = async(e) =>{
e.preventDefault();
const email = form['email'].value;
const password = form['password'].value;
let userName = ''
let password2 =''
if(isRegister){
userName = form['userName'].value;
password2 = form['password2'].value;
if(password !== password2){
errAlert("Password and Confirmed doesn't matched", 4000)
}
}
const url = isRegister ? '/register' : '/login'
const config = {
method: 'POST',
body: JSON.stringify({ email, password, userName }),
headers: {
'Content-Type': 'application/json',
},
};
const res = await fetch(url, config)
const token = await res.json()
if(token){
localStorage.setItem('token', token)
const config = {
method: 'GET',
redirect: 'follow',
headers: {
Authorization: `Bearer ${token}`,
}
};
axios('/loginDetour', config)
}
}
form.addEventListener("submit", authHandler)
</script>

SOS TTTTTTTTTTTTTTTTTTTTTTTTTT


More From » node.js

 Answers
2

I was wrong in the comments about being able to read a 3xx response, but if you allow the request to follow the redirects, you can check the redirected property and access the final url.
https://developer.mozilla.org/en-US/docs/Web/API/Response/url


Then it's just a matter of doing a client side redirect:


  fetch("/loginDetour").then(res => {
if (res.redirected) window.location = res.url;
});

My first comment still stands however, that unless you need to send the redirect url back from the server, it's much easier to do the redirect after the login request:


        const res = await fetch(url, config)
const token = await res.json()
if(token){
localStorage.setItem('token', token)
window.location = '/';
}

If you have a token, it means that the login was successfull, so just redirect there and save an extra HTTP request.




Off topic, but unless you are doing some funky cross-domain stuff, you'll be much better of putting the token in a cookie than localstorage.


From: https://balavishnuvj.com/blog/where-to-store-auth-tokens/



I would recommend storing all long-living tokens (like session ids, refresh tokens) in Cookie with httpOnly and SameSite enabled. As additional security, based on the application and the library/module you are using you can enable CSRF.



and https://twitter.com/ryanflorence/status/1370435079898497025



Followed a tutorial and put JWTs in localStorage?


If the guy behind UNPKG wanted to, he could inject code to JS requests
and collect all of your users JWTs. Same w/ any 3rd party scripts you
use.


2B req/mo is a lot of tokens.


I put that crap in signed, https, SameSite cookies.



[#1645] Tuesday, March 9, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
Sat, Aug 13, 22, 00:00, 2 Years ago
Sun, May 9, 21, 00:00, 3 Years ago
Tue, Sep 29, 20, 00:00, 4 Years ago
Wed, Aug 26, 20, 00:00, 4 Years ago
;