Supabase storage API denying itself access to a RLS-disabled table - javascript

I have a storage policy on Supabase for select, insert, update and delete with this as the USING expression:
((bucket_id = 'projects'::text) AND (
SELECT (
EXISTS (
SELECT data.pid
FROM (
SELECT "UserManagesProject"."projectId" AS pid
FROM "UserManagesProject"
WHERE (
"UserManagesProject"."managerId" = (uid())::text)
) data
WHERE (
(data.pid)::text = (storage.foldername(objects.name))[1]
)
)
) AS "exists"
)
)
From what I was able to test on the Supabase UI SQL editor, this query works for what I want, which is to check if the folder name has the same id as the project that the user's id is linked to.
The problem comes from trying to access this folder using the supabase API:
await supabase.storage
.from("projects")
.upload(
`${id}/${pngFile.name}`,
pngFile,
{
cacheControl: "0",
upsert: false,
contentType: "image/png",
}
);
When using this API call, I get an error:
{statusCode: '403', error: '', message: 'permission denied for table UserManagesProject'}
What I'm confused about is the UserManagesProject table does not have RLS enabled, so it shouldn't be denying access, but it is.
I've tried turning on RLS for the UserManagesProject table and creating a policy that allows anonymous users to read from the table, but that does not stop supabase from denying itself access to table.
Not sure what is even happening here. Any ideas?

Related

how can i use laravel csrf token on my nuxt vps

I started creating a new application using Laravel and Nuxt Js.
i have two VPS servers :
The first one contain my Nuxt JS ( Front End )
The second one is the end point ( back end ) based on Laravel
i have created a lot of pages i insert the data correctly into my database. and now i tried to create a new function to update users data, but i get an error after submiting the form since i use the same axios code to insert.
Right now i'm working without tokens and i know its insecure way.
i would like to know how can i communicate the tokens between Nuxt JS front end Laravel Backend.
i have two servers.
the error that i get is :
CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException
this is my Axios code :
edit (customerId, submit = false) {
this.editMode = true
this.customerId = customerId
if (submit === 1) {
const formData = $('#add-customer').serialize()
this.$axios.$post('/customer/update', formData).then((response) => {
this.refresh = true
})
} else {
this.$axios.$get('/customer/edit?customer=' + customerId).then((response) => {
this.formFields = response.data[0]
})
}
}
when i change this line from post to get, it works fine
this.$axios.$post('/customer/update', formData)
I would suggest using a single Redis server for session management,so you have a centralized location. or using a database, for more details check laravel doc
https://laravel.com/docs/6.x/session

Why does failed dynamodb query fail with cors error on localhost instead of actual error?

In my development environment, I have a local copy of Dynamodb set up, using Reactjs to connect to it. I'm using the AWS SDK, in particular the query method for Dynamodb, to make queries.
When the query is properly structured, it runs fine. However, if the query is poorly structured, I get a cryptic response. The Chrome console gives me a:
POST http://localhost:8000/ 400 (Bad Request)
Access to XMLHttpRequest at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
where localhost:8000 points to the local Dynamodb instance and localhost:3000 points to the react instance.
Most importantly, I don't get an error message dealing specifically with the mistake I've made. For instance, I might project a field with a reserved word, which then should correctly not work. However, I would expect an error saying "such and such word is reserved", not this CORS business.
Furthermore, when I run the same query from my node server, I do get a proper error message. This makes me wonder if the problem is related to reactjs somehow.
Is there any way to get a proper error message in my development environment as I've described? Thanks.
Edit:
As requested in the comments, here's a typical way I grab the data. Please note that this is a working query, so this is not generating an error. As I'm developing, though, this would be the type of query where I'd be making mistakes and not seeing good feedback.
// define tableName, indexName
async componentDidMount() {
// properties include an initiated docClient and organizationId
const [posts] = await Promise.all([ // typically I will fetch more than just posts (omitted for brevity)
new Promise((resolve, reject) =>
this.props.docClient.query(
{
TableName: tableName,
IndexName: indexName,
KeyConditionExpression: 'SortKey = :sortKey',
ExpressionAttributeValues: {
':sortKey': this.props.organizationId + delimiter + 'POST-Date'
},
ProjectionExpression: 'chatTitle, creatorName, creatorEmail, PostId, creationTime, #text, #data, lastModifiedTime, #status, mentions, attachments, chatType, creatorType',
ExpressionAttributeNames: { '#text': 'text', '#status': 'status', '#data': 'Data' }
},
(err, data) => {
if (err) {
reject(err);
return;
}
resolve(data.Items);
}
)
)
]);
// do something with posts, etc...
}
docClient is generated in a component using:
new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'})
where AWS is the aws-sdk module

get instagram public media using new api

I am trying to get the 10 latest instagram photos of a public profile in my nodejs app:
const request = require('request');
const accessToken = '1234567890123456789012345678901234567890';
const url = `https://api.instagram.com/v1/users/1470414259/media/recent/?access_token=${accessToken}&count=10`;
request.get(url, { json: true }, (err, res, body) => {
console.log('print the body: ', body);
});
my attempt is not successful, and i get no results.
Could somebody help me get this going?
i am trying to follow the example here : https://www.instagram.com/developer/endpoints/users/#get_users_media_recent
update:
i updated the username to user ID, but i am still getting no response:
{ meta:
{ code: 400,
error_type: 'APINotFoundError',
error_message: 'this user does not exist' } }
update 2:
actually i realize that my access token has some restrictions:
{"meta": {"code": 400, "error_type": "OAuthPermissionsException", "error_message": "This request requires scope=public_content, but this access token is not authorized with this scope. The user must re-authorize your application with scope=public_content to be granted this permissions."}}
why is this happening? i am just trying to get some public profile feeds.
update 3:
is there any other way to bypass these access token permissions and just get the 10 media of a public user?
take a look at the json that this link is returning:
https://www.instagram.com/aa/?__a=1
body.user.media[0] will give you the last photo object
body.user.media[1] will give you the photo before the last one object
.. and so on.
what you have to do here is change aa in the url I provided to your desired username.
ps. you might use some json viewer tools to organize the json if you browser doesn't support that
You have two problems there:
First of all the endpoint receives the user ID as param (not the username):
const url = `https://api.instagram.com/v1/users/${userId}/media/recent/?access_token=${accessToken}&count=10`;
Besides that, the endpoint responds with an object that has only one element: data, that is an array. So I don't know what data you are trying to get but you won't get it in body.user, you should go through the array and ask for the user in the corresponding position, for example try this: console.log(body.data[0].user).
And you of course must define a valid access token!

Firebase FCM error: 'InvalidRegistration'

I am currently trying to send a PushNotification to a Device Group using FCM with the help of Firebase Cloud Functions but once the notification is sent, it returns with code 200 but with failure :
SUCCESS response= {
multicast_id: 8834986220110966000,
success: 0,
failure: 1,
canonical_ids: 0,
results: [ { error: 'InvalidRegistration' } ]
}
Here is the code I am using to send this notification... what am I missing?
const options = {
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Authorization': 'key=' + serverKey,
},
body: {
to: groupId,
data: {
subject: message
},
notification: {
title: title,
body: body,
badge: 1,
},
content_available: true
},
json: true
};
return rqstProm(options)
.then((parsedBody) => {
console.log('SUCCESS response=', parsedBody);
})
.catch((err) => {
console.log('FAILED err=', err);
});
Where JSON values title, body, subject, message are String
In my case, I was sending notifications to topic ("topics/my-topic"). I was missing prepending / in the starting of topic so I was getting the same issue. SO topic should be /topics/my-topic.
May be this helps!!
There is an easier way to send a message to a device group from a Cloud Function. Use admin.messaging().sendToDeviceGroup(). Sample code and instructions are in this guide.
I think your current method is failing because there is something wrong with the group notification key provided in groupId. It should be the string key value that was returned when you created the device group. The error codes are listed in this table. For 200/InvalidRegistration it says:
Check the format of the registration token you pass to the server.
Make sure it matches the registration token the client app receives
from registering with Firebase Notifications. Do not truncate or add
additional characters.
I was losing my mind with this InvalidRegistration error.
Eventually the problem was that I was subscribing my device to "example" but sending the notification json to: "example".
But we actually need to send to "/topics/example"
2 hours of my life wasted..
A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app.
Al you need to do is add a http header 'project_id' with your sender id.
I was getting InvalidRegistration:
Basic meaning: you are using the wrong token. Why? This may happen when you a new registrationToken is given to you in onNewToken (docs), but for some reason you are using the old token. That could happen when:
You're using a different push notification library which remembers token (stores it somewhere locally) and you didn't update that library with the new token.
Your application (or other library dependencies) implements another FirebaseMessagingService, and they conflict. Only one service can accept (react to) to the action sent by the FirebaseMessaging Android library's when a new token is given to it. You can double check this by opening the AndroidManifest.xml in Android Studio and selecting the Merged Manifest tab at the bottom of the tab. You can also place debuggers in each Service from each library you use. You'll see that only one service's onNewToken gets called.
When they conflict, one doesn't get the correct token, and the FCM registration token that gets registered would be wrong. Sending a message to a wrong registration, gets you InvalidRegistration.
for me, it was a mistake that I was passing an Id from my models instead of the tokens of the users
InvalidRegistration simply means that the token is either invalid or expired. You can uninstall the app and then reinstall and get a new token and then try with that token. This will definitely solve your problem.
You can read more here.

Signup with Facebook JS SDK

I'm trying to create a signup functionality with Facebook JS SDK, But i got different type of records, than i search a lot and come to know that Facebook update his app policy's, they release v2.0 for apps.
Now it sending different response on login
Object {authResponse: Object, status: "connected"}
authResponse: Object
accessToken: "CAATZCeMqNYsABADVG3lHL1WYJiwnZASJIBzUtkfB4MFyFUC21g6myDeAP6WDSKkd8ZAnggffW5sIJzSDqmqxxvRgdeT7MKRXJ0L8Logg57PYwawEBSbgqz9I5qGU9Oo7uvaRN5MupjCfvo5w4bfCDZA5uvMkg7AK8DbwhXW4WoGHZBgG6EsmDDWZCnbVpUxWUZD"
expiresIn: 4562
signedRequest: "GXGqWXN9C5IzSy6jf2NOOQK7-ZK9JisKBCLEBHbaoIc.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImNvZGUiOiJBUUE5c21GSWZ1dXoxMnpvNVV0MGdYYXNXclI1blJXZXh1NElGWHFFMHhnUDM3T0pScUJyaDhZeEo2YWt5aHlJYXUzc3UyU2hhZVczUzh1aHRheWJGX3N3aWtfSmVfUDRwallOeV9IX1JpTEs2ZWZKNlpETDQ5MC1OVUxKSzN4SWw2QmtfVXJER2ZrVE1uV1haZFY3LU02Y19xMjRwWjJUOEo2anB6djNGQ0Z0YUs5bW5fMVVobThycjRlVmlQOVVtVVNMZXA5NTg1X1ZhSHg2YkUyTEFBMUl3OUdfQXJnb2JRSldQaERXczlTSDdONzNzS1dlakQ3MDNsTmhpblhjbUt0RXU1NmpvTnVMODhvME9ZUXVtVEFfbzF4SEJ5YndSbDU4ekVrWEpMdVUtVFZfejY5UW9KekFMeFRCekNBUHBXcEQtVzUyVHlKd0tJNjBMTU5Qbjg0bCIsImlzc3VlZF9hdCI6MTM5OTI3NTgzOCwidXNlcl9pZCI6IjEwMDAwMDAxNTU5MzEwNyJ9"
userID: "100000015593107"
__proto__: Object
status: "connected"
__proto__: Object
}
as in last SDK we get email using
response.email
but in new one we got only userID which is also app specific and
response.authResponse.signedRequest
So i search how we can extract the "signedRequest" because i think the rest value surely encrypted in this code ..
So i used
$signed_request= $_POST['maindata'];
if (isset($signed_request))
{
$data_signed_request = explode('.', $signed_request); // Get the part of the signed_request we need.
$jsonData = base64_decode($data_signed_request['1']); // Base64 Decode signed_request making it JSON.
$objData = json_decode($jsonData, true); // Split the JSON into arrays.
}
print_r($objData);
but its again send me
Array
(
[algorithm] => HMAC-SHA256
[code] => AQA9smFIfuuz12zo5Ut0gXasWrR5nRWexu4IFXqE0xgP37OJRqBrh8YxJ6akyhyIau3su2ShaeW3S8uhtaybF_swik_Je_P4pjYNy_H_RiLK6efJ6ZDL490-NULJK3xIl6Bk_UrDGfkTMnWXZdV7-M6c_q24pZ2T8J6jpzv3FCFtaK9mn_1Uhm8rr4eViP9UmUSLep9585_VaHx6bE2LAA1Iw9G_ArgobQJWPhDWs9SH7N73sKWejD703lNhinXcmKtEu56joNuL88o0OYQumTA_o1xHBybwRl58zEkXJLuU-TV_z69QoJzALxTBzCAPpWpD-W52TyJwKI60LMNPn84l
[issued_at] => 1399275838
[user_id] => 100000015593107
)
I'm wondering how we can get the email address , Please if you have some idea please let me know
You can use the acquired access_token and use the Facebook API endpoint GET /me and pass the access_token the response of the said endpoint will allow you to obtain the email address given that the email address being associated to the Facebook is account is still valid.

Categories

Resources