How the users can access my Elasticsearch database in my Django SaaS? - django

Let's say that I have a SaaS based on Django backend that processes the data of the users and write everything to the Elasticsearch. Now I would like to give users access to search and request their data stored in ES using all possible search requests available in ES. Obviously the user should have only access to his data, not to other user's data. I am aware that it can be done in a lot of different ways but I wonder what is safe and the best solution? At this point I store everything in one index and type in the way shown below but I can do this in any way.
"_index": "example_index",
"_type": "example_type",
"_id": "H2s-lGsdshEzmewdKtL",
"_score": 1,
"_source": {
"user_id": 1,
"field1": "example1",
"field2": "example2",
"field3": "example3"
}
I think that the best way would be to associate every document with the user_id. The user would send for example GET request with body and authorization header with Token. I would use Token to extract id of the user for example in this way
key = request.META.get('HTTP_AUTHORIZATION').split()[1]
user_id = Token.objects.get(key=key).user_id
After this I would redirect his request to ES and only data that meet requirements and belongs to this user would be returned. Of course I could do this like shown above where I also add field user_id. For example I could use post_filter in this way:
To every request I would add something like this:
,
"post_filter": {
"match": {
"user_id": 1
}
}
For example the user sends GET with body
{
"query": {
"regexp": {
"tag": ".*example.*"
}
}
}
and I change this in my backend and redirect request to ES with body:
{
"query": {
"regexp": {
"tag": ".*example.*"
}
},
"post_filter": {
"match": {
"user_id": 1
}
}
}
but it doesn't seem to me that including this field in _source is a good idea. I am almost sure that it can be solved in a more optimal way than post_filtering. I see a lot of information about authorization in ES however I can’t find how can I associate document with user_id and then search only his documents without post_filtering. Any ideas?
UPDATE
My current solution looks in they way shown below however as I mentioned I believe that it is not optimal way. If anyone has an idea how can I solve this in the way described above I will be grateful for help.
I send for example
{
"query": {
"regexp": {
"tag": ".*test.*"
}
}
}
In Django backend I just do
key = request.META.get('HTTP_AUTHORIZATION').split()[1]
user_id = Token.objects.get(key=key).user_id
body = json.loads(request.body)
body['post_filter'] = {"match": {"user_id": user_id}}
res = es.search(index="pictures", doc_type="picture", body=body)
output = []
for hit in res['hits']['hits']:
output.append(hit["_source"])
return Response(
{'output': output},
status=status.HTTP_200_OK)

In elasticsearch 7.1, you have now basic security in the free version of elasticsearch. Thanks to that, you can control per indice thé Access of your user.

Related

Facebook API process shared object [duplicate]

I just tried through the Graph API Explorer with this path /v2.4/10153513872748291 and I've got this result:
{
"error": {
"message": "(#12) singular links API is deprecated for versions v2.4 and higher",
"type": "OAuthException",
"code": 12
}
}
But https://developers.facebook.com/docs/reference/api/post/ doesn't say anything about deprecation.
I'm not sure if I miss something, or there's another way to get info about an individual post.
Edit: v2.3 works, but v2.4 is the latest one.
Looks like you now need to the combination of the id of the user or page that made the post (or whose wall it is on), an underscore, and then the post id.
For your example post, 10153513872748291, that is made by a page Drama-addict, that has the id 141108613290 – so 141108613290_10153513872748291 will work.
And so does 788239567865981_10153513872748291, because 788239567865981 is the id of the user making the post.
Firstput userId underscore add postId /Likes to check Like status in facebook
userId_post_Id/Likes to fetch Likes Records
userId_post_Id/Comments to fetch Comments Records
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=303261006522998_751199848395776%2FLikes&version=v2.9
**In this link Right side Get Token indide GetAccessToken to select Permission**
303261006522998_751199848395776/Likes
303261006522998_751199848395776/Comments
{
"data": [
{
"id": "124778301449917",
"name": "Manisha Gera"
},
{
"id": "1680577265523548",
"name": "Rubi Sharma"
}
],
"paging": {
"cursors": {
"before": "MTI0Nzc4MzAxNDQ5OTE3",
"after": "MTY4MDU3NzI2NTUyMzU0OAZDZD"
}
}
}

I want to manipulate the file in MarkLogic using Python

declareUpdate();
//get Docs
myDoc = cts.doc("/heal/scripts/Test.json").toObject();
//add Data
myDoc.prescribedPlayer =
[
{
"default": "http://www.youtube.com/watch?vu003dhYB0mn5zh2c"
}
]
//persist
xdmp.documentInsert("/heal/scripts/Test.json",myDoc,null,"scripts")
You're looking to add a new JSON property. You can do that using a REST Client API request, sending a PATCH command. Use an insert instruction in the patch.
See the note in Specifying Position in JSON, which indicates that
You cannot use last-child to insert a property as an immediate child of the root node of a document. Use before or after instead. For details, see Limitations of JSON Path Expressions.
Instead, your patch will look something like:
{
"insert": {
"context": "/topProperty",
"position": "after",
"content":
[
{
"default": "http://www.youtube.com/watch?vu003dhYB0mn5zh2c"
}
],
}
}
where topProperty is a JSON property that is part of the root node of the JavaScript object you want to update.
If that approach is problematic (for instance, if there is no topProperty that's reliably available), you could also do a sequence of operations:
retrieve the document
edit the content in Python
update the document in the database
With this approach, there is the possibility that some other process may update the document while you're working on it. You can either rely on optimistic locking or a multi-statement transaction to work around that, depending on the potential consequences of someone else doing a write.
Hey #Ankur Please check below python method,
def PartialUpdateData(self,filename, content, context):
self.querystring = {"uri": "/" + self.collection + "/" + filename}
url = self.baseUri
self.header = {'Content-Type': "application/json"}
mydata = {
"patch":[{ "insert": {
"context": context,
"position": "before",
"content": content
}}]}
resp = requests.patch(url + "/documents", data=json.dumps(mydata),
headers=self.header, auth=self.auth, params=self.querystring)
return resp.content
I hope this can solve your problem.

How to set variable Request format in Amazon Api Gateway?

I want to make a Model for request where some part of the request structure may change.
As i don't have uniform structure here. How can i define json model for Amazon Api Gateway?
Request:
Here data inside items.{index}.data is changing according to type_id. Also we are not sure about which item with perticular type_id come at which {index}. even the type of items.{index}.data may change.
{
"name":"Jon Doe",
"items": [
{
"type_id":2,
"data": {
"km": 10,
"fuel": 20
}
},
{
"type_id": 5,
"data": [
[
"id":1,
"value":2
],
.....
]
},{
"type_id": 3,
"data": "data goes here"
},
....
]
}
How should i do this?
API Gateway uses JSON schema for model definitions. You can use a union datatype to represent your data object. See this question for an example of such a datatype.
Please note that a data model such as this will pose problems for generating SDKs. If you need SDK support for strictly typed languages, you may want to reconsider this data model.

How to write CouchDb views?

I have list of such documents in my database of couchDB.
{
"_id": "9",
"_rev": "1-f5a9a0b76c6ae1fe5e20f1a1f9e6f8ba",
"Project": "Vaibhava",
"Type": "activity",
"Name": "Civil_Clearence",
"PercentComplete": "",
"DateAndTime": "",
"SourcePMSId": "1049",
"ProgressUpdatedToPMSFlag": "NO",
"UserId": "Kundan",
"ParentId": "5"
}
How to write a view function so that when i pass a doc._id as a key then i must get all siblings of that doc._id(docs with ParentId same as the key which I have sent)??
As said in another answer, it is not possible to do that with a single request.
However, you can do the following instead:
Define a map (with no reduce) view indexed on ParentID:
function(o) {
if (o.ParentID) {
emit(o.ParentID);
}
}
Send a first request to your object to know the ID of its parent:
GET /myDatabase/myObject
Then send a request to your view
GET /myDatabase/_design/myApp/_view/myView/?key="itsParent"&include_docs=true
Having several requests should not cause much harm here, since their number (2) is constant.
Moreover you can hide them behind a single request handled by NodeJS.
Unfortunately, you would need to chain together two map-reduce functions to achieve this result and that functionality is not available in CouchDB. See this question for further information.

getting high resolution photos that were posted on a page wall/feed

I'm getting my page wall with the open graph.
And when someone posted a photo, I get it on the JSON
{
"id": "27888702146_10150369820322147",
"from": {
"name": "brocoli",
"category": "Record label",
"id": "27888702146"
},
"message": "Vincent Epplay / David Fenech / Jac Berrocal \u00e0 Beaubourg ce soir, 19h, gratos.",
"picture": "http://photos-f.ak.fbcdn.net/hphotos-ak-snc7/305819_10150369820292147_27888702146_8255527_583491475_s.jpg",
"link": "https://www.facebook.com/photo.php?fbid=10150369820292147&set=a.386279807146.165840.27888702146&type=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yz/r/StEh3RhPvjk.gif",
"type": "photo",
"object_id": "10150369820292147",
"created_time": "2011-10-16T08:22:21+0000",
"updated_time": "2011-10-16T08:22:21+0000",
"likes": {
"data": [
{
"name": "brocoli",
"category": "Record label",
"id": "27888702146"
},
{
"name": "Agathe Morier",
"id": "601668526"
}
],
"count": 2
},
"comments": {
"count": 0
},
"is_published": true
}
The problem is that the picture link is a low resolution copy of the picture.
How can I get the URL of the full picture ?
Thanks!!
Best
Geoffroy
You can get different version of the photo by querying Graph API with its object_id (not photo post_id which is id in results you provided).
Once you'll request the photo by object id you'll get array of images with URLs and dimensions:
http://graph.facebook.com/10150369820292147?fields=images
If you're attempting to access posts on a Facebook Page (such as for a company) instead of typical user profile, you firstly need to fetch the feed like this:
https://graph.facebook.com/v15.0/YOUR_PAGE_ID_HERE/feed?fields=attachments&access_token=...
And then access data[0].attachments.data[0].subattachments.data[0].target.id to get the object ID (or "target ID" in this case) which you can then use to perform an additional query to obtain the higher resolution image. Increment the numbers to get additional posts and images inside each post.
All you need to do is :
http://graph.facebook.com/me?fields=picture.height(961)
// replace 961 with your required height which u want
You can do this from the main posts list now using
/v2.3/105753476132681/posts?limit=5&fields=likes.summary(true),comments.summary(true), attachments
If attachments doesn't work, try full_picture - but that just gave the 100x100 image for me as well.
Attachments returns a data hash with a 640x480 version of the image at least (not sure what my orig. photo size was)
Use this Code. Its Work for me and get Clear Image
String PICTURE_URL;
String getPicture = hashMap.get("picture");
if (getPicture.contains("_t.")) {
PICTURE_URL = getPicture.replaceAll("_t.", "_n.");
} else if (getPicture.contains("_a.")) {
PICTURE_URL = getPicture.replaceAll("_a.", "_n.");
} else if (getPicture.contains("_s.")) {
PICTURE_URL = getPicture.replaceAll("_s.", "_n.");
} else if (getPicture.contains("_q.")) {
PICTURE_URL = getPicture.replaceAll("_q.", "_n.");
}
url=new URL(PICTURE_URL);
Bitmap bitmap=BitmapFactory.decodeStream(url.openConnection().getInputStream());
((ImageView)view.findViewById(R.id.imageView_FullImage)).setImageBitmap(bitmap);
Though requesting a photo by its object_id will return an array of images with different dimensions, in some cases this approach would require an additional call to the Facebook API.
A simpler approach is to add full_picture to your list of parameters, which will extract the highest resolution image associated with the post.
/v2.2/6275848869/posts?fields=full_picture
For example, if you want to extract all the posts from a Facebook page in the past X days, with the object_id approach you'd need to call the API 3 times:
To get the page info.
To extract the list of posts and obtain the object_id for each post.
For each object_id, to retrieve the list of higher resolution images.