How to use cookies in python with other platform - python

My python app lets people upload files on a Third-party platform.
They need to ask my server for a token for the platform to verify
It looks like:
when people upload files they post to the platform
<form method="post" action="http://upload.qiniu.com/"
enctype="multipart/form-data">
<input name="key" type="hidden" value="<resource_key>">
<input name="x:<custom_name>" type="hidden" value="<custom_value>">
<input name="token" type="hidden" value="<upload_token>">
<input name="file" type="file" />
<input name="crc32" type="hidden" />
<input name="accept" type="hidden" />
</form>
I wonder if it's ok to ask for the token each time someone tries to upload files, or just let people get the token when they login, set the token into the cookie and make its lifetime as long as the cookie's?
Thanks.

It is normal practice to store client access tokens as cookies for returning users.
This and also this SO post also back this idea up.

Related

How would I translate this html POST request into python

I am having difficulty translating this specific HTML POST request into Python - I am attempting to exploit a security vulnerability on a test server.
director=
<form action="http://127.0.0.1:8000/card/0" method="POST">
<input type="hidden" name="amount" value="8000" />
<input type="hidden" name="username" value="hacker" />
<input type="submit" value="View my photos" />
</form>
Before you run the code below. Run pip install requests.
import requests
response = requests.get("http://api.open-notify.org/astros.json")
print(response)
>>>> Response<200>
See more details in the URL below.
https://www.nylas.com/blog/use-python-requests-module-rest-apis/

How can one use Webhooks from Paypal in its django application

I'm using django-paypal and paypalrestsdk to integrate Paypal payment & subscriptions to my website.
I've looked over django-paypal and other modules but I wasn't able to fully understand the process of handling a webhook.
I'm getting a 405 Error in my console when I'm completing a payment.
I have successfully created a paypal sandbox account for testing purposes ( two user accounts were automatically created on it for tests ).
In my settings.py:
PAYPAL_RECEIVER_EMAIL = "the email"
PAYPAL_IDENTITY_TOKEN = "_BB3dqp-crOrUo2uh84g0zN2alX0LwWPAT85r0g-2Eo0"
In my index.html:
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="business" value="my_email" id="id_business" />
<input type="hidden" name="amount" value="1" id="id_amount" />
<input type="hidden" name="item_name" value="Subscription Package" id="id_item_name" />
<input type="hidden" name="notify_url" value="website/page" id="id_notify_url" />
<input type="hidden" name="cancel_return" value="website/page" id="id_cancel_return" />
<input type="hidden" name="return" value="website/page" id="id_return_url" />
<input type="hidden" name="invoice" value="UID" id="id_invoice" />
<input type="hidden" name="cmd" value="_xclick" id="id_cmd" />
<input type="hidden" name="charset" value="utf-8" id="id_charset" />
<input type="hidden" name="currency_code" value="USD" id="id_currency_code" />
<input type="hidden" name="no_shipping" value="1" id="id_no_shipping" />
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="Buy it Now" />
</form>
And my views.py:
class PayPalWebhook(View):
#staticmethod
def post(request):
event_json = json.loads(request.body)
print '=========='
print event_json.type
print '=========='
print event_json
return HttpResponse(status=200)
class PaypalAPI(View):
#staticmethod
def post(request):
pass
shall I pass anything in my PaypalAPI class in order to get my form working as it should ? ( for the moment it correctly sends the payment but it uses the values inside the form parameters and that's not what I want)
how can I get rid of that 405 error ? What am I doing wrong ?( as a mention, I created a webhook in dashboard)
I would just like to see the webhooks in my console, that's all.
Hope this helps: 405 is usually when the API/Endpoint you are calling is used with an incorrect method. For example using a POST for a HTTP Call which only supports GET or not using the correct endpoint.
Python SDKs are a good point to start with as well https://github.com/paypal/PayPal-Python-SDK
Also, its a good practice to not share any tokens in forums/QnA sites. :)
You need to add
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def PayPalReturnView(request):
# Do something here
to the view that PayPal posts too. I think I got your problem right but anyway try adding more info: your urls for example which are crucial here.

Pass Python parameters to HTML

I've the following HTML code:
<html>
<form action="index.php" method="post">
Enter Input:
<input type="text" class="textbox" name="usn" id="usn" required />
<input class="buttongo" type="submit" value="Go" />
<input type="hidden" name="task" value="getResult"/>
</form>
</html>
I want to write a python script, which executes the above HTML, passing a value parameter to the first input statement to the above HTML. That is,
<html>
<form action="index.php" method="post">
Enter Input:
<input type="text" class="textbox" name="usn" id="usn" value="FromPython" />
<input class="buttongo" type="submit" value="Go" />
<input type="hidden" name="task" value="getResult"/>
</form>
</html>
Further, is there a way in which I can directly send the value to index.php and get the response?
(P.S.: I want to loop the value from 0 to 100 and save the response generated in a file)
Why don't you send the request using python ? You can send the requests inside a loop and pass the parameters you want.
Making requests with the requests module
sample code :
import requests
for i in range(101):
payload = {'usn': i}
response = requests.post("index.php", data=payload)
# do something with response
Use urllib module, documentation at: https://docs.python.org/2/library/urllib.html
As described in the link, this module provides a high-level interface for fetching data across the World Wide Web.

Creation of StringToSign

I am reading the documentation of passing a querystring to Amazon's S3 for authentication, and can't seem to grok how exactly the StringToSign is created and used. I am looking for a concrete example to illustrate (1) how to construct the StringToSign, and (2) once I have the signature, how to call the form.
For example's sake, let's say the following is my information:
Content-type='image/jpeg'
Bucket='test-bucket'
Key = 'filename'
ACL = 'public-read'
Expiration = '(never expires)'
Access Key = '12345'
Secret Password = '1a2b3c'
File = <file the user uploads>
How would I get the StringToSign value from this? And once I have that, how would I create the following form:
<form action="??" method="post" enctype='multipart/form-data' class="upload-form">
<input name="file" type="file">
</form>
And for reference: http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html#RESTAuthenticationQueryStringAuth. Thank you.
Based on what you described, it seems like you want to support browser-based uploads using POST. There is a section of the AWS documentation which talks about this.
As an overview keep in mind you'll either have to make your bucket publically writeable or include a policy document. I'll assume you'll be including a policy document (check the docs if you don't want to):
A policy document is just a fragment of JSON that is used to authenticate the request, and gives a bunch of conditions that must be met before data is uploaded. E.g:
"expiration": "2020-12-01T12:00:00.000Z",
"conditions": [
{"acl": "public-read" },
{"bucket": "test-bucket" },
["eq", "$key", "filename"],
]
}
This says the action to upload will be allowed until 2020, given that the bucket is only publically readable, the bucket name is 'test-bucket' and the key is exactly equal to 'filename'.
Now, to construct your signature you take the above JSON doc, UTF-8 encode it and then base64 that and then sign the whole thing using your secret access key (using hmac sha1) and finally base64 that whole thing
policy_data = ... # stuff above
enc_policy = base64.b64_encode(policy_data.encode('utf8'))
signed = base64.b64_encode(hmac.new(AWS_SECRET, enc_policy, hashlib.sha1))
Then finally, your form would look something like this:
<form action="http://test-bucket.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
Key to upload: <input type="input" name="key" value="filename" /><br />
<input type="hidden" name="acl" value="public-read" />
<input type="hidden" name="success_action_redirect" value="http://test-bucket.s3.amazonaws.com/successful_upload.html" />
Content-Type: <input type="input" name="Content-Type" value="image/jpeg" /><br />
<input type="hidden" name="AWSAccessKeyId" value="YOUR_ACCESS_KEY_ID" />
<input type="hidden" name="Policy" value="<enc_policy from above>" />
<input type="hidden" name="Signature" value="<signed from above>" />
File: <input type="file" name="file" /> <br />
<!-- The elements after this will be ignored -->
<input type="submit" name="submit" value="Upload to Amazon S3" />
</form>

How to pass variables to a form before it is processed

I have the following template form, containing several variables.
<form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form">
<input type="hidden" name="key" value="videos/{{filename}}">
<input type="hidden" name="AWSAccessKeyId" value="{{access_key}}">
<input type="hidden" name="acl" value="public-read">
<input type="hidden" name="policy" value="{{policy}}">
<input type="hidden" name="signature" value="{{signature}}">
<input type="hidden" name="Content-Type" value="{{content_type}}">
<input name="file" type="file">
<input type="submit" value="Upload" name="upload">
</form>
However, as soon as the submit button is hit, the form is sent to amazon, and I'm not able to pass it variables. This is what I've been trying to do, unsuccessfully --
if 'upload' in request.POST:
policy = base64.b64encode(...)
signature = base64.b64encode(
hmac.new('secret_key', policy, sha).digest())
file = request.POST['files']
filename=file.name
content_type=mimetypes.guess_type(filename)[0]
What do I need to do to pass the variables to the form after the POST request but BEFORE amazon processes the form? Thank you.
You should change your form's action to your django view and in your view you can re-post to https://me.s3.amazonaws.com/:
In your template
<form action="http://mywebsite/upload" method="post" ...
In your view.py:
def upload(request):
# Your treatment here.
# Post the data to amazon S3.
urllib2.urlopen("https://me.s3.amazonaws.com/", your_data)
...
You could change the form to POST to one of your own views, then do your post-processing in your view, and then within your view code, issue a POST to Amazon with the correct values using, say, urllib2 or similar.

Categories