I'm trying to implement a basic login mechanism based on this answer: http://stackoverflow.com/a/8003291/5111904
In my backend I'm handling the login post request like this:
app.post('/login', function (req, res) {
console.log(req.body);
if (req.body.user === 'normal' && req.body.password === '12345') {
req.session.user_id = 0; // This is failing (req.session is undefined)
res.redirect('/index');
} else {
res.send('Bad user/pass');
}
});
The server is using https:
server = https.createServer(https_options, app).listen(PORT, HOST);
When the client is clicking the login button this code is getting executed:
function postLogin(){
var url = "/login";
var xhr = new XMLHttpRequest();
var data = {
user: userInput.value,
password: passwordInput.value
};
xhr.open("POST", url, true);
xhr.onreadystatechange = function (oEvent) {
if(xhr.readyState === 4){
// Checking status codes
if(xhr.status === 200){
onSuccess(xhr.responseText, xhr.responseType);
}
else{
console.log(xhr.status);
onError();
}
}
}
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
console.log("Sending this data: " + JSON.stringify(data));
xhr.send(JSON.stringify(data));
}
After the login the user should get redirected to the index page:
app.get('/index', (request, response) => {
response.render('main', {});
})
So I got this issues:
- In the first code snippet req.session is undefined
- In the secod snippet the value of (xhr.responseText) evaluates to the html of the index page (where the user should be redirected)
- How do I redirect the user to the index page in a proper way?
There will be only one valid user so this code is not intended to be used by many people and it should only provide a basic type of security.
via Matthias Herrmann
No comments:
Post a Comment