Parse.com update Role error - parse-platform

I'm getting {"code":101,"error":"object not found for update"} when calling save on my role after adding a user to it, all on Cloud Code.
Sample code:
var role_query = new Parse.Query('_Role')
role_query.equalTo('name', 'USER')
role_query.first().then(function(role) {
role.getUsers().add(user)
role.save()
})

The error was that I didn't have permission to update the role.
Solution was using Parse.Cloud.useMasterKey() at the beginning of the Cloud Code function.
In case you need to update roles on the client:
https://www.parse.com/questions/role-cant-assign-user-in-js

Related

AWS Cognito SignUP with custom Attributes in node js causing error

I am trying to build Signup through a lambda function with AWS user pool where I added a custom attribute called type.
When I am sending a type value with signup, an error "A client attempted to write unauthorized attribute" is populating.
I am using 'amazon-cognito-identity-js' package to save data.
Here is my code snippet
const attributeList = [];
attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name:"name",Value:user.username}));
attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name:"custom:type",Value:'asd'}));
attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name:"gender",Value:user.gender}));
attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name:"email",Value:user.email}));
userPool.signUp(user.email, user.password, attributeList, null, function(err, result){
if (err) {
return reject(err);
}
return resolve(result);
});**strong text**
After that you added a new attribute, you should select the user attributes this app client can read and write.
Steps:
Go to your Cognito User Pool page
Click on the "App Client" from the left side menu
Click on the "Set attribute read and write permissions"
Make sure you added the necessary(read/write) permissions for the needed attribute
In addition to the above answer, sometimes custom attributes may take time to reflect under clients. Because I noticed it around 15 mins but after 1 hour it was there.

Call cloud code without logged in user Parse Server JS SDK

Is it possible to call a cloud function that returns objects without having a current user? The iOS and Android SDKs support anonymous users but I'm asking specifically for JavaScript.
I'd like to allow it so that anyone who visits my web app can read objects without having to sign in. I'm using Back4App.
Yes. You can call a cloud code function no matter the user is logged in or not. Inside the cloud function you can check the user property of the request object to check if the user is either logged in or not. In the case that your user is not logged in and you want to query a class which requires user permission, you can use the useMasterKey option.
Parse.Cloud.define('myFunction', async req => {
const { user, isMaster } = req;
if (isMater) {
// the cloud code function was called using master key
} else if (user) {
// the cloud code function was called by an authenticated user
} else {
// the cloud code function was called without passing master key nor session token - not authenticated user
}
const obj = new Parse.Object('MyClass');
await obj.save(null, { useMasterKey: true }); // No matter if the user is authenticated or not, it bypasses all required permissions - you need to know what you are doing since anyone can fire this function
const query = new Parse.Query('MyClass');
return query.find({ useMasterKey: true }) // No matter if the user is authenticated or not, it bypasses all required permissions - you need to know what you are doing since anyone can fire this function
});

How to call web API under specific user permission?

I have a function that allows the end user to execute a Workflow (containing many APIs) or schedule it to run as a background job.
Example: User1 creates Workflow1, which contains 3 APIs (Api1, Api2, Api3), and configures it to run at 9AM every day.
I use HttpClient to call each API like this:
var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("/api/services/myApp/workflow/Api1?input=something", "").Result;
How do I add the credentials of User1 to the request while the user is not logged in to the application (because it will run automatically as a scheduled job)?
Update 1
I decided to use reflection to call an API by string name.
In the case of executing an API directly, how do I run it under a specific permission?
Update 2
I have put my code inside a using block, but all APIs were fired successfully:
using (_session.Use(1, 3)) // 3 is the Id of User1, who has no permissions
{
// Execute operator
switch (input.Operator.Type)
{
case "api":
executeApiResult = await ExecuteApi(input);
break;
case "procedure":
executeApiResult = await ExecuteProcedure(input);
break;
default:
return new ExecuteOperatorOutput
{
Result = new ExecuteOperatorResult { Status = false, Message = $"Wrong operator type: {input.Operator.Type}" },
WorkflowStatus = false
};
}
}
In the case of executing an API directly, how do I run it under a specific permission?
You can override current session values and call your method inside the using block.
I have put my code inside a using block, but all APIs were fired successfully
Declare your API methods as public virtual as there are some restrictions for AbpAuthorize.
You have two options.
1- You can make those Application Services anonymously accessible. And if you want it to be secure, send an encrypted security token.
2- You didn't mention if your project is MVC or Angular. I assume you have Angular version. You need a bearer token to make authenticated requests. First you have to authenticate user and get a token. Then add this bearer token to every request.
You have to research for using bearer tokens in asp.net core...

How to authenticate user with firebase sdk

I am using this SDK and following this documentation. Now I am trying to create and authenticate user in firebase db. How can I do that.I am doing the project in Codeigniter and in my controller I did this:
public function register()
{
$firebase = (new Firebase\Factory())->create();
$tokenHandler = $firebase->getTokenHandler();
$uid = 'a-uid';
$claims = ['foo' => 'bar']; // optional
// Returns a Lcobucci\JWT\Token instance
$customToken = $tokenHandler->createCustomToken($uid, $claims);
echo $customToken; // "eyJ0eXAiOiJKV1..."
$idTokenString = 'eyJhbGciOiJSUzI1...';
// Returns a Lcobucci\JWT\Token instance
$idToken = $tokenHandler->verifyIdToken($idTokenString);
$uid = $idToken->getClaim('sub');
echo $uid; // 'a-uid'
}
and I call the function It gave me this error:
Type: Kreait\Firebase\Exception\ServiceAccountDiscoveryFailed
Message: Kreait\Firebase\ServiceAccount\Discovery\FromEnvironmentVariable: The environment variable "FIREBASE_CREDENTIALS" is not set. Kreait\Firebase\ServiceAccount\Discovery\FromEnvironmentVariable: The environment variable "GOOGLE_APPLICATION_CREDENTIALS" is not set. Kreait\Firebase\ServiceAccount\Discovery\FromGoogleWellKnownFile: The well known file is not readable or invalid
Filename: E:\xampp\htdocs\firebasedb\vendor\kreait\firebase-
php\src\Firebase\ServiceAccount\Discoverer.php
Line Number: 48
Can anyone help me with this issue? Any kind of help are appreciated. Thanks.
EDIT
Okay I solve this problem with default .json file path like this:
$serviceAccount = ServiceAccount::fromJsonFile(JSON_FILE_PATH.'google-service-account.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
Now can I register a new user from web-app? Can anyone Help please. I have been stopped in this problem since long. Helps are highly appreciated.
You Set JSON Key environment variables
FIREBASE_CREDENTIALS GOOGLE_APPLICATION_CREDENTIALS ?
try reading this Firebase Admin SDK for PHP Setup
From the documentation https://firebase-php.readthedocs.io/en/latest/authentication.html#authenticate-with-admin-privileges
There two crucial points to note.
Many use cases for verifying ID tokens on the server can be accomplished by using Security Rules for the Firebase Realtime Database and Cloud Storage. See if those solve your problem before verifying ID tokens yourself.
The ID token verification methods included in the Firebase Admin SDKs are meant to verify ID tokens that come from the client SDKs, not the custom tokens that you create with the Admin SDKs Check out https://firebase.google.com/docs/auth/users/#auth_tokens
About Users:
From https://firebase-php.readthedocs.io/en/latest/user-management.html
You have a sample
$request = \Kreait\Auth\Request\CreateUser::new()
->withUnverifiedEmail('user#example.com')
->withPhoneNumber('+15555550100')
->withClearTextPassword('secretPassword')
->withDisplayName('John Doe')
->withPhotoUrl('http://www.example.com/12345678/photo.png');
$createdUser = $auth->createUser($request);
Please Note:
By default, Firebase Authentication will generate a random uid for the new user. If you instead want to specify your own uid for the new user, you can include in the properties passed to the user creation method:
$properties = [
'uid' => 'some-uid',
// other properties
];
$request = \Kreait\Auth\Request\CreateUser::new()
->withUid('some-uid')
// with other properties
;
I had same problem with Laravel in my case, here is the solution:
First save the .json credentials file you got from Firebase project into the root of your Laravel app on the same level as .env file.
The json file looks like you-file-firebase-adminsdk-0000-9845985498a.json
Then open the .env file and create a new environment variable and paste the json credential file name.
FIREBASE_CREDENTIALS=../you-file-firebase-adminsdk-0000-9845985498a.json

Parse Cloud Code on Heroku User Query

I am trying to access properties located on the User object for the current user in a cloud code function. The current user is passed to the cloud code function and available at request.user. The Cloud Code is deployed to Heroku using parse-cloud-express.
When the request first arrives, it does not contain the user data other than the id.
So I tried performing a fetch to get the latest data:
Parse.Cloud.define("functionName", function (request, response) {
request.user.fetch().then(function (user) {
console.log(util.inspect(user));
});
});
But it outputs the same data and does not seem to include the User object's properties.
2015-12-15T01:19:08.830880+00:00 app[web.1]: { _objCount: 1, className: '_User', id: 'dKqZMSRgDc' }
I also tried performing a query on the user id, but receive the same result.
var userQuery = new Parse.Query(Parse.User);
userQuery.get(request.user.id).then(function (user) {
console.log(util.inspect(user));
});
How do I get the properties of the User object?
The problem was not with getting data for the User object, but the way I was logging it. It seems that the data is not available from the object itself, so the output from util.inspect was correct, but does not include any properties. (I'm guessing the internals of the Parse framework manages this in another way.)
I replaced with console.log(user.toJSON()) and can now see the expected data for the user.

Resources