make rest api in nodejs for if not loged in - javascript

I want an API for which if user is not logged in then redirect to homepage /
but this api is access by both web and android.
So i made like this for both web and app .
function requiresLogin(req, res, next) {
if (req.session && req.session.userID) {
return next();
} else {
res.send({status : "logout" , message : "Please Login First"});
}
}
I don't understand how to redirect to homepage / by web-end
because If i am using res.redirect('/homepage') then what about app.
My ajax part is this
$(document).ready(function() {
$.ajax(
{
success: function (result) {
alert(alert.status);
if (result.status === "logout") {
window.location = '/';
}
else {
}
},
error: function (err) {
console.log(err);
}
});
});
but nothing happens.
Thanx in advance.

Related

nodejs does not emit data to client

I have simple nodejs app with sockets and I've faced an error where I can't find any solution. So I'm emiting from app to client and nothing happens there. Or client can't receive it - I don't know, because I can't check if it was successfully emited to client. This is the error I got when I tried to debug callback of emit:
Error: Callbacks are not supported when broadcasting
This my app code:
http.listen(6060, function () {
console.log("Listening on *: 6060");
});
io.set('authorization', function (handshakeData, accept) {
var domain = handshakeData.headers.referer.replace('http://', '').replace('https://', '').split(/[/?#]/)[0];
if ('***' == domain) {
accept(null, true);
} else {
return accept('You must be logged in to take an action in this site!', false);
}
});
io.use(function (sock, next) {
var handshakeData = sock.request;
var userToken = handshakeData._query.key;
if (typeof userToken !== null && userToken !== 0 && userToken !== '0' && userToken.length > 0) {
connection.query('***',
[xssfilter.filter(validator.escape(userToken))],
function (error, data) {
if (error) {
debug('Cant receive user data from database by token');
next(new Error('Failed to parse user data! Please login!'));
} else {
// load data to this user.
_updateUsers(xssfilter.filter(validator.escape(userToken)), 'add', data[0], sock.id);
_loadPreData();
next(null, true);
}
});
} else {
debug('Cant receive user token');
next(new Error('Failed to parse user data! Please login!'));
}
sock.on("disconnect", function () {
_updateUsers(false, 'remove', false, sock.id);
});
});
// we need to show people online count
io.emit('online-count', {
count: Object.keys(connectedUsers).length
});
And the function used above:
function _updateUsers(userToken, action, userData, sockedID) {
switch (action) {
case 'add':
connectedUsers[sockedID] = {...};
io.emit('online-count', io.emit('online-count', {
count: Object.keys(connectedUsers).length
}););
break;
case 'remove':
delete connectedUsers[sockedID];
io.emit('online-count', io.emit('online-count', {
count: Object.keys(connectedUsers).length
}););
break;
}
}
so after emiting online-count I should accept it on the client side as I'm doing it:
var socket;
socket = io(globalData.socketConn, {query: "key=" + globalData.userData.token});
socket.on('connect', function (data) {
console.log('Client side successfully connected with APP.');
});
socket.on('error', function (err) {
error('danger', 'top', err);
});
socket.on('online-count', function (data) {
console.log('Got online count: ' + data.count);
$('#online_count').html(data.count);
});
but the problem is with this online-count.. Nothing happens and it seems that it's not was even sent from node app. Any suggestions?
The problem was with my logic - I was sending online count only if new user were connecting/disconnecting. Problem were solved by adding function to repeat itself every few seconds and send online count to client side.

Phantomjs authentication with node.js to access mean.js page

I need to access a mean.js web site page with phantomjs. The problem is I dont know what to include in the header to make it happen.
I can authenticate using http.request and get back the user object. But then I need to somehow take that information and place it in the phantomjs header to allow access to the page.
Here is some code:
'use strict';
var phantom = require('node-phantom-simple');
phantom.create({ path: require('phantomjs').path }, function (err, browser) {
if (err) {
console.log(err);
}
else {
browser.createPage(function (err, page) {
if (err) {
console.log(err);
}
else {
//this is wrong - does not work with mean.js/passport authentication
var authentication_data = { 'Authorization': 'Basic ' + new Buffer('<user>:<password>').toString('base64') };
page.set('customHeaders', authentication_data, function (err) {
if (err) {
console.log(err);
}
else {
var htmlPath = 'http://localhost:3000/path-to-my-web-page';
var complete = false;
page.onConsoleMessage = function (msg) {
console.log('Console: %s', msg);
if (msg === 'the page is loaded') complete = true;
};
return page.open(htmlPath, function (err, status) {
console.log('opened page ', status);
if (err) {
console.log('page.open', err);
}
else {
console.log('opened ' + htmlPath);
//stuff happens here after page is loaded
}
});
}
});
}
});
}
});
I am missing the piece that says it is ok to access the page.
Thanks for your help!

Why do I get Can't find variable: GlobalStore in React Native ios Facebook login

I'm using the following module in my React Native app in order to login users with Facebook. https://github.com/facebook/react-native-fbsdk
I logged the following issue.
https://github.com/facebook/react-native-fbsdk/issues/58
I have the following in my view and I get the GlobalStore can't find error.
var FBSDKLogin = require('react-native-fbsdklogin');
//init facebook login
fbTouchHandler(event) {
FBSDKLoginManager.setLoginBehavior(GlobalStore.getItem('behavior', 'native'));
FBSDKLoginManager.logInWithReadPermissions([], (error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCancelled) {
alert('Login cancelled.');
} else {
alert('Logged in.');
}
}
});
}

accessToken on faceook php sdk 4.0 and Javascript sdk on laravel

I use js-sdk with php-sdk and this is my php code when js is login
loginController.php
FacebookSession::setDefaultApplication('appid','sec');
$helper = new FacebookJavaScriptLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Work!
}
it work at first and Not work when php session is expire
js is work fine.
this is my js
.js on index page
function Login() {
FB.login(function(response) {
if (response.status === 'connected') {
FB.api('/me', function(data) {
if(data.email == null) {
// Fail
} else {
// OK redirect to .php
window.location.href = "{{ action('UserController#getLogin') }}"
}
});
} else {
// Fail
}
}, {scope: 'public_profile,email'});
}
OK I got that
I for got
cookie : true,
on
FB.init
= = my 3 hours back pls.

Ajax request not working when signed in, works when not signed in

I have an Ajax request that is simple like this:
$.ajax({
type: "POST",
url: "/admin.html",
data: dataString,
success: function(data) {
if(data.error) {
$('#alertt').text(data.error);
$('#alertt').show();
$('#alertt').fadeIn().delay(2000).fadeOut('slow');
} else if (data.success) {
var lati = $('#route_latitude').val();
var longi = $('#route_longitude').val();
increment();
setMarker(lati, longi);
$('#alertt').text(data.success);
$('#alertt').show();
$('#alertt').fadeIn().delay(2000).fadeOut('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + " " + errorThrown)
}
})
The problem is, that if the user is signed in on the webpage, then it sits at (pending) for about 5 minutes then 500 errors, I'm not sure why this is, I'm using Express v3 and this is basically how the request goes:
var isAdmin = function(req, res, next) {
helper.isAdmin(req, res, next);
}
app.post('/admin.html', isAdmin, admin.new);
exports.isAdmin = function(req, res, next) {
db.users.find({'rememberToken': req.cookies.rememberToken}, function(err, foundUser) {
if (err) { console.log('We have an error' + err) } else {
if (foundUser.length === 0) {
console.log('Somebody attempted to view the Admin page without an account.')
res.render('index', { 'title': 'Home Page'})
} else if (foundUser[0].admin === 0) {
console.log('A non-admin user account tried to log into the Admin page: ' + foundUser[0].email);
res.render('index', { 'title': 'Home Page' });
} else if (foundUser[0].rememberToken === req.cookies.rememberToken) {
console.log('Admin viewing Admin page.');
next();
}
}
})
}
I really can't see anything wrong, yet for some reason it just sits at (pending) but if I do it not-logged in with no cookie set, (with the isAdmin function removed from the post) it works. Any help would be great this has been driving me nuts.
If you're curious how the sign in is handled: https://gist.github.com/anonymous/f458783ffdc45255f85d/raw/dd59d045b7fa76abc2dca458eea16702477c36d1/gistfile1.js
This actually works completely as intended on localhost, but when I push it to Nodejitsu, it doesn't work and this problem happens.

Categories