Parse.com Adding Cloud code to html buttons - javascript

I'm testing some functions locally using my database created on parse.com and the functions run exactly as intended. I am trying now to put these functions on cloud code to reduce the amount of request sent to parse as well as run the queries in the cloud code instead of locally. For whatever reason I cant get these functions to work when I convert them to cloud code. Also, how would I make a button in html that can run a function in cloud code?
Before cloud code, my html button looked like this:
<button type="button" onclick="authenticate()">Log-In</button>
How would I create that button with cloud code that looks like this:
Parse.Cloud.define("authenticate()", function(request, response) {
var myname = document.getElementById("username").value;
var mypass = document.getElementById("psswd").value;
Parse.User.logIn(myname, mypass, {
success: function(user) {
// Do stuff after successful login.
if(myname == "test1" || myname == "test2"){
window.location.href="itSplash.html";
}
else{
window.location.href="ticketRequest.html";
}
},
error: function(user, error) {
// The login failed. Check error to see why.
alert("Failed to login: " + error.message);
}
});
});
for clarification that if statement just directs login to itSplash if username matches test1 or test2, and ticketRequest if its anyone else. We have a seperate page for different users. Also, that function works locally if I create it as a normal function authenticate(). When I converted it to cloud code as seen above it wont work. I create a seperate function name runAuthenticate() with a Parse.Cloud.run call inside that and it wouldnt work there. All I got was an Error saying define cannot be used on that Object. Any Help?

You can link the HTML button with a cloud code function by using Parse.Cloud.run.
Take a look at the Parse Cloud code
documentations.
This is how you can call the cloud code from javascript.
Parse.Cloud.run('hello', {}, {
success: function(result) {
// result is 'Hello world!'
},
error: function(error) {
// Error while running cloud code
}
});
As you have written, you can try calling a javascript method onclick on the HTML button and then call the Parse.Cloud.run method.

First, you don't have access to document or window in cloud code so you need to rethink where you're coming from.
Also, it isn't appropriate to have the user details sent to the cloud code, you should login on the web page using the SDK and then use the SDK to trigger the cloud code and it will send the user and auth details.
So, the whole premise of your authenticate function being in cloud code doesn't really work.
That doesn't mean you shouldn't use cloud code, it's just that you shouldn't use it for this purpose. You talk about making queries but you don't actually have any in the code you show - but that kind of thing is more likely to be movable to cloud code...

Related

RingCentral JavaScript SDK Handle Redirect URI points to local JavaScript Function

RingCentral JavaScript SDK handle redirect URI point to local JavaScript function
As-per Doc, they give option
RingCentral.SDK.handleLoginRedirect()
but dont know how to use that
var SDK = require('ringcentral');
rcsdk = new SDK({
server: SDK.server.sandbox,
appKey: '_app_key',
appSecret: 'app_password',
redirectUri: ''
})
function handleredirectURI(){
//handle redirections
}
We need points out our handleredirectURI function
Thanks in advance
Per the documentation. The context is 3-legged oAuth. Here is a demo: https://github.com/ringcentral/ringcentral-demos-oauth/tree/master/javascript
However the demo doesn't use the handleredirectURI method. Which means that the method is simply an utility method and it's not required to use it.
For the usage of handleredirectURI, I will come back and update my answer later.
Update
Here is the source code for handleredirectURI: https://github.com/ringcentral/ringcentral-js/blob/669b7d06254d3620c5a5f24c94b401aa862be948/src/SDK.js#L115-L124
You can see that the method parses win.location to get some useful data and postMessage back to its opener.
Unit tests for handleredirectURI: https://github.com/ringcentral/ringcentral-js/blob/669b7d06254d3620c5a5f24c94b401aa862be948/src/SDK-spec.js#L27-L63
Update 2
I read handleredirectURI' source code, unit tests, sample code again and I think its usage is just like what is written in its documentation:
Popup Setup
This setup is good when your app is rendered as a widget on a third-party sites.
If you would like to simply open RingCentral login pages in a popup, you may use the following short-hand in your app's login page:
var platform = rcsdk.platform();
var loginUrl = platform.loginUrl({implicit: true}); // implicit parameter is optional, default false
platform
.loginWindow({url: loginUrl}) // this method also allows to supply more options to control window position
.then(function (loginOptions){
return platform.login(loginOptions);
})
.then(...)
.catch(...);
In this case your landing page (the one to which Redirect URI points) need to call the following code:
RingCentral.SDK.handleLoginRedirect();
Explained:
Run the first code snippet to open the login popup.
In the redirected to page, run the second code snippet (that one line of code) to get everything else done.
After that the authorization part is done and you can invoke other APIs.
Let me know if you have more questions.

Firebase cloud notification localization

Trying to get localization keys to work with firebase and nodes firebase.admin utility but cannot get it to work.
I receive a messageId when sending and no errors at all so a little stuck.
I use a Firebase Function to send notifications so everything is running within firebase.
admin.messaging().sendToTopic("my_topic", {
"notification": {
"titleLocKey" : "FRXT",
"bodyLocKey" : "FRXB",
"bodyLocArgs" : "['test']"
}
}).then(function(resp){
res.send(200, resp)
})
I guess i'm doing something wrong here that i just cannot see so if there are any smart people out there please give a shout. The keys used are in the iOS localization string file. If i just use title and body the push work fine also.

Parse Cloud Code User Validation

I want to validate an iOS user calling a Cloud Code function.
Parse.Cloud.define("sayMyName", function(request, response) {
var user = request.user;
console.log(user);
response.success("Your name is: " + user.get("name"));
)};
However this always brings up undefined. There doesn't seem to be any documentation about this, and it is Parse specific, so my hands are kind of tied.
Within Cloud Code, how do I determine which user is calling the function?
and make sure user has name as key.

Parse iOS SDK: Understanding Cloud Code

Scenario = I am slowly but surely wrapping my head around what is going on with Parse's cloud code features. I just need some help from those who would like to answer some short, relatively simple questions about what is going on in some sample cloud code functions.
The code I will use in this example is below
1) cloud code
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.set('new_col', newColText);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
2) called from iOS
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": #"someuseridhere",
#"newColText": #"new text!"
}];
This code was taken from here
Question 1 =
(request, response)
I am confused by what this is. Is this like typecasting in iOS where I am saying (in the iOS call) I want to pass an NSString into this function ("userId") and inside the cloud code function I'm going to call it "request"? Is that what's going on here?
Question 2 =
Parse.Object.extend('_User')
Is this grabbing the "User" class from the Parse database so that a "PFObject" of sorts can update it by creating a new "user" in the line below it?
Is this like a...
PFObject *userObject = [PFObject objectWithClassName:#"User"]?
Question 3 =
user.set('new_col', newColText)
This obviously 'sets' the values to be saved to the PFUser (~I think). I know that the "newColText" variable is the text that is to be set - but what is 'new_col'? Only thing I can think of is that this sets the name of a new column in the database of whatever type is being passed through the "request"?
Is this like a...
[[PFUser currentUser] setObject: forKey:]
Question 4 =
Parse.Cloud.useMasterKey()
Without getting too technical, is this basically all I have to type before I can edit a "User" object from another User?
Question 5 =
user.save().then(function(user) {
response.success(user);
}
Is this like a...
[user saveInBackgroundWithBlock:]?
and if so, is
function(error) {
response.error(error)
just setting what happens if there is an error in the saveInBackgroundWithBlock?
Please keep in mind, I know iOS - not JavaScript. So try to be as descriptive as possible to someone who understands the Apple realm.
Here's my take on your questions:
The request parameter is for you to access everything that is part of the request/call to your cloud function, it includes the parameters passed (request.params), the User that is authenticated on the client (request.user) and some other things you can learn about in the documentation. The response is for you to send information back to the calling code, you generally call response.success() or response.error() with an optional string/object/etc that gets included in the response, again documentation here.
That's a way of creating an instance of a User, which because it is a special internal class is named _User instead, same with _Role and _Installation. It is creating an instance of the user with an ID, not creating a new one (which wouldn't have an ID until saved). When you create an object this way you can "patch" it by just changing the properties you want updated.
Again, look at the documentation or an example, the first parameter is the column name (it will be created if it doesn't exist), the second value is what you want that column set to.
You have to do Parse.Cloud.useMasterKey() when you need to do something that the user logged into the client doesn't have permission to do. It means "ignore all security, I know what I'm doing".
You're seeing a promise chain, each step in the chain allows you to pass in a "success" handler and an optional "error" handler. There is some great documentation. It is super handy when you want to do a couple of things in order, e.g.
Sample code:
var post = new Parse.Object('Post');
var comment = new Parse.Object('Comment');
// assume we set a bunch of properties on the post and comment here
post.save().then(function() {
// we know the post is saved, so now we can reference it from our comment
comment.set('post', post);
// return the comment save promise, so we can keep chaining
return comment.save();
}).then(function() {
// success!
response.success();
}, function(error) {
// uh oh!
// this catches errors anywhere in the chain
response.error(error);
});
I'm pretty much at the same place as you are, but here are my thoughts:
No, these are the parameters received by the function. When something calls the editUser cloud function, you'll have those two objects to use: request & response. The request is basically what the iOS device sent to the server, and response is what the server will send to the iOS device.
Not quite that. It's like creating a subclass of _User.
Think of Parse objects types as a database table and it's instances as rows. The set will set (derp) the value of 'newColText' to the attribute/column 'new_col'.
Not sure, never used that function as I don't handle User objects. But might be that.
Pretty much that. But it's more sort of like (pseudo-code, mixing JS with Obj-C):
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if(error){
response.error(error); // mark the function as failed and return the error object to the iOS device
}
else{
response.success(user); // mark the function call as successful and return the user object to the iOS device
}
}];

Parse.com Javascript logging out w/ facebook

I'm having trouble getting a logged in facebook user in my parse.com application to log out. What is wrong with the code below?
function logOff() {
function thisSuccess(e) {
console.log(1);
}
function thisError(e) {
console.log(0);
}
var u = Parse.User.current();
Parse.FacebookUtils.unlink(u, {success: thisSuccess,error: thisError});
u.logOut();
}
I've searched everywhere, the best response I got was that the facebook account linked to the user needs to be unlinked as well - I'm not entirely sure whether this is so.
All you need is Parse.User.logOut();
Don't unlink the Facebook account, as that use won't be able to log in again. Next time they try to log in with Facebook Parse will create a new user for them.

Categories