How to get request.session in Vue.js - node.js

I'm trying to do authentication in my web site, so I've used express-session and tested with Postman.
Everything go well, but testing with Vue.js it's cannot get session, so how do I get the session on Vue.js.
app.js (Node.js)
router.post('/login', urlencodedParser, ldapAuth, async (req, res) => {
console.log(req.session)
if (!req.session.username) {
res.status(401).send('Auth failed, please log in.');
}
});
router.get('/session', async (req, res) => {
console.log(req.session)
if (req.session.username && req.cookies.user_sid) {
res.status(200).send(req.session)
} else {
res.status(401).send('Auth failed, please log in.');
}
})
login.vue
methods: {
login: e => {
e.preventDefault();
let username = e.target.elements.username.value;
let password = e.target.elements.password.value;
let login = () => {
let data = {
username: username,
password: password
};
PostServices.login(data)
.then(res => {
router.push("/content");
})
.catch(err => console.log(err));
};
login();
}
}
content.vue
methods: {
async getContent() {
const response = await GetServices.fetchSession();
console.log(response);
this.cont = response.session;
}
}
here some console.log output
http request with postman => https://imgur.com/a/EBNyFvT
http request with vue.js => https://imgur.com/a/T3AmPpL

Related

How to get the return value from the hook of fastify?

How to pass parameters from hooks to request handler in Fastify?
For example, I want to get the username in the BasicAuth hook from the request.
const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('#fastify/basic-auth'), { validate, authenticate })
function validate (username, password, req, reply, done) {
if (username === 'Tyrion' && password === 'wine') {
// How to return username from here?
done()
} else {
done(new Error('Winter is coming'))
}
}
fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)
fastify.get('/', (req, reply) => {
// How to get the username here?
})
})
You need to attach it to the request object:
const fastify = require('fastify')()
const authenticate = { realm: 'Westeros' }
fastify.register(require('#fastify/basic-auth'), { validate, authenticate })
// this decoration will help the V8 engine to improve the memory allocation for the request object
fastify.decorateRequest('user', null)
function validate(username, password, req, reply, done) {
if (username === 'Tyrion' && password === 'wine') {
// add it to the
req.user = { username }
done()
} else {
done(new Error('Winter is coming'))
}
}
fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)
fastify.get('/', async (req, reply) => {
return { hello: req.user.username }
})
})
fastify.inject({
method: 'GET',
url: '/',
headers: {
authorization: 'Basic ' + Buffer.from('Tyrion:wine').toString('base64')
}
}, (err, res) => {
console.log(res.payload)
})

Cannot fetch data from Nodejs backend to React frontend

I'm building MERN stack CRUD with goolge login
I'm running my server on port:3001
and frontend on port:3000
getAll() {
return axios.get("http://localhost:3001/jobs")
}
try to fetch data with session loggedin
router.get("/", util.isLoggedin, (req, res) => {
Job.find()
// .populate("author")
.limit(20)
.sort({ jobId: -1 })
.then((jobs) => res.json(jobs))
.catch((err) => res.status(400).json("Error:" + err))
})
const util = {}
util.isLoggedin = function (req, res, next) {
console.log(req.isAuthenticated())
if (req.isAuthenticated()) {
next()
} else {
console.log(req.isAuthenticated())
res.redirect("/")
}
}
module.exports = util
I can retrieve the data only on the server side, not frontend.
what can be the solution?
source code:
https://github.com/jamespark89/mern-communitywebsite
it seems like you are not awaiting your promise..
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}
replace
getAll() {
return axios.get("http://localhost:3001/jobs")
}
with
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}
Try to make your get request as an async function I usualy do that:
router.get("/", util.isLoggedin, async (req, res) => {
try {
const res = await Job.find()
// .populate("author")
.limit(20)
.sort({ jobId: -1 })
res.status(400).json({ res })
} catch(err) {
res.status(400).json("Error:" + err)
}
})

Why does my register user post request fail with a 500 error?

I'm building an app with React and Node/Express, and I'm having trouble with my register user function. The data I am passing in is correct, and other endpoints work fine. The register one keeps returning a 500 error and I can't figure out why.
This is my request:
console.log(values)
axios
.post(
'https://foodtrackr-backend.herokuapp.com/api/register',
values
)
.then(res => {
console.log('res.data', res.data);
})
.catch(error => {
console.log('nope');
console.error(error);
});
};
and this is my endpoint:
router.post('/register', async (req, res) => {
let user = req.body;
const newUser = await Users.add(user);
try {
if (newUser) {
res.status(201).json(user);
} else res.status(404);
} catch (error) {
res.status(500).json('noooooo');
}
});
and this is my model:
function findById(id) {
return (
db('users')
.where({ id })
.first()
);
}
async function add(user) {
const [id] = await db('users').insert(user, 'id');
return findById(id);
}
Any help would be appreciated!

Securely access route with JWT and localstorage

I'm building a small application where a user logs in and gets redirected to /profile. Right now, I fetch the JWT from localstorage and check it via the server. The server then sends it back to the client to tell me if it's a valid session or not.
jQuery/Client:
UserController.initPanel = () => {
if (session === null) {
window.location = "/";
} else {
UserController.requestAuth(session);
}
};
UserController.requestAuth = (sessionToken) => {
var settings = {
"url": "/api/auth",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": `Bearer ${sessionToken}`,
},
"data": ""
}
$.ajax(settings).done(function (response) {
console.log(response);
});
};
Node.js/auth.js route:
router.post("/", (req, res) => {
const authHeader = req.headers.authorization;
if (typeof authHeader !== 'undefined') {
const bearerToken = authHeader.split(' ')[1];
verifyToken(bearerToken, (authData) => {
tokenRequest(authData, (authResponse) => {
handleAuthResponse(req, res, authResponse);
})
});
}
});
const handleAuthResponse = (req, res, authResponse) => {
console.log(authResponse);
return res.status(200).json(authResponse);
}
const verifyToken = (token, cb) => {
jwt.verify(token, 'mysecret', (err, authData) => {
if (err) {
res.sendStatus(403)
} else {
cb(authData);
}
});
}
const tokenRequest = (authHeader, cb) => {
//console.log(authHeader);
var config = {
headers: {'Authorization': `bearer ${authHeader.token}`}
};
axios.get('https://myapi.dev/api/session/me', config)
.then((res) => {
if (res.data.error) {
return response.data
} else {
cb(res.data);
}
})
.catch((error) => {
console.log('error', error);
});
}
I feel like this isn't the correct way to do it. I'm rendering templates with ejs:
router.get("/profile", (req, res) => {
const settings = {
title: "Profile",
revslider: false
};
res.render("profile/profile", { settings: settings } );
});
And if for some reason, JS is disabled, /profile is still accessible. Which isn't that big of a problem, it just feels wrong.
So, is it possible to access /profile route, securely checking for authorization server-side first, before rendering?
Also, auth.js returns some user data I could use in the .ejs template. So that's another reason I'd like to try check auth before rendering as well.
EDIT:
Auth middleware, which I didn't use because I wasn't sure how to pass in the token?
module.exports = (req, res, next) => {
try {
const decoded = jwt.verify(req.body.token, 'mysecret');
req.token = decoded;
} catch (error) {
console.log(error);
return res.status(401).json({
message: 'Auth Failed'
});
}
next();
}
Very basic middleware implementation below which leverages express and express-session.
We basically create a simple function to check req.session exists, within that object, you could have something that identifies whether the user has actually authenticated. I'd recommend you add your own logic here to further check the user status.
const authCheckMiddleware = (req, res, next) => {
// Perform auth checking logic here, which you can attach
// to any route.
if(!req.session) {
return res.redirect('/');
}
next();
};
The authCheckMiddleware can be attached to any route, with app.use or router.use. The req object is passed to all middleware.
// Use the authCheckMiddleware function
router.use('/profile', authCheckMiddleware);
Your router.get('/profile') call is now protected by the above middleware.
// Route protected by above auth check middleware
router.get("/profile", (req, res) => {
const settings = {
title: "Profile",
revslider: false
};
res.render("profile/profile", { settings: settings } );
});

authentication and tokens node_js

i've got a problem
I'm trying to make a simple login page,
but i've problem with passing the token through http header
app.post('/login',(req,res) => {
var body = req.body.user;
User.findByCredentials(body.email,body.password).then((user) => {
return user.generateAuthToken().then((token) => {
res.header('x-auth', token).send(user);
});
}).catch((e) => {
res.status(400).send();
});
});
here is the route for login page, I saved the token in 'x-auth' in header, and it's work
but...
var authenticate = (req, res, next) => {
var token = req.header('x-auth');
User.findByToken(token).then((user) => {
if (!user) {
return Promise.reject();
}
req.user = user;
req.token = token;
next();
}).catch((e) => {
res.status(401).send();
});
};
module.exports = {authenticate};
this function is middle-ware for privet routes, when I asking for 'x-auth' i've got 'undifined'
here is the piece that connect between both codes
app.get('/',authenticate,(req,res) => {
res.sendFile(publicPath + '/index.html');
});
someone can help me with that?

Resources