NodeJS and Socket.io session handling - ios

I'm currently trying to set a session (req.session.username) inside a socket.io connection however it will set it but when I refresh and log out the req.session.username, it logs undefined.
I have my socket.io in a router.get callback:
router.get('/', function(req, res, next) {
var io = req.app.get('socketio');
io.sockets.on('connection', function(socket) {
socket.on('login', function(data) {
var username = data.username;
utils.getUser(data.username, function(obj) {
if(typeof obj != 'undefined') {
if(data.password == obj.password) {
req.session.username = username;
socket.emit('loginSuccess', {message: "You have successfully logged in, whats up " + data.username + "?"});
} else {
socket.emit('loginError', {message: "Invalid password, please try again."});
}
} else {
socket.emit('loginError', {message: data.username + " does not exist, please create an account."});
}
});
});
});
console.log(req.session.username);
res.render('./users/login', {
logged: false
});
});

Related

BBC Consumer SQS Issues

I'm using the sqs-consumer node module package.
I have the following code:
init: function () {
var app = Consumer.create({
queueUrl: Settings.getSetting("sendgrid-aws-sqs-queue"),
batchSize: 1,
visibilityTimeout: 30,
waitTimeSeconds: 20,
sqs: MarvelAWS.sqs,
handleMessage: function (message, done) {
try {
var msgBody;
try {
msgBody = JSON.parse(message.Body);
} catch (err) {
msgBody = null;
this._warn("parsing error handling SQS queue " + err, msgBody);
}
var environment = Settings.getSetting('environment');
if (validateMsg(msgBody) && (environment !== "prod" || this.LIST_TO_ID[msgBody.listId.toString()])) {
var userProfile = msgBody.profile,
timeSent = msgBody.timeSent,
action = msgBody.action,
listId = msgBody.listId.toString(),
suppressionListId = msgBody.suppressionListId.toString();
_.each(this.actionsMap[action], function (oneAction) {
this._debug(oneAction + ':' + listId + ' ' + msgBody.profile.email);
sendgridQueueManager.createQueue({
action: oneAction
});
sendgridQueueManager.push({
action: oneAction,
listId: listId,
suppressionListId: suppressionListId,
timeSent: timeSent,
profile: userProfile
});
}.bind(this));
EngineMonitor.countOperation(EngineMonitor.OPS.SENDGRID_SQS_QUEUE_PULL_SUCCESS);
} else {
this._warn("validation error", msgBody);
EngineMonitor.countOperation(EngineMonitor.OPS.SENDGRID_SQS_QUEUE_PULL_ERROR);
}
done();
} catch (err) {
this._warn("error_processing_message " + err);
done(new Error('error processing message'));
}
}.bind(this)
});
app.on("message_received", function () {
this._debug("message_received");
EngineMonitor.countOperation(EngineMonitor.OPS.SENDGRID_SQS_QUEUE_MESSAGE_RECEIVED);
}.bind(this));
app.on("message_processed", function () {
this._debug("message_processed");
EngineMonitor.countOperation(EngineMonitor.OPS.SENDGRID_SQS_QUEUE_MESSAGE_PROCESSED);
}.bind(this));
app.on("error", function (err, message) {
this._warn("message_error " + err + " " + message);
EngineMonitor.countOperation(EngineMonitor.OPS.SENDGRID_SQS_QUEUE_PULL_ERROR);
}.bind(this));
app.on("processing_error", function (err, message) {
this._warn("processing_error " + err);
EngineMonitor.countOperation(EngineMonitor.OPS.SENDGRID_SQS_QUEUE_PULL_ERROR);
}.bind(this));
app.start();
this._debug('sqs_app_start');
},
sometimes a message gets added to the SQS queue but doesn't not get received by the consumer/
Here are my sqs queue settings:
Can someone please help?
In what cases do a message get added to the Queue and not received by the consumer?

How to store chat messages in database?

I'm using Node.js with Rails for a basic chat app. Now when i refreshed the page all messages get deleted. So i want to store messages in rails database using AJAX.
How can i do this?
nodejs/index.js
console.log("Server is starting...");
const http = require('http');
const hostname = '0.0.0.0';
const port = '8000';
console.log("Creating server...");
const server = http.createServer().listen(port, hostname);
console.log('chat server running on '+ hostname + ':' + port);
let socketList = require('socket.io').listen(server);
socketList.sockets.on('connection', function (socket) {
console.log('connection received');
console.log('socket in node = ', socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
socket.on('join_room', function (data) {
socket.join(data.chatroom);
socketList.in(data.chatroom).emit('user_joined', {
user_email: data.user_email,
chatroom: data.chatroom
});
});
socket.on('send_message', function (data) {
console.log(data.message, data.user_email);
socketList.in(data.chatroom).emit('receive_message', {
message: data.message,
user_email: data.user_email
});
});
});
rails/application.js
window.addEventListener('load', function (ev) {
var user_email = $('#current_user_email').html(); // checking if user login
if(user_email){
var socket = io.connect('http://0.0.0.0:8000');
console.log('socket in rails = ' , socket);
socket.on('connect', function () {
console.log('connection established to node server');
});
socket.emit('join_room',
{
user_email: user_email,
chatroom: 'home'
});
socket.on('user_joined', function (data) {
console.log(data.user_email + ' joined ' + data.chatroom);
});
$('#send-message').click(function () {
let msg = $('#chat-message-input').val();
if(msg !==''){
socket.emit('send_message', {
message: msg,
user_email: user_email,
chatroom: 'home'
});
}
$('#chat-message-input').val('');
});
socket.on('receive_message', function (data) {
console.log(data.user_email, data.message);
let newMessage = $('<li>');
let messageType = 'other-message';
if (data.user_email === user_email){
messageType = 'self-message';
}
newMessage.addClass(messageType);
newMessage.append($('<span>', {
'html': data.message
}));
newMessage.append($('<sub>', {
'html': data.user_email
}));
$('#chat-messages-list').append(newMessage);
});
Also what are the different methods can be used to store messages in database?
Can we also store directly in the Rails database just using Node.js?
Not gonna write code but basically u can start:
rails g scaffold Chat name:text chat:text
then post with ajax to /chat.json set data like {name:user_name, chat:texxt}
Then also u need to ask all user chats from /chat.json
Also u need to write in rails in index function
if params[:id]) do
#chat = Chat.find(name:username)
else
#chat = Chat.all
end
Then show those messages to user
but this is basic concept to get u going

Titaniuim: Facebook login event doesn't fire

I am trying to login through facebook.
I have all info in plist and in entitlelements file
So when I click to button it is redirecting safari facebook page and asking to confirm
When I click to OK it doesn’t fire ‘login’ event and it is not logged.
Currently I am testing on iOS 5s Simulator
Here is the code
var fbook = require('facebook');
fbook.appid = <MyAPP_ID>;
fbook.permissions = ['public_profile'];
//fbook.forceDialogAuth = true;
if (fbook.loggedIn) {
//progress.hide();
params = {
access_token : fbook.accessToken
};
fbook.requestWithGraphPath('/me', params, 'GET', function(e) {
var result = JSON.parse(e.result)
});
} else {
fbook.addEventListener('login', function(e) {
//alert('try to login');
if (e.success) {
//progress.hide();
params = {
access_token : fbook.accessToken
};
fbook.requestWithGraphPath('/me', params, 'GET', function(e) {
var result = JSON.parse(e.result);
Ti.API.info("Result is : " + e.result);
});
} else if (e.error) {
Ti.API.info("error");
//alert('Error: ' + e.error);
} else if (e.cancelled) {
Ti.API.info("cancelled");
}
});
fbook.authorize();
/*
fbook.addEventListener('logout', function(e) {
fbook.logout();
});*/
}

How to get updated session data on rails using AngularJs without page refresh

I'm currently working on integrating devise as an authentication backend with angular as its frontend.
I have faced a problem on when login and logout, the session data will be updated untill the page refresh.
What i will do get session data without page refresh..?
Thanks for your Answers...
AngularJs Controller :
function UsersCtrl($scope, Session) {"use strict";
$scope.CurrentUser = Session.requestCurrentUser();
$scope.login = function(user) {
$scope.authError = null;
Session.login(user.email, user.password)
.then(function(response) {
if (!response) {
$scope.authError = 'Credentials are not valid';
} else {
$scope.authError = 'Success!';
}
}, function(response) {
$scope.authError = 'Server offline, please try later';
});
};
$scope.logout = function() {
// alert("woow");
Session.logout();
};
$scope.register = function(user) {
$scope.authError = null;
console.log(user);
Session.register(user.email, user.password, user.confirm_password)
.then(function(response) {
}, function(response) {
var errors = '';
$.each(response.data.errors, function(index, value) {
errors += index.substr(0,1).toUpperCase()+index.substr(1) + ' ' + value + ''
});
$scope.authError = errors;
});
};
}
AngularJs Session Service:
angular.module('sessionService', ['ngResource'])
.factory('Session', function($location, $http, $q) {
// Redirect to the given url (defaults to '/')
function redirect(url) {
url = url || '/';
$location.path(url);
}
var service = {
login: function(email, password) {
return $http.post('/users/login', {user: {email: email, password: password} })
.then(function(response) {
service.currentUser = response.data.user;
if (service.isAuthenticated()) {
//$location.path(response.data.redirect);
$location.path('/store');
}
});
},
logout: function() {
$http.delete('/sessions').then(function(response) {
$http.defaults.headers.common['X-CSRF-Token'] = response.data.csrfToken;
service.currentUser = null;
redirect('/store');
});
},
register: function(email, password, confirm_password) {
return $http.post('/users', {user: {email: email, password: password, password_confirmation: confirm_password} })
.then(function(response) {
service.currentUser = response.data;
if (service.isAuthenticated()) {
console.log("authenticated");
$location.path('/');
}
});
},
requestCurrentUser: function() {
if (service.isAuthenticated()) {
return $q.when(service.currentUser);
} else {
return $http.get('/users').then(function(response) {
service.currentUser = response.data.user;
return service.currentUser;
});
}
},
currentUser: null,
isAuthenticated: function(){
return !!service.currentUser;
}
};
return service;
console.log(service);
});
One Thing about building applications like this (restful) is that understanding the the backend as an api and app as a front-end very well.
Then think about a story as such;
In the login screen of your app
Front-end: You Provided the credentials to your backend;
Back-end: Checked and authenticated then It will create a unique hash stored in db (JWT recommended to check expiration in frontend) to your Front-end.
Front-end:Save it in a cookie.
Also place it in your ajax setting header part as "Authorization: {token}"
Front-end: Then send each request with this header to your backend.
Back-end: Always check if the token is present and valid to provide resources.
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/ this link has helped me understand the whole thing and misconceptions in the past.
use $window.location.reload(); before page redirect.
One way to achieve this could be overriding the devise sessions_controller destroy action and afrer doing sign_out #current_user return the session as json

JsonResult returns HTML response

I have this method in a controller to reset the password of a user by mail.
public JsonResult RecoverPasswordByEmail(string mail)
{
MembershipUser member = Membership.GetUser(Membership.GetUserNameByEmail(mail));
string newPassword = System.Web.Security.Membership.GeneratePassword(14, 0);
member.UnlockUser();
if (!member.ChangePassword(member.ResetPassword(), newPassword))
{
return Json(new { Resultado = false, Excepcion = "Couldn't change password" }, JsonRequestBehavior.AllowGet);
}
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("foo#bar.com");
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mail);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);
message.Subject = "Forgot pass";
if (member.IsLockedOut)
{
message.Body = "You're locked";
}
else
{
message.Body = "New password: " + newPassword;
}
var client = new System.Net.Mail.SmtpClient("my.smtpserver.com", 587)
{
Credentials = new System.Net.NetworkCredential("foo#bar.com", "12345"),
EnableSsl = true
};
try
{
client.Send(message);
}
catch (System.Net.Mail.SmtpException ex)
{
return Json(new { Resultado = false, Excepcion = ex.Message }, JsonRequestBehavior.AllowGet);
}
return Json(new { Resultado = true }, JsonRequestBehavior.AllowGet);
}
I do an ajax request using jQuery from a button in a dialog from the login View.
The weird thing is that I use another controller method RecoverPassword that does the same thing but by the username and that works. Using firebug I see that RecoverPassword does the job and returns a JSON with the result, but RecoverPasswordByEmail responds with a big html document.
The important part of the HTML:
<div id="dialog">
<h2>Retrieve Password</h2>
#Html.Label("Mail:")<br/>
#Html.TextBox("txtMail")
<div id="loading">
<br/><img class="displayed" src="#Url.Content("~/Content/Images/Ajax/ajax-loader3.gif")" alt="loading" /><br/>
#Html.Label("Error")
</div>
<br/><br/><input class="button" id="btnSendMail" type="submit" value="Get new password" />
<div>
Recuperar contraseña
</div>
</div>
And the js:
$(document).ready(function () {
var requestMail;
$('#btnSendMail').button();
$('#loading').hide();
$("label[for=Error]").text("");
$('#btnSendMail').click(function (event) {
event.preventDefault();
var mail = $("#txtMail").val();
if (mail.length > 0) {
if (requestMail && requestMail .readystate != 4) {
requestMail .abort();
}
$('#loading').show();
$('input[id="btnSendMail"]').attr('disabled', 'disabled');
requestCorreo = $.ajax({
url: '/Users/RecoverPasswordByEmail',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
timeout: 8000,
data: { Email: mail },
success: function (response) {
if (response.Result) {
$("label[for=Error]").text('New password has been sent to: ' + mail);
}
else {
alert(response.Result + ' ' + response.Exception);
}
},
error: function (xhr, textStatus, thrownError) {
if (textStatus === "timeout") {
alert("got timeout");
}
else {
alert(xhr.status + ' ' + textStatus + ' ' + thrownError);
}
},
complete: function () {
$('#loading').hide();
$('input[id="btnSendMail"]').removeAttr('disabled');
}
});
}
else {
$("label[for=Error]").text("Insert a valid email");
}
requestCorreo.done(function (msg) {
alert(msg);
});
requestCorreo.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus + " " + jqXHR.responseText);
});
});
});
What is in the HTML that is returned? I'm going to bet that your method is throwing an exception, which is caught by ASP.NET, and an error page is returned rather than the JsonResult from your method.
Or it not, the content of the HTML would help shed more light on the issue.
As a side note, you don't seem to be checking null anywhere in your method - and you're assuming the MembershipUser will be found no matter what email address is passed (which may indeed be the source of your exception).

Resources