handling http 302 redirect in nyroModal - asp.net-mvc-3

I'm using nyroModal v2 in an ASP.NET MVC3 application. The application forces users to authenticate and the auth cookie has max. lifetime of two hours. When the auth cookie expires all requestes are redirected to a login page (using http status code 302).
When a user opens a link in a modal "window" (using jQuery plugin nyroModal) and the auth cookie is expired nyroModal shows "an error has occoured". I managed to add a callback function to handle all errors
$(this).nyroModal({
callbacks: {
error: function (nm) {
alert("some error");
}
});
but I don't see a way to decide what kind of error (http status code) has happened. Is there an error object in nyroModal?
What I want to achieve is: close the modal window and redirect the browser window to the login page.
Thanks in advance!
Thomas

$(window).ajaxComplete(function(ev, xmlhr, options){
try {
var json = $.parseJSON(xmlhr.responseText);
}
catch(e) {
console.log('Session OK');
return;
}
if ($.isPlainObject(json) && json.SESSION == 'EXPIRED') {
console.log('Session Expired');
return;
}
console.log('Session OK');
});

Related

(VueJS, Axios) Different way to catch errors

I'm currently building a single page application based on Laravel and VueJS.
Is there any better way then mine to handle errors with axios?
This is how I currently do it when a user clicks on login button:
VueTemplae:
methods : {
authenticateUser() {
axios.post('/api/login', this.form).then(() => {
this.$router.push({name : 'home'});
}).catch((error) => {
this.error = error.response.data.message;
});
}
}
Api route:
public function login() {
try {
// do validation
} catch(Exception) {
// validation failed
throw new Exception('login.failed');
}
// manually authentication
if(Auth::attempt(request()->only('email', 'password'))) {
return response()->json(Auth::user(), 200);
}
// something else went wrong
throw new Exception('login.failed');
}
Unfortunately, throwing an exception always prints an internal server error into the console.
If I return something else than an exception, axios always executes then().
Is there any way to prevent this or a better way to handle axios responses?
Thank you!
Your API needs to return a response with a 4XX status code in order for the catch block to fire in your Vue component.
Example:
After you catch the error on the API side, send a response with status code 400 Bad Request. It will be formatted similarly to your successful login response, but with an error message and 400 status code instead of 200.

How to detect response in VueJS?

I ask the help of knowledgeable people
im create a RESTfull API project on Vue.js (Vuex also)
And im get small problem
The server to which I am sending the request is down why how idn
Can someone tell me how can im detect this message from response
This response dont have any massege, error, status, statusText, text, preview and response
All this field is empty
If someone have expirience about this or some info I will be very grateful for that
You can do something like this to handle these cases:
submitRequest() {
axios.post('/api/test', this.testData)
.then(response => {
// handle success
})
.catch(function(error) {
// handle error
if (error.response) {
// The request was made and the server responded with a status code
} else if (error.request) {
// YOU CAN HANDLE IT HERE
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
}
});
}

Express.js res.render not redirecting, just displayed in console

This time I want to use res.render to display html as success of DB update. I did it several times, but this time it doesn't work. It's not render html file, just displayed on chrome's console.
I think it caused because of async problem or duplicated response. I tried to many ways but I couldn't solve it, so pointers appreciated.
The code is related when the user paid service, increase user's level.
Get Access Token => Validate => res.render
app.post('/payment/validate', function(req, res, next){
// Get access token
request.post({
url : 'https://payment-company/get/token'
}, function(err, response, body) {
if(!err & response.statusCode == 200) {
var result = JSON.parse(body);
var accessToken = result.response.access_token;
// Validate payment (compare paid and would be paid)
request.get({
headers : { 'Authorization' : accessToken }
url : 'https://payment-company/find/paymentid'
}, function (err, response, body) {
if (!err && response.statusCode == 200){
var result = JSON.parse(body);
if (result.response.amount == req.body.price){
Members.findOne({id : req.user.id}, function(err, member){
// If no problem, update user level
member.level = 2;
member.save(function(err, result){
if (err) return next();
res.render('payment.view.result.ejs',
{
title : 'Success !',
description : 'level up.'
});
});
});
}
} else {
...
}
});
}
})
});
sorry to verbose code I tried to shorten code, No problem until res.render, res.render will work but it's not display page instead it just send html code to chrome's console.
Looks like there's a bit of a misunderstanding of how these requests work. What I think you intend:
Browser makes a GET request, server responds with an HTML document, the browser renders it
User takes an action
Browser makes a POST request, server responds with an HTML document, the browser renders it
What you've started coded on the frontend is an alternate method:
You make a POST request via AJAX, server responds with some JSON, you modify the current document with JavaScript to let the user know

No callback when calling yam.platform.login

When using Yammer SDK and using yam.platform.login method, I don't get any callback when authentication fails or when the user closes dialog window. Is this a bug or something you have seen in your Yammer integration tasks?
My code
yam.platform.getLoginStatus(function (response) {
if (response.authResponse) {
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
console.dir(response);
}
else {
### CODE NEVER EXECUTED IF LOGIN FAILS OR USER CLOSE POPUP###
}
});
}
});
Make sure to add your web application url to "Javascript Origins" of your registered yammer app.
Make sure you added your web app url to "Trusted Sites" and other Yammer urls.
We get this problem (no callback on yam.platform.login) when the user is currently logged into a network other than the home network (network where app is registered). If your users use multiple networks, you may need to add your app to the global app register.
An alternative (hacky) way is to 'try' the approach below. This worked for us as it only needed to happen once (to get the auth token).
yam.getLoginStatus(function(resp){
if (resp.authResponse) {
//success
} else {
// not logged in
var yamLoginSuccess=0;
try {
yam.platform.login( function (response) { //prompt login
console.log('no response here if user in another network');
if (response.authResponse) {
//success
yamLoginSuccess=1;
}
});
}
catch(err) {
// does not throw an error so this bit is not helpful
}
finally{
if(yamLoginSuccess===0){
alert('Need to be logged into the home yammer first :-/ /n '
+ 'Redirecting now, hit back to come back');
window.location='https://www.yammer.com/YOURNETWORK/';
}
}
}
});

How to use Passport-Facebook login without redirection?

I'm building a phonegap application which will have nodejs at the server side. I wanted to implement login using passport-facebook strategy but their callbacks specify two routes, /successcallback and /failurecallback. Having a single page application, this makes it very confusing to have users redirected to so and so page.
I don't want to serve static files (index.html, login.html) from the server but rather have them on the client and ask the client to make ajax calls. So far, I'm able to make /auth/facebook call as an AJAX request but I can't receive any response on the same request because the login strategy requires the user to be redirected. I'd rather want to send a user_id or name back to the user on successful login or show him the login form (which is also on the www directory in phonegap) on failure. But the redirection and CORS errors are preventing me from doing this. Is there any way I can implement this? I've looked for this since a few weeks now, but no success. I'd really appreciate your help!
PS: I'd rather avoid having to send all html and static content from the node server.
EDIT: Adding login code for better understanding:
app.get('/userpage', utility.isLoggedIn, function(req, res)
{
res.send('User:'+req.user);
});
app.get('/', utility.isLoggedIn, function(req, res)
{
res.redirect('/userpage');
});
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',passport.authenticate('facebook',
{
successRedirect : '/',
failureRedirect : '/login'
}));
app.get('/logout', function(req, res)
{
req.logout();
res.redirect('/login');
});
utility.isLoggedIn:
function isLoggedIn(req, res, next)
{
if (req.isAuthenticated())
return next();
res.redirect('/login');
}
You can't do that with facebook oAuth, but Facebook provides another login solution where you can code your client app to request a token, that you can later validate on the server with passport-facebook-token.
This way you can use the advantages of passport for persistent sessions, without that annoying redirection.
Instead of using the standard redirections offered by passport, you can define your own function which will be executed instead of the redirection. Here's an example of what that code would look like
passport.authenticate('login', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.json({ status:"failed", "error": "Invalid credentials" }); }
// req / res held in closure
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.json({ "status":"success"});
})
})(req, res, next);

Resources