from itsdangerous import URLSafeTimedSerializer
from system import Config
serializer = URLSafeTimedSerializer(Config.SECRET_KEY)
def serialise_token(**kwargs):
return serializer.dumps(kwargs)
def deserialise_token(token):
try:
return serializer.loads(token,max_age=1800)
except:
print(serializer.loads(token,max_age=1800))
return None
Error Signature age 176518 > 1800 seconds
I am generating the token using the serialise_token. But when I am deserialising it with deserialise I am getting the above error.
And why the age is showing 176518 seconds despite I have created the token now?
Related
I'm attempting to write a django-allauth Provider for Snapchat and I'm stuck at a roadblock.
Snapchat requires PKCE parameters. I first changed the AUTH_PARAMS.
'AUTH_PARAMS': {
'code_challenge': 'state',
'code_challenge_method': "S256"
}
This has only resulted in invalid responses from the Snapchat API upon Access_Token Request after I have the code response.
This error the first error I got.
{'error': 'invalid_request', 'error_description': 'Invalid code_verifier length.', 'state': ''}
After overriding the SocialLogin.stash_state I receive this error.
{'error': 'invalid_grant', 'error_description': 'Invalid code_verifier.', 'state': ''}
From what I can dig through the code of all auth I can't find anything in the codebase on the PKCE parameters or base64 Url SHA256 encoding.
I'm willing to implement the solution but I'm stuck finding where to subclass the state parameters then match them after.
There are some issues around the Snapchat Docs with this as well.
https://gist.github.com/CisarJosh/733bb76a13f36f0a7944f05d257bb3f6
This is a gist of some of my attempts.
I think this will get you started:
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
import secrets
import base64
import hashlib
import urllib.parse
VOCAB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-._~0123456789"
def generate_code_verifier() -> str:
length = max(43, secrets.randbelow(129))
return "".join([secrets.choice(VOCAB) for i in range(0, length)])
def generate_state() -> str:
return secrets.token_urlsafe(32)
class SnapchatProvider(OAuth2Provider):
def get_auth_params(self, request, action):
params = super().get_auth_params(request, action)
code_verifier = generate_code_verifier()
state = generate_state()
# store this state token somewhere so it can be looked up
challenge = hashlib.sha256(code_verifier).digest()
encoded = base64.b64encode(challenge)
urlencoded = urllib.parse.quote_plus(encoded)
params.update(state=state, code_challenge=urlencoded)
return params
That's my interpretation of the spec for that part.
The API result at /date is giving an {"message": "Internal server error"} error. /hello is successfully returning 'hello world'.
The ultimate goal is to return the number of days passed so far this year.
'''
from chalice import Chalice
from datetime import date
app = Chalice(app_name='days')
app.debug = True
#app.route('/hello')
def index():
return {'hello': 'world'}
#app.route('/date')
def days():
return date.today()
'''
Based on the comments.
The issue was that date.today() was not returning json.
The solution was to convert it to string so that is correctly recognized as a json string: something like str(date.today())
So as the title suggest, I am able to send a POST request, and see in my postgresql database (through the pgAdmin client) that the data is being submitted and stored, however I run into a number of errors in the response output. It may have to do with the Authorization, as I have never worked with authorizing before. Both errors produce responses with 500 errors, contrary to what I would like.
The POST request is as follows:
def create():
"""
Create Student Function
"""
req_data = request.get_json()
try:
data = student_schema.load(req_data)
except ValidationError as err:
error = err.messages
return custom_response(error, 400)
#check if student exists in db
student_in_db = Student.get_user_by_email(data.get('email'))
if student_in_db:
message = {'error': 'Student already exists, please supply another email address'}
return custom_response(message, 400)
student = Student(data)
student.save()
ser_data = student_schema.dump(student).data
token = Auth.generate_token(ser_data.get('id'))
return custom_response({'jwt_token': token}, 201)
The custom_response is as so:
def custom_response(res, status_code):
"""
Custom Response Function
"""
return Response(
mimetype="application/json",
response=json.dumps(res),
status=status_code
)
Error 1
The new entry is stored, however the response to the server is still a 500 error. The error output is an attribute error pointing towards
ser_data = student_schema.dump(student).data
which is apparently a dict object, thus has no attribute data.
Error 2
Emails are declared unique in my database, thus when trying to create another user with the same email, I get a unique constraint failure, which leads to a 500 response, even though I have the built in function of checking if the student is already in the database.
With flask_sqlalchemy, I expect to see
db.session.add(student)
db.session.commit()
unless you're doing that in
student.save()
I am running the below program.But am getting the below error Message.
401 ****
401 ****
(keeps on repeating)
The code(got from some forum) basically tries to connect to Twitter and fetch tweets.
When its ran on ubuntu terminal the 401 error message appear.
import sys
import json
import pymongo
import tweepy
consumer_key="XX" ##all the keys and codes have to be strings
consumer_secret="XX"
access_token = "XX"
access_token_secret = "XX"
# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
def on_data(self, data):
# Twitter returns data in JSON format - we need to decode it first
decoded = json.loads(data)
# Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
print '#%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
print ''
return True
def on_error(self, status):
print status
if __name__ == '__main__':
l = StdOutListener()
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
print "Showing all new tweets for #programming:"
# There are different kinds of streams: public stream, user stream, multi-user streams
# In this example follow #programming tag
# For more details refer to https://dev.twitter.com/docs/streaming-apis
stream = tweepy.Stream(auth, l)
stream.filter(track=['programming'])
This is how it works..!!!
Twitter keeps track of the current time.
If an API request to authenticate comes from a server that claims it is a time that is outside of 15 minutes of Twitter time, it will fail with a 401 error.
Just reset your system's clock according to world clock or let it govern by internet your problem will be solved.
Good luck..!!!
Running into a very stange error. I'm running Django on my Mac OSX and when I tried to send an email from my application it hangs and gives me this error: "Error 61 Connection Refused"
Any ideas? I don't have my firewall turned on. I can upload an image of the error if needed.
Have you actually configured the EMAIL_* settings in settings.py? Error 61 is the error you get if you leave it on the default values and you don't have a local SMTP server running.
Alternatively, as Peter suggests, if you have set it up then you might need to use authentication with your SMTP server.
Being totally Max OS X ignorant, my first guess would be that your SMTP server requires authentication.
Its simple, if sendmail works via command-line, copy the code from http://djangosnippets.org/snippets/1864/ into a file called sendmail.py
"""sendmail email backend class."""
import threading
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from subprocess import Popen,PIPE
class EmailBackend(BaseEmailBackend):
def __init__(self, fail_silently=False, **kwargs):
super(EmailBackend, self).__init__(fail_silently=fail_silently)
self._lock = threading.RLock()
def open(self):
return True
def close(self):
pass
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not email_messages:
return
self._lock.acquire()
try:
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
finally:
self._lock.release()
return num_sent
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
try:
ps = Popen(["sendmail"]+list(email_message.recipients()), \
stdin=PIPE)
ps.stdin.write(email_message.message().as_string())
ps.stdin.flush()
ps.stdin.close()
return not ps.wait()
except:
if not self.fail_silently:
raise
return False
return True
Inside of settings.py, set the variable:
EMAIL_BACKEND = 'path.to.sendmail.EmailBackend'
I had a similar problem and found this link: http://dashasalo.com/2011/05/29/django-send_mail-connection-refused-on-macos-x/
Basically, you need to have a mail server running in order to send mail from it. If there is no mail server running you will get a 61.