Reputation: 2048
I'm using rest-framework-jwt and just wanna know a few things.
First, I make the login with the email and password, and I get the token. It works well.
but I also wanna create a token in my register. so, I use this function:
def create_token(user):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
The problem is that I don't have an username. So, it doesn't work. :) I thought, if it works with the login, it should work with the register. But not. :smiley:
Even if I wrote this USERNAME_FIELD = 'email'
in my model. It always asks for a username in my create_token
function.
But second, I would like to create the token with just the email, password, and uuid
And third... Is the same token from my register and from my login? To make the requests, it should be the same.
Thank you!
Upvotes: 3
Views: 3272
Reputation: 2048
I found the answer.
I read this doc and realized that I just need to redefine those functions. In my case, I preferred to override jwt_playload_handler
So, I added the function to a file called utils.py and it looks so:
from calendar import timegm
from datetime import datetime
from rest_framework_jwt.compat import get_username_field
from rest_framework_jwt.settings import api_settings
def jwt_payload_handler(user):
username_field = get_username_field()
print(user['uuid'])
payload = {'user_id': user['uuid'], 'email': user['email'], 'username': user['email'],
'exp': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA, username_field: user['email']}
# Include original issued at time for a brand new token,
# to allow token refresh
if api_settings.JWT_ALLOW_REFRESH:
payload['orig_iat'] = timegm(
datetime.utcnow().utctimetuple()
)
if api_settings.JWT_AUDIENCE is not None:
payload['aud'] = api_settings.JWT_AUDIENCE
if api_settings.JWT_ISSUER is not None:
payload['iss'] = api_settings.JWT_ISSUER
return payload
and then, in the settings.py
JWT_AUTH = {
'JWT_PAYLOAD_HANDLER':
'users.utils.jwt_payload_handler',
}
to say it, that it should take my function.
and in my views:
def create_token(user):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
that's it
Upvotes: 6