couchdb session and IE8 - couchdb

I am writing a couchapp, which uses the couch.jquery.js library.
When I login to the site with ie8, i get a successful login (it returns ok, and a login id), but when I query the session, I get a userCtx.name of null (just like if the login didn't happen).
It would seem that explorer will not keep the cookie from the login. Does anyone have any info on this?
I have tried J Chris's couchLogin.js library and written my own login scripts with the same problem.
The session code is:
$.couch.session({
success: function(data) {
console.log(JSON.stringify(data));
}
});
Response from IE:
{"ok":true,"userCtx":{"name":null,"roles":[]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"]}}
Response from Firefox / Chrome:
{"ok":true,"userCtx":{"name":"user1","roles":[]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"cookie"}}

I have solved this by editing jquery.couch.js, and adding cache:false to ajax call in the session function.
session: function(options) {
options = options || {};
$.ajax({
cache: false, //disable caching for IE
type: "GET", url: this.urlPrefix + "/_session",
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept', 'application/json');
},
complete: function(req) {
var resp = $.parseJSON(req.responseText);
if (req.status == 200) {
if (options.success) options.success(resp);
} else if (options.error) {
options.error(req.status, resp.error, resp.reason);
} else {
throw "An error occurred getting session info: " + resp.reason;
}
}
});
}

Related

Problem with validating header/data fields from JQuery AJAX to Backend flask API

I'm trying to pass JWT token and data fields via Jquery and then consume those values in Flask.
So, my client side query looks like this:
function getData() {
var data = {
UserPoolId : 'AWS CognitoUser Pool Id',
ClientId : 'AWS CognitoUser client Id'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
cognitoUser.getSession(function(err, session) {
if (err) {
alert(err);
return;
}
console.log('session validity: ' + session.isValid());
console.log(cognitoUser.signInUserSession.accessToken.jwtToken);
//
$.ajax({
url: "/api/v1/count",
type: "POST",
headers: { "X-Test-Header": cognitoUser.signInUserSession.accessToken.jwtToken },
// data: JSON.stringify(data),
data: JSON.stringify("{'UserPoolId': 'XXXX','ClientId': 'XXXX'}"),
contentType: 'application/json; charset=utf-8',
error: function(err) {
switch (err.status) {
case "400":
// bad request
break;
case "401":
// unauthorized
break;
case "403":
// forbidden
break;
default:
//Something bad happened
break;
}
},
success: function(data) {
console.log(data);
}
});
//
});
}
Now, in my serverside flask:
I tried to catch the token value using below: which is not working
#app.route("/api/v1/count", methods=["GET", "POST"])
def get_data_count():
if 'X-Test-Header' in request.headers:
headers = request.headers
app.logger.info(headers)
auth = headers.get("X-Test-Header")
app.logger.info('testing info log' + auth)
Also I tried to catch the data fields , using result = request.get_json() also not working.
I tried to inspect in chrome, and I don't see these values being added to the request header.
Can anyone suggest to me if I'm doing it correctly while passing the values from client to server? I also don't see console.log(cognitoUser.signInUserSession.accessToken.jwtToken) in the console log.
if not can anyone suggest to me, how to fix it?

EJS page not rendering /redirecting after req.getValidationResult() method

Ajax request has the following code:
function validate_referral(e){
// stop default action
e.preventDefault();
const button = this.children[this.children.length-1];
//Form Handling with ajax
$.ajax({
url : '/validatereferral',
method : 'GET',
data : $(this).serialize(),
dataType : 'json',
beforeSend : function(http){
button.style.opacity = '0.7';
button.innerText = 'Submitting';
button.setAttribute("disabled", "true");
},
});
}
Now i am validating in the DB if the code exists and if so i would like to render/redirect to a different web page. But render/redirection is failing. Any help is much appreciated.
router.get('/validatereferral',function(req,res){
var referralCode = req.body.referralcode;
if(referralCode == ""){
data = {msg:"Referral Code is required.",param:"",success:false};
}else {
var validation = req.checkBody('referralcode', 'Referral code already exist. Please enter a unique code').isExist_referralcodegen();
req.getValidationResult()
.then(function(result) {
var error = result.array();
var data;
if (!(error.length == 0)) {
data = {msg: "This is an invalid referral code.", success: false};
res.send(data);
}
console.log("validgen");
//res.redirect("http://localhost:3000/signup")
res.render('signup',{title:"Community Network | Sign Up",header:false,navbar:false});
})
}
});
You are sending an AJAX request. In AJAX response, redirect or render will not be reflected on your website. Instead your server should response the url and client have to change browser url.
$.ajax({
url : '/validatereferral',
method : 'GET',
data : $(this).serialize(),
dataType : 'json',
beforeSend : function(http){
button.style.opacity = '0.7';
button.innerText = 'Submitting';
button.setAttribute("disabled", "true");
},
}).done(function(data) {
location.href = data;
});
In server,
res.send("http://localhost:3000/signup")

Why is my cookie not available in my handler function when testing?

I am using Hapi and this is my handler function:
function propertyDetailsValidateHandler(request, reply, source, error) {
console.log(request.state)
var data = joiValidationHelper.checkForErrors(request, error);
if (typeof data !== "undefined"){
return reply.view('property-details', data).code(400);
} else {
var details = request.state.details;
details.propertyType = request.payload.propertyType;
details.newBuild = request.payload.newBuild;
return reply.redirect('/property-details/postcode').state('details', details, {path: '/'});
}
}
And this is my test written using Jasmine:
describe('tell us about the property youre buying flow', function(){
it('test /property-details, status code and location', function(done){
var options = {
method: 'POST',
url: '/property-details',
headers: {
cookie: {details: { test: "test"}}
},
payload: {
propertyType: "freehold",
newBuild: true
}
};
server.inject(options, function(response){
detailsTestCookie = response.headers['set-cookie'][0].split(';')[0];
expect(response.statusCode).toBe(302);
expect(response.headers.location).toMatch("/property-details/postcode");
done();
});
});
})
The handler function runs correctly when I run my server and use the browser but when I run the test request.state is an empty object when I was expecting it to be the cookie I provided in the test hence my test fails as request.state.details is undefined. Is this the correct way to provide the headers with a cookie in my test?
This works in our project, using tape and Hapi.
var cookie = the_cookie_you_want_to_send;
Then in your test payload:
headers: { cookie: `details=${cookie}`}
The cookie needed to be encoded as that is how the cookie was registered in our server file:
server.state('details', {
ttl: null,
isSecure: false,
isHttpOnly: false,
encoding: 'base64json', //this is not encrypted just encoded
clearInvalid: false, // remove invalid cookies
strictHeader: false // don't allow violations of RFC 6265
});

Express js - can't redirect

I am trying to do the following:
from client
var req = jQuery.post(
"http://www.example.com:3000"+"/dologin",
{"username" : username, "password" : password}).error(function(){
alert("an error occurred");
});
in express root
app.post('/dologin',function(req, res) {
res.redirect('http://bbc.co.uk');
});
result passed back
<p>Moved Temporarily. Redirecting to http://bbc.co.uk</p>
Seems that if I do post from jquery the redirect will not work. Does anyone know a way to force it to redirect?
Browser does not redirect the window on redirect on ajax response. Redirect the browser with javascript.
In server send the new site as content, for example.
res.contentType('application/json');
var data = JSON.stringify('http://site.example.com/')
res.header('Content-Length', data.length);
res.end(data);
In client
var req = jQuery.post(
"http://www.mysite.com:3000"+"/dologin",
{"username" : username, "password" : password}, 'json').error(function(){
alert("an error occurred");
}).success(function(data) {
window.location = data;
});
I've actually encountered the same thing when developing an app. It seems Express doesn't redirect if the method is post.
Try:
app.post('/dologin',function(req, res) {
req.method = 'get';
res.redirect('http://bbc.co.uk');
});
I'm doing something like this when using OAuth2. I have an link to one of my pages and this in turn redirects to google.
To redirect to another location the following code does the actual redirect
app.get('/GoogleRequestAuthorization.html',function(req,res) {
.
.
.
.
res.writeHead(302, {location: url});
res.end();
});
url being the address you want to redirect to.
The full function is...
I have come to a similar problem and solved it by checking the type of the request. In my case I use JSON, but it works for other POST requests as well:
var ajax = req.xhr;
if(ajax) {
res.status(401).json({'msg':'redirect','location':'/login'});
}
else {
req.method = 'get';
res.status(401).redirect('/login');
//Or if you prefer plain text
//res.status(333).send("Redirect");
}
This handles both Ajax POST and AJAX and standard GET requests.
On the client, in the Ajax respose callback:
$.ajax({
type: 'POST',
data: Msg,
url: '/some/post',
dataType: 'JSON'
}).success(function(data, textStatus, req ) {
if(data.msg==="redirect") window.location = data.location;
else {...}
}).error(function(data, textStatus, req) {
if(req=="Unauthorized") {
alert("Unauthorized!");
window.location = "/login";
} else if (data.responseJSON.msg==="redirect") window.location = data.responseJSON.location;
else {
//...
}
});
You can actually handle more statuses here, except for 302, which is automatically followed by JQuery and you get as response 200 from the page you wanted to redirect to. So I avoid sending the 302, sending 401 in my case, or any other status, for example 333, which will be handled as error.

Ajax request not working in IIS

This code runs in Visual Studio but not in IIS.
$('#addMessage').click(function () {
var textMessage = $('#ticketMessage').val();
var isInternal = $('#isInternal')[0].checked;
var ticketID = $('#TicketID').val();
$.ajax({
url: '/Ticket/AddMessage',
type: 'POST',
data: { textMessage: textMessage, isInternal: isInternal, ticketID: ticketID },
success: function (data) {
var tbody = $('#allMessages').children()[0];
tbody.innerHTML = tbody.innerHTML + data;
$('#ticketMessage').val("");
$('#isInternal')[0].checked = false;
}
});
});
What to fix in this code for the ajax request to run properly in IIS?
Please check with URL, Because sometimes the URL may point to 404 error page.
Because, the file is hosted in virtual folder. So, Please try with fully URL first, to check if it work fine. Better use Firebug or IE 9 developer tools. we can trace the Ajax requests.
I mean like this
$.ajax({
url: 'http://localhost/yourapplication/Ticket/AddMessage',
type: 'POST',
data: { textMessage: textMessage, isInternal: isInternal, ticketID: ticketID },
success: function (data) {
var tbody = $('#allMessages').children()[0];
tbody.innerHTML = tbody.innerHTML + data;
$('#ticketMessage').val("");
$('#isInternal')[0].checked = false;
}
});

Resources