import logging from datetime import datetime from rest_framework_simplejwt.tokens import RefreshToken from rest_framework_simplejwt.settings import api_settings from django.conf import settings from app.models import VendorApiCredentials from app.api import api import jwt from app.util import datetime_util log = logging.getLogger(__name__) class CustomRefreshToken(RefreshToken): @classmethod def for_user(cls, user, loan_application): """ Returns an authorization token for the given user that will be provided after authenticating the user's credentials. """ payload = { api_settings.USER_ID_CLAIM: user.id, 'token_type': 'access', 'exp': int((datetime_util.now_ist() + settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']).timestamp()), 'iat': datetime_util.get_epoch_secs(), } vendor_id = loan_application.get_vendor_id() if not vendor_id: log.error('Missing vendor id for loan application') return api.UNABLE_TO_FETCH_VENDOR_ID, '' payload['vendor_id'] = vendor_id vendor_api_credentials = VendorApiCredentials.objects.filter(vendor_id=vendor_id).first() if not vendor_api_credentials.key: log.error('Missing vendor key for loan application') return api.UNABLE_TO_FETCH_VENDOR_KEY, '' token = jwt.encode(payload, vendor_api_credentials.key, algorithm=settings.SIMPLE_JWT['ALGORITHM']) return api.SUCCESS, token