Is there a way to enforce single device login on parse.com? - ios

I am developing an app where I need to be very API request frugal, the less requests the better. The problem is every user has settings and messages and I want to avoid to pull for possible changes on every wake up. And I can't rely on that every user enables push notifications.
My approach is as a compromise to enforce that a user can only be logged in with one device. If they try to login with another device (via facebook) they get an error message where they can choose to either cancel the login or go ahead and logout the other device remotely.
Is this possible?

I found a solution to this problem.
Query number of sessions after login
If the number is greater than 1 ask user what do
logout other device (and go ahead) -> call "deleteAllOtherSessions"
cancel login (and go back to login screen) -> call "deleteLastSession"
Cloud code:
Parse.Cloud.define("getSessionCount", function(request, response) {
if (request.user == null) {
reportError("findSessions", "userCheck", 0);
response.error("invalid user");
return
}
var query = new Parse.Query(Parse.Session);
query.find({
success: function(results) {
response.success(results.length);
},
error: function(error) {
response.error(error);
}
});
});
Parse.Cloud.define("deleteAllOtherSessions", function(request, response) {
if (request.user == null) {
reportError("deleteAllOtherSessions", "userCheck", 0);
response.error("invalid user");
return
}
var sessionToken = request.params.sessionToken;
var query = new Parse.Query(Parse.Session);
// this query will find only sessions owned by the user since
// we are not using the master key
query.find().then(function(results) {
var promises = [];
_.each(results, function (result) {
if(result.get("sessionToken") != sessionToken) {
promises.push(result.destroy());
}
});
return Parse.Promise.when(promises);
}).then(function() {
response.success(true);
},
function(error) {
response.error(error)
});
});
Parse.Cloud.define("deleteLastSession", function(request, response) {
if (request.user == null) {
reportError("deleteLastSession", "userCheck", 0);
response.error("invalid user");
return
}
var sessionToken = request.params.sessionToken;
var query = new Parse.Query(Parse.Session);
query.descending("createdAt");
// this query will find only sessions owned by the user since
// we are not using the master key
query.find().then(function(results) {
var promises = [];
console.log(results);
promises.push(results[0].destroy());
return Parse.Promise.when(promises);
}).then(function() {
response.success(true);
},
function(error) {
response.error(error)
});
});
Hope that helps somebody.

Related

Focus tab and change page with service worker

We need a little help with a service worker. What we want to do is to click on notification, to execute service worker code and to check if the site is yet opened in a tab: if the site is not opened, we want to open a new tab and to navigate to a predefined url, if it is opened, we want to focus tab and then to navigate to a predefined path of the site.
We tried the code below but it doesn't work, cause we get some errors such as 'the service worker is not the active one' and so on.
Any help is really appreciated
Thanks
event.waitUntil(clients.matchAll({type: 'window' }).then(function (clientList) {
let openNewWindow = true;
for (let i = 0; i < clientList.length; i++) {
const client = clientList[i];
if (client.url.includes('localhost') && 'focus' in client) {
openNewWindow = false;
client.focus()
.then(function (client2)
{ return client.navigate(openUrl)});
// });
}
}
if (openNewWindow) {
return clients.openWindow(openUrl);
}
}));
I don't know if you still need a solution, but we did it like this.
After click, we look for the right registration by a lookup. Because our solution has many different customers, and there can be multiple registrations.
When we found it, we send a message. Somewhere else we have a listener on those messages to handle the rounting with the angular app.
If there is no tab opened, we use winClients.openWindow(url)
self.addEventListener('notificationclick', event => handleClick (event));
const handleClick = async (event) => {
const data = event.notification.data
const winClients = clients;
const action = event.action;
event.notification.close();
event.waitUntil(
clients.matchAll({includeUncontrolled: true, type: 'window'}).then(clients => {
let found = false;
let url = data.fallback_url;
if (action === 'settings') {
url = data.actions.settings;
}
clients.every(client => {
if (client.url.includes(data.lookup)) {
found = true;
client.focus();
client.postMessage({action: 'NOTIFICATION_CLICK', message_id: data.message_id, navigate_url: url});
return false;
}
return true;
});
if (!found) {
winClients.openWindow(url);
}
})
);
};

Creating chat "rooms" using Node, Express, Heroku, and Socket.io

So I've been building an app for quite some time and I'm running into problems in terms of scalability. I'm new to Node, and Heroku for that matter. Please bear with me.
I originally followed this tutorial to get my node service up and running. Essentially, it creates a real-time chat service. However, my question now comes with creating 'rooms'. It doesn't make sense to me that I might have 15+ chats going on, yet they all are calling the same functions on the same clientSocket, and I have to determine what UI updates go to which clients on the front end. As of now, I have upwards of 15 clients all trying to interact on different chats, but I'm pushing updates to everyone at once (for example, when a message is posted), then determining who's UI to update based on which room ID I'm cacheing on each device. Seems like a terrible waste of computing power to me.
I'm thinking that the solution involves modifying how each client connects (which is the code snippet below). Is there a way to create location based 'rooms', for example, where the clients connected are the only ones getting those updates? Any idea how to go about this solution? If anyone is also willing to just explain what I'm not understanding about Node, Express, Heroku, Socket.io or others, please do let me know.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var pg = require('pg');
var userList = [];
var typingUsers = {};
var ActiveQueue = [];
app.get('/', function(req, res){
res.send('<h1>Active RT Queue</h1>');
});
var conString = "postgres://url";
pg.defaults.ssl = true;
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
});
http.listen(process.env.PORT || 5000, function(){
console.log('Listening on *:5000');
});
io.on('connection', function(clientSocket){
console.log('a user connected');
clientSocket.on('disconnect', function(){
console.log('user disconnected');
var clientNickname;
for (var i=0; i<userList.length; i++) {
if (userList[i]["id"] == clientSocket.id) {
userList[i]["isConnected"] = false;
clientNickname = userList[i]["nickname"];
break;
}
}
delete typingUsers[clientNickname];
io.emit("userList", userList);
//io.emit("userExitUpdate", clientNickname);
//io.emit("userTypingUpdate", typingUsers);
});
clientSocket.on("exitUser", function(clientNickname){
for (var i=0; i<userList.length; i++) {
if (userList[i]["id"] == clientSocket.id) {
userList.splice(i, 1);
break;
}
}
io.emit("userExitUpdate", clientNickname);
});
clientSocket.on("connectUser", function(clientNickname) {
var message = "User " + clientNickname + " was connected.";
console.log(message);
var userInfo = {};
var foundUser = false;
for (var i=0; i<userList.length; i++) {
if (userList[i]["nickname"] == clientNickname) {
userList[i]["isConnected"] = true
userList[i]["id"] = clientSocket.id;
userInfo = userList[i];
foundUser = true;
break;
}
}
if (!foundUser) {
userInfo["id"] = clientSocket.id;
userInfo["nickname"] = clientNickname;
userInfo["isConnected"] = true
userList.push(userInfo);
}
io.emit("userList", userList);
io.emit("userConnectUpdate", userInfo)
});
///functions pertaining to transfer of messages and updating the UI follow
I would try something like this:
io.on('connection', function(clientSocket) {
clientSocket.on('room:general', function(data) {
var user = data.user;
var message = data.message;
console.log('%s sent new message: %s',user,message);
io.emit('room:general:newMessage', data);
});
//and so for each room
.........
});
and from front end you need to send JSONObject:
{
user:your_username,
message:user_message
}
,
socket.emit("room:general", json_object);
socket.on("room:general:newMessage", onYourDefinedEmiterListener);
..........
..........
//and so for each room
I never made Chat Application, hope it helps.

What is the query to fetch result from database in deployd server?

I am new in delpoyd server and need to validate email address already exist.
I read his document but unable to achieve result as expected.
According to deployd doc, I was trying this.
dpd['to-do'].get(query, function (result) { console.log(result); });
Please help me if anyone know.
This is the code I use for validating whether email already exists.I use this code in the Validate event.The need for checking the method 'PUT' is to prevent users from changing the email id to something that already exists after registering.
function validate(result, field) {
if (method === 'PUT') {
if (result.length === 0) {
} else if (!(result.length === 1 && result[0].id === id)) {
error(field, field + " is already in use");
}
} else if (result.length !== 0) {
error(field, field + " is already in use");
}
}
if (!internal) {
var email;
var method = ctx.method;
email = {
"email": this.email
};
dpd.users.get(email, function (result) {
validate(result, "email");
});
}

Failing Parse background job when using beforesave with thousands of objects

I am using a background job to query a json with thousands of objects to initially populate my database. I have also implemented the beforesave function to prevent any duplicate entries. However, once I implemented this, it seems my background job called response.error and does not save all objects. It looks like I might be exceeding the requests/sec? I would really appreciate if someone could take a look at my code and tell me why it is not saving all entries successfully.
Here is my background job:
Parse.Cloud.job("testing", function(request, response) {
var json;
Parse.Cloud.httpRequest({
url: stringURL + pageNumber.toString(),
success: function(httpResponse) {
json = httpResponse.data;
console.log("total is: " + json["meta"].total);
console.log("object 1 is: " + json["events"][1].title);
return json;
}
//after getting the json, save all 1000
}).then(function() {
//helper function called
saveObjects(json).then(function() {
response.success("success");
},
function(error) {
response.error("nooooo");
});
});
});
function saveObjects(json) {
var promises = [];
for(var i = 0; i < 1000; i++) {
var newEvent = new Event();
promises.push(newEvent.save(new Event(json["events"][i])));
}
return Parse.Promise.when(promises);
}
Here is my beforesave code:
Parse.Cloud.beforeSave("Event", function(request, response) {
var newEvent = request.object;
var Event = Parse.Object.extend("Event");
var query = new Parse.Query("Event");
query.equalTo("title", newEvent.get("title"));
query.equalTo("datetime_utc", newEvent.get("datetime_utc"));
query.equalTo("url", newEvent.get("url"));
query.first({
success: function(temp) {
response.error({errorCode:123,errorMsg:"Event already exist!"});
},
error: function(error) {
response.success();
}
});
});
Thanks I really appreciate any help... I've been stuck for a while.
If it's a request rate issue, then you could probably use something like node-function-rate-limit but it's fairly simple to write your own rate limiting batcher. See doInBatches() below.
Also, when using promise-returning methods that also offer a "success:..." callback, it's better not to mix the two styles. It may behave as expected but you are denied the opportunity to pass results from the "success:..." callback to the rest of the promise chain. As you can see below, the "success:..." code has simply been shuffled into the .then() callback.
Parse.Cloud.job("testing", function(request, response) {
Parse.Cloud.httpRequest({
url: stringURL + pageNumber.toString()
}).then(function(httpResponse) {
var json = httpResponse.data;
// console.log("total is: " + json.meta.total);
// console.log("object 1 is: " + json.events[1].title);
/* helper function called */
doInBatches(json.events, 30, 1000, function(evt, i) {
var newEvent = new Event();
return newEvent.save(new Event(evt));
}).then(function() {
response.success('success');
}, function(error) {
response.error('nooooo');
});
});
});
// Async batcher.
function doInBatches(arr, batchSize, delay, fn) {
function delayAsync() {
var p = new Parse.Promise();
setTimeout(p.resolve, delay);
return p;
}
function saveBatch(start) {
if(start < arr.length) {
return Parse.Promise.when(arr.slice(start, start+batchSize).map(fn))
.then(delayAsync) // delay between batches
.then(function() {
return saveBatch(start + batchSize);
});
} else {
return Parse.Promise.as();
}
}
return saveBatch(0);
}
I can't see how or why the beforesave code might affect things.

How to create a "loading" spinner in Breeze?

I'm trying to create a loading spinner that will be displayed when breeze is communicating with the server. Is there some property in Breeze that is 'true' only when breeze is sending data to the server, receiving data, or waiting for a response (e.g. after an async call has been made but no response yet)? I thought of binding this data to a knockout observable and binding the spinner to this observable,
Thanks,
Elior
Use spin.js
http://fgnass.github.io/spin.js/
Its so simple..make it visible before you execute the query and disable it after the query succeeds or fails.
I don't see any property that is set or observable while Breeze is querying, but if you are using a datacontext, or some JavaScript module for your data calls, this is what you can do -
EDIT
Taking John's comments into account, I added a token'd way of tracking each query.
var activeQueries = ko.observableArray();
var isQuerying = ko.computed(function () {
return activeQueries().length !== 0;
});
var toggleQuery = function (token) {
if (activeQueries.indexOf(token) === -1)
{ activeQueries.push(token); }
else { activeQueries.remove(token); }
};
var getProducts = function (productsObservable, forceRemote) {
// Don't toggle if you aren't getting it remotely since this is synchronous
if (!forceRemote) {
var p = getLocal('Products', 'Product','product_id');
if (p.length > 0) {
productsObservable(p);
return Q.resolve();
}
}
// Create a token and toggle it
var token = 'products' + new Date().getTime();
toggleQuery(token);
var query = breeze.EntityQuery
.from("Products");
return manager.executeQuery(query).then(querySucceeded).fail(queryFailed);
function querySucceeded(data) {
var s = data.results;
log('Retrieved [Products] from remote data source', s, true);
// Toggle it off
toggleQuery(token);
return productsObservable(s);
}
};
You will need to make sure all of your fail logic toggles the query as well.
Then in your view where you want to place the spinner
var spinnerState = ko.computed(function () {
datacontext.isQuerying();
};

Resources