I am trying to basically have a sign up form that will sign up a user and also add that user that just signed up to a certan role. I got the app signing up the user fine but it isnt creating the role and adding the user to that role. Here is what I had
<script type="text/javascript">
Parse.initialize("key", "key");
//set the user
var user = new Parse.User();
$( "form" ).submit(function( event ) {
//get the input data
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var facility = $('#facility').val();
//Set the user info
user.set("facility", "" + facility + "");
user.set("username", "" + username + "");
user.set("email", "" + email + "");
user.set("password", "" + password + "");
//Sign them up
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
//Make the role
var roleACL = new Parse.ACL();
roleACL.setPublicReadAccess(true);
var role = new Parse.Role("Pro", roleACL);
role.getUsers().add(username);
role.save();
//Show and Hide the alert
$('#successModal').modal('show');
setTimeout(function(){
$('#successModal').modal('hide')
}, 4000);
//Clear the form
$( 'form' ).each(function(){
this.reset();
});
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
return false
});
</script>
My thought was create the user then on successful user creation create the role and add the user to that role. Seems not to be working though.
code the querys a user
querys a role
then adds the user to the role
var qu = new Parse.Query(Parse.User);
var qr = new Parse.Query(Parse.Role);
qr.get(roleId, {
success: function(role) {
_role = role;
qu.get(userId, {
success: function(user) {
_role.getACL().setRoleReadAccess(_role, true);
_role.getUsers().add(user);
_role.save();
response.success(_role.toJSON());
},
error: function(object, error) {
console.log('got role, failed on get user');
}
});
The aim is to add the newly saved user to an existing role, so that role must be queried, not created when the user is saved.
Since you must the save of a user, query a role, and save that role -- three asynch operations that must be performed in sequence -- it's advisable to use promises, lest the code become unreadably indented, so...
// prepare the user as you have it, then
user.signUp().then(function(user) {
// query the role, you can get it with the role name
var roleQuery = new Parse.Query(Parse.Role);
roleQuery.equalTo("name", "Pro");
return roleQuery.first();
}).then(function(role) {
role.getUsers().add(user);
return role.save();
}).then(function() {
// no need to set a timer. with the promise, we know exactly when we are done
$('#successModal').modal('hide');
}, function(error) {
alert("Error: " + error.code + " " + error.message);
});
Be sure to first create the "Pro" role manually using the data browser. Read through the security section in the programming guide.
Also note, if this happens for every user, the role code is a good candidate to be part of an afterSave cloud function on PFUser.
Related
I created two test users from MESIBO API, to test messaging between them.
Created exact same script in two files, and add send function in one file, to send message to the second user.
I tried the second user's token, UID, and address but the message gets sent from the first user but 2nd user's script listener doesn't catch it. Both the user tokens, appid (app name) are valid, I tried even in HTTPS connection too, but still couldn't receive a message on another end.
Second User (two.html) : Sender
FIrst User (one.html) : Receiver
Script form first user: which supposed to get the message
<script type="text/javascript" src="https://api.mesibo.com/mesibo.js"></script>
<script>
var demo_user_token = 'XXXXXXXXXXXXXXXXXX';
var demo_appid = 'legal.web';
var api = new Mesibo();
api.setListener(new MesiboListener());
api.setAppName(demo_appid);
api.setCredentials(demo_user_token);
api.setAccessToken(demo_user_token);
//api.setDatabase("mesibo");
api.start();
console.log('First User');
function MesiboListener() {
}
MesiboListener.prototype.Mesibo_OnConnectionStatus = function(status, value) {
console.log("Mesibo_OnConnectionStatus: " + status);
}
MesiboListener.prototype.Mesibo_OnMessageStatus = function(m) {
console.log("Mesibo_OnMessageStatus: from "
+ m.peer + " status: " + m.status);
}
MesiboListener.prototype.Mesibo_OnMessage = function(m, data) {
console.log("Mesibo_OnMessage: from " + m.peer);
}
MesiboListener.prototype.Mesibo_OnCall = function(callid, from, video) {
console.log("Mesibo_onCall: " + (video?"Video":"Voice") + " call from: " + from);
}
</script>
Script from the second user, who send message to the first user using first user's token
<script type="text/javascript" src="https://api.mesibo.com/mesibo.js"></script>
<input type="button" value="Send" onclick="sendTextMessage()" >
<script>
var demo_user_token = 'XXXXXXXXXXXXXXXXXXX';
var demo_appid = 'legal.web';
var api = new Mesibo();
api.setListener(new MesiboListener());
api.setAppName(demo_appid);
api.setCredentials(demo_user_token);
api.setAccessToken(demo_user_token);
api.start();
console.log('Scond User User');
function MesiboListener() {
}
MesiboListener.prototype.Mesibo_OnConnectionStatus = function(status, value) {
console.log("Mesibo_OnConnectionStatus: " + status);
}
MesiboListener.prototype.Mesibo_OnMessageStatus = function(m) {
console.log("Mesibo_OnMessageStatus: from "
+ m.peer + " status: " + m.status);
}
MesiboListener.prototype.Mesibo_OnMessage = function(m, data) {
console.log("Mesibo_OnMessage: from " + m.peer);
}
function sendTextMessage() {
let to = "2757b980f05600c48d75f17f6cb0480ed3a91557655dc7d2ebb3f2dc5vaa1cbe86178"
var profile = api.getProfile(to, 0);
console.log(profile);
var id = parseInt(Math.random()*10000);
profile.sendMessage(id, "this is text message");
}
</script>
Why are you using a token in the "to" parameter? It should be the address "USER_2". Please do not share your tokens in a public forum.
function sendTextMessage() {
let to = "USER_2"
var profile = api.getProfile(to, 0);
console.log(profile);
var id = parseInt(Math.random()*10000);
profile.sendMessage(id, "this is text message");
}
Refer to the tutorial here https://mesibo.com/documentation/tutorials/get-started/javascript/
I got a very simple socket.io application where I'm able to see when a user connects to my site and when a user leaves. The first user is able to see everybody that gets in, however the second will only see the people coming in after him, and so on.... What I want the user that connects to see are all current connected users
Server.js
var io = require("socket.io")(http);
var users = [];
io.on("connection", function (socket) {
console.log("User connected", socket.id);
Some loop to see user connected I think?!
socket.on("user_connected", function (username) {
users[username] = socket.id;
console.log(users);
if (username !== 'null'){
io.emit("user_connected", username);
}
});
socket.on("send_message", function (data) {
io.emit("new_message", data);
});
socket.on("user_left", function (datan) {
io.emit("user_remove", datan);
console.log("user left", datan);
});
});
site.html
window.onbeforeunload = function () {
io.emit("user_left", name);
};
var name = <?php echo json_encode($_SESSION['displayname']); ?>;
var bild = <?php echo json_encode($_SESSION['userpic']);?>;
var dt = new Date();
var tid = dt.getHours() + ":" + dt.getMinutes();
io.emit("user_connected", name);
sender = name;
io.on("user_connected", function (username) {
var html = "";
html += "<li data-username='" + username + "'>" + username + "</li>";
document.getElementById("users").innerHTML += html;
});
Looked into this question, but me a dumb coder doesn't understand what 'my_room' is towards my soloution. Sorry for weird question, I'm just kind of lost
If you want to send a user list to everyone, create an object like users, add a record each time a user connected, and broadcast to everyone.
if someone disconnects, then first remove that from your collection then send only disconnected user's info to clients, so clients can delete that user from their list.
If all you want is total number of questions, just send io.sockets.clients().length
I am using the phonegap facebook Connect plugin to enable facebook login in my app.
However the facebook email is being returned as undefined.
Do I need to add something into my code?
I have looked up this issue on the internet and it seems my code should work. Everything else is returned except for the email address.
I would appreciate if you can help
Here is my javascript code:
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
Edit:
I tried a test user account with this code and the email address DID get returned. However for the real account I was testing with this doesn't work.
With more testing I tried adding in the email permission as follows however this did not work as the data that I got back stated "FACEBOOK_NON_JSON_RESULT"
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile", "email"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
I find a workaround for this problem which was to do two separate api requests as follows:
facebookConnectPlugin.api('/me?fields=email', ["email"], function(apiResponse) {
//alert("api" + JSON.stringify(apiResponse));
fb_email = apiResponse.email;
alert("fb_email" +fb_email); //email being retrieved successfully
facebookConnectPlugin.api('/me?fields=id, name, link, picture', ["public_profile"],function(data) {
alert("data" + JSON.stringify(data));
var fb_user_id = data.id;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_user_id" + fb_user_id);
alert("fb_name" + fb_name);
alert("fb_picture_url" + fb_picture_url);
alert("fb_user_link" + fb_user_link);
//do stuff with facebook user data here
}
,function(error){
//api call failed
alert("api call Failed: " + JSON.stringify(error));
}); //end api
}
,function(error){
alert("email api call Failed: " + JSON.stringify(error));
}); //end api
This works perfect!
Update: Solved, happens to be incorrect Cloud Code I wrote, see update #3
I am trying to make a signup for user using Parse.com API in Javascript.
Still with no success.
Basically I have a user field and a password field, and when hit signup button, tries to login but always I have the "Error Code: 142 :User name already exists, try login error from Parse api.
What is wrong with the code? (I previously used c# code and it was success)
Thanks in response.
function onSignupButtonClicked(button) {
event.preventDefault();
game_username = $("#loginUserText").val();
game_password = $("#loginPasswordText").val();
parseLogout(); // tried both logout earlier or put here..
var user = new Parse.User();
user.set("username", game_username);
user.set("password", game_password);
var progressCircle = showProgressCircle(); //some fullscreen progress
//also tried user.signup(null, {.. with no luck
Parse.User.signUp(game_username, game_password, {}, {
success: function(user) {
// Hooray! Let them use the app now.
//NOW LOGIN
login(game_username, game_password).then(function(result) {
console.log(result); // "Stuff worked!"
hideProgressCircle(progressCircle);
$("#loginButton").attr("disabled", true);
$("#logoutButton").attr("disabled", false);
$("#signupButton").attr("disabled", true);
game_manualLogin = true;
isLoggedIn = true;
}, function(err) {
hideProgressCircle(progressCircle);
console.log("loginPromise: " + err.message + " code: " + err.code); // Error: "It broke"
handleParseError(err);
});
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
hideProgressCircle(progressCircle);
handleParseError(error);
}
});
}
update:
Even basic Parse.com javascript returns 142.. here is the code, and my location is Istanbul/Turkey
function register() {
var user = new Parse.User();
user.set("username", "testop");
user.set("password", "testop");
user.set("email", "email#example.com");
// other fields can be set just like with Parse.Object
user.set("phone", "415-392-0202");
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
console.log("testop register ok!");
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
}
This is the error I get to above updated code
Error:code: 142 :User name already exists, try login (Code is from Parse Javascript Signup
Update #2:
Even Rest API gives same error:
MacBook-Pro:~ gg$ curl -X POST \
> -H "X-Parse-Application-Id: MYAPPID" \
> -H "X-Parse-REST-API-Key: MYRESTAPIKET" \
> -H "X-Parse-Revocable-Session: 1" \
> -H "Content-Type: application/json" \
> -d '{"username":"testdude","password":"tesdude","phone":"415-392-0202"}' \
> https://api.parse.com/1/users
{"code":142,"error":"User name already exists, try login"}
MacBook-Pro:~ gg$
UPDATE #3:
After checking with 3 apis, found that problem was my fault.
I forgot a Cloud Code on user save, which was faulty as it did not check length of query length..
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
var username = request.object.get("username");
var usernamequery = new Parse.Query(Parse.User);
usernamequery.equalTo("username", username);
usernamequery.find({
success: function()
{
--->>>should be checking length of query here <<<---
console.log("same user name found");
response.error("User name already exists, try login");
},
error: function(error)
{
console.log("ok unique user name continue save");
response.success("OK saving user");
}
});
});
You need two forms, one for signing up (as a new user) which calls Parse.User.signUp and a second form (for returning users) that calls Parse.User.logIn.
The problem is that you can only 'sign up' once with a username and password, after which you should 'login'. Also when you have got a success callback from Parse.User.signUp then the user is logged in and you don't have to call 'login'.
Something like this (where the two event listeners are triggered by two different buttons).
SIGNUP
function onSignupButtonClicked(button) {
event.preventDefault();
game_username = $("#loginUserText").val();
game_password = $("#loginPasswordText").val();
Parse.User.signUp(game_username, game_password, {}, {
success: function(user) {
// A new user has signed up and is now the Parse.User.current() user
// Do something
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
}
});
}
LOGIN
function onLoginButtonClicked(button) {
event.preventDefault();
game_username = $("#loginUserText").val();
game_password = $("#loginPasswordText").val();
Parse.User.logIn(game_username, game_password, {}, {
success: function(user) {
// An existing user has logged in and is now the Parse.User.current() user
// Do something
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
}
});
}
More info here: https://parse.com/docs/js_guide#users-signup
I build a signup form and there, there is filed for the user image
<input type="file" name="img1" id="img1">
Now , When the user press the button "signup" I call the function signUp:
function signUp(){
var username = document.getElementById('username_signUp').value;
var password = document.getElementById('password_signUp').value;
Parse.initialize("kkbFC-----dldRYvUOywO8", "2ux4CkBgv4QB---wNguk");
var user = new Parse.User();
user.set("username", username);
user.set("email", username);
user.set("password", password);
var fileUploadControl = $("#img1")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
parseFile.save().then(function() {
// The file has been saved to Parse.
}, function(error) {
alert("Error: " + error.code + " " + error.message);
// The file either could not be read, or could not be saved to Parse.
});
user.set("image", file);
}
user.signUp(null, {
success: function (user) {
},
error: function (user, error) {
}
});
}
The signUp complete and I get new row on parse.com.
In the "image" filed I habe
{"lastModifiedDate":{"__type":"Date","iso":"2014-01-18T20:07:11.000Z"},"name":"empty-f.gif","size":2498,"type":"image/gif","webkitRelativePath":""}
I don't undersatd if it is good or not, but when I try to get the image - it seems to be undfined.
alert(profilePhoto.url); ->It show me the message "undefined"
Thanks!
//Parse's asynchronous nature causes some of hard-to-spot errors.
//The right way to use parse is to keep nesting code into the
//success handlers/promise handler.
function signUp(){
var username = document.getElementById('username_signUp').value;
var password = document.getElementById('password_signUp').value;
Parse.initialize("kkbFCxNGrHeUB7MpVEIRGMvZYgh0dldRYvUOywO8", "2ux4CkBgv4QBNYwlLh7RGmNQjXh7t0x7jGjwNguk");
var user = new Parse.User();
user.set("username", username);
//THE NEXT LINE SETS EMAIL TO BE THE USER NAME. THAT IS MOST LIKELY A BUG
user.set("email", username);
//-----------------------------------------------------------------------
user.set("password", password);
var fileUploadControl = $("#img1")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
parseFile.save().then(function(parseFile) {
// The file has been saved to Parse. file's URL is only available
//after you save the file or after you get the file from a Parse.Object.
//Get the function url() on the Parse.File object.
var url = parseFile.url();
user.set("image", url);
user.signUp();
},
function(error) {
// The file either could not be read, or could not be saved to Parse.
alert("Error: " + error.code + " " + error.message);
});
};
};