def get_jwt_user(request):
     user = get_user(request)
     if user.is_authenticated:
         return user
     jwt_authentication = JSONWebTokenAuthentication()
     if jwt_authentication.get_jwt_value(request):
         user, jwt = jwt_authentication.authenticate(request)
     # print request.
     print jwt_authentication.get_jwt_value(request)
     print jwt_authentication.authenticate(request)
     return user
Exemplo n.º 2
0
    def get_assets_by_user(self, request, *args, **kwargs):
        """
        根据用户id查看用户资产
        """
        # Create the instance of JSONWebTokenAuthentication to do the authentication job
        authentication = JSONWebTokenAuthentication()

        # try:
        '''
        authentication.authenticate 会抛出异常,所以添加异常捕获
        '''
        auth_data = authentication.authenticate(request)
        if auth_data is None:
            raise exceptions.NotAuthenticated()

        user = auth_data[0].investor

        # user_id = request.query_params['id']
        # user = get_object_or_404(Investor, pk=user_id)
        queryset = user.asset_set.all()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
Exemplo n.º 3
0
 def post(self, request, format=None):
     try:
         auth = JSONWebTokenAuthentication()
         user = auth.authenticate(request=request)
         if user is not None and user[0].is_superuser:
             count = Quote.objects.filter(accepted=True).count()
             quote_id = Quote.objects.filter(accepted=True)[int(
                 random.random() * count)].id
             try:
                 while quote_id == Daily.objects.latest('date').quote_id:
                     quote_id = Quote.objects.filter(accepted=True)[int(
                         random.random() * count)].id
             except Daily.DoesNotExist:
                 pass
             daily = Daily.objects.create(quote_id=quote_id)
             daily.save()
             return Response({'status': 'success'})
         else:
             return Response({
                 'status': 'Error',
                 'message': 'Authentication failed'
             })
     except AuthenticationFailed:
         return Response({
             'status': 'Error',
             'message': 'Authentication failed'
         })
Exemplo n.º 4
0
    def get_jwt_user(request):
        user = get_user(request)
        if user.is_authenticated:
            return user
        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            jwt_value = jwt_authentication.get_jwt_value(request)
            import jwt
            try:
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                print("Signature expired.")
                msg = {
                    'jwtResponse': 'Signature has expired.'
                }
                return msg
            except jwt.DecodeError:
                print('Error decoding signature.')
                msg = {
                    'jwtResponse': 'Error decoding signature.'
                }
                return msg
            except jwt.InvalidTokenError:
                print("invalid token error")
                return exceptions.AuthenticationFailed()

            user = jwt_authentication.authenticate_credentials(payload)

            user, jwt = jwt_authentication.authenticate(request)
        return user
Exemplo n.º 5
0
    def process_request(self, request):
        """ Override only the request to add the user """
        try:
            return request.user
        except AttributeError:
            pass

        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        if user_auth_tuple is not None:
            request.user, _ = user_auth_tuple

            # Set last_seen on the user record if it has been > 10 mins
            # since the record was set.
            if not request.user.last_seen or (
                    request.user.last_seen <
                    timezone.now() - timedelta(minutes=LAST_SEEN_DELTA)):
                request.user.last_seen = timezone.now()
                request.user.save()
            return
Exemplo n.º 6
0
 def get_user_from_request(request):
     """
     Getting user from User table
     :param request:
     :return User or None:
     """
     JWT = JSONWebTokenAuthentication()
     user, payload = JWT.authenticate(request)
     return user if user else None
Exemplo n.º 7
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     token = request.META.get('HTTP_AUTHORIZATION', None)
     if token is None:
         return
     jwt_auth = JSONWebTokenAuthentication()
     try:
         auth = jwt_auth.authenticate(request)
         request.user = auth[0]
     except Exception:
         return
Exemplo n.º 8
0
    def process_view(self, request, *args):

        token = request.META.get('HTTP_AUTHORIZATION', '')
        if not token.startswith('JWT'):
            return
        jwt_auth = JSONWebTokenAuthentication()
        try:
            request.user = jwt_auth.authenticate(request)[0]
        except Exception:
            return
Exemplo n.º 9
0
    def get_jwt_user(request):
        user = get_user(request)

        # prevent the generation of Token for anonymous user
        if user.is_authenticated:
            return user
        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            user, jwt = jwt_authentication.authenticate(request)
        return user
Exemplo n.º 10
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     token = request.META.get('HTTP_AUTHORIZATION', '')
     if not token.startswith('JWT'):
         return
     jwt_auth = JSONWebTokenAuthentication()
     auth = None
     try:
         auth = jwt_auth.authenticate(request)
     except Exception:
         return
     request.user = auth[0]
 def get_jwt_user(request):
     try:
         user = get_user(request)
         if user.is_authenticated:
             return user
         jwt_authentication = JSONWebTokenAuthentication()
         if jwt_authentication.get_jwt_value(request):
             user, jwt = jwt_authentication.authenticate(request)
     except AuthenticationFailed as e:
         logger.error("Authentication failed: {}".format(e))
         return None
     return user
    def get_jwt_user(request):
        """

        :param request:
        :return:
        """
        user = get_user(request)
        if user.is_authenticated:
            return user
        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            user, jwt = jwt_authentication.authenticate(request)
        return user
Exemplo n.º 13
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     # token should be either in http headers or cookie..
     token = request.META.get("HTTP_AUTHORIZATION", "")
     if not token.startswith("JWT") and JWT_COOKIE_NAME not in request.COOKIES:
         return
     jwt_auth = JSONWebTokenAuthentication()
     auth = None
     try:
         auth = jwt_auth.authenticate(request)
     except Exception:
         return
     if auth is not None:
         request.user = auth[0]
Exemplo n.º 14
0
    def dispatch(self, *args, **kwargs):

        # Get auth Class
        auth = JSONWebTokenAuthentication()

        # Try to authenticate the params in request
        try:
            authentication = auth.authenticate(self.request)

        except AuthenticationFailed as e:
            return JsonResponse({"error": str(e)}, status=401)

        # If token was not found
        if authentication is None:
            return JsonResponse({"error": "Token has not been provided"}, status=401)

        return super().dispatch(*args, **kwargs)
Exemplo n.º 15
0
    def process_request(self, request):
        """ Override only the request to add the user """
        try:
            return request.user
        except AttributeError:
            pass

        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        if user_auth_tuple is not None:
            request.user, _auth = user_auth_tuple
            return
Exemplo n.º 16
0
 def delete(self, request, id, format=None):
     try:
         auth = JSONWebTokenAuthentication()
         user = auth.authenticate(request=request)
         if user is not None and user[0].is_superuser:
             Quote.objects.get(id=id).delete()
             return Response({'status': 'success'})
         else:
             return Response({
                 'status': 'Error',
                 'message': 'Authentication failed'
             })
     except AuthenticationFailed:
         return Response({
             'status': 'Error',
             'message': 'Authentication failed'
         })
Exemplo n.º 17
0
    def get_jwt_user(request):
        user = get_user(request)
        if user.is_authenticated:
            return user

        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            try:
                user, jwt = jwt_authentication.authenticate(request)
                return user
            except exceptions.AuthenticationFailed as af:
                logger.warning(
                    request,
                    "get_jwt_user(): AuthenticationFailed: {}.".format(af))
                return user  # AnonymousUser
        else:
            return user  # AnonymousUser
Exemplo n.º 18
0
    def get(self, request, id, format=None):
        user = None
        try:
            try:
                auth = JSONWebTokenAuthentication()
                user = auth.authenticate(request=request)
            except AuthenticationFailed:
                pass

            if user is not None and user[0].is_superuser:
                quote = Quote.objects.get(id=id)
            else:
                quote = Quote.objects.filter(accepted=True).get(id=id)

            prev_quote = Quote.objects.filter(
                id__lte=quote.id,
                accepted=True).exclude(id=quote.id).order_by('-id').first()
            next_quote = Quote.objects.filter(
                id__gte=quote.id,
                accepted=True).exclude(id=quote.id).order_by('id').first()
            if prev_quote is not None:
                prev_id = prev_quote.id
            else:
                prev_id = None
            if next_quote is not None:
                next_id = next_quote.id
            else:
                next_id = None

        except Quote.DoesNotExist:
            return Response({
                'status': 'Error',
                'message': 'Quote does not exists'
            })
        serializer = QuoteSerializer(quote)
        return Response({
            'status': 'success',
            'quote': serializer.data,
            'next': next_id,
            'prev': prev_id
        })
Exemplo n.º 19
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        userId = serializer.validated_data['sourceContext']

        # JSONWebTokenAuthentication assumes that the JWT will come in the header

        obj = JSONWebTokenAuthentication()
        try:
            user, jwt_value = obj.authenticate(request)
        except TypeError:
            return Response({'errmsg': '请携带参数访问'},
                            status=status.HTTP_400_BAD_REQUEST)

        # 验证用户身份,把控视频上传权限

        user_auth = authenticate(username=user.username, password=userId)

        if user_auth:
            videoSize = serializer.validated_data['videoSize']
            # "procedure": "QCVB_SimpleProcessFile(1,0,10)",
            currentTimeStamp = int(time.time())
            params = {
                "secretId": qcloud_options['SecretID'],
                "currentTimeStamp": currentTimeStamp,
                "expireTime": currentTimeStamp + 600,
                "random": get_random_string(8, '0123456789'),
                "sourceContext": user.username,
                "procedure": "QCVB_SimpleProcessFile(0,0,10)",
                "videoSize": videoSize
            }

            urlcode = urlencode(params).encode()
            mac = hmac.new(qcloud_options['SecretKey'].encode(), urlcode,
                           hashlib.sha1).digest()

            return Response({"signature": base64.b64encode(mac + urlcode)})
        else:
            return Response({'errmsg': "不存在此用户"},
                            status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 20
0
def get_user_jwt(request):
    """
    Приоритет, если есть пользователь в JWT - вытаскиваем его.
    :param request:
    :return:
    """
    auth = JSONWebTokenAuthentication()
    try:
        jwt_value = auth.get_jwt_value(request)
        if jwt_value:
            user_jwt = auth.authenticate(Request(request))
            if user_jwt is not None:
                return user_jwt[0]
    except AuthenticationFailed:
        # Тут был jwt токен
        return AnonymousUser()

    user = get_user(request)
    if user.is_authenticated():
        return user
    return AnonymousUser()
Exemplo n.º 21
0
    def get(self, request, format=None):

        # Create the instance of JSONWebTokenAuthentication to do the authentication job
        authentication = JSONWebTokenAuthentication()

        # try:
        '''
        authentication.authenticate 会抛出异常,所以添加异常捕获
        '''
        auth_data = authentication.authenticate(request)
        if auth_data is None:
            raise exceptions.NotAuthenticated()
        '''
        auth_data type is tuple, first is user instance, the second is jwt value.
        So I serializer the investor attribute of the first argument.
        '''
        serializer = self.get_serializer(auth_data[0].investor)
        '''
        Response the data
        '''
        return Response(serializer.data)
Exemplo n.º 22
0
    def create(self, request, *args, **kwargs):
        # Create the instance of JSONWebTokenAuthentication to do the authentication job
        authentication = JSONWebTokenAuthentication()

        # try:
        '''
        authentication.authenticate 会抛出异常,所以添加异常捕获
        '''
        auth_data = authentication.authenticate(request)
        if auth_data is None:
            raise exceptions.NotAuthenticated()

        owner = auth_data[0].investor

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(owner=owner)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Exemplo n.º 23
0
    def post(self, request):
        serializer = QuoteSerializer(data=request.data)
        if serializer.is_valid():
            user = None
            try:
                auth = JSONWebTokenAuthentication()
                user = auth.authenticate(request=request)
            except AuthenticationFailed:
                pass
            if user is not None and user[0].is_superuser:
                serializer.save(accepted=True)
            else:
                token = get_random_string(length=32)
                quote = serializer.save(accepted=False,
                                        token=make_password(token))

                print(
                    request.data['text'] +
                    "\nTo accept: https://alo-quotes.tk/api/accept_with_token/"
                    + str(quote.id) + "/" + token + "\n" +
                    "To reject: https://alo-quotes.tk/api/reject_with_token/" +
                    str(quote.id) + "/" + token)

                emails_pre = list(
                    User.objects.filter(
                        is_staff=True).all().values_list('email'))
                emails = [email[0] for email in emails_pre]
                # send_mail(
                #     'New quote submitted',
                #     request.data['text']
                #     + "\nTo accept: https://alo-quotes.tk/api/accept_with_token/"
                #     + str(quote.id) + "/" + token + "\n"
                #     + "To reject: https://alo-quotes.tk/api/reject_with_token/"
                #     + str(quote.id) + "/" + token,
                #     '*****@*****.**',
                #     emails,
                #     fail_silently=False, )

            return Response({'status': 'success', 'quote': serializer.data})
        return Response({'status': 'Error', 'messages': serializer.errors})
Exemplo n.º 24
0
    def process_request(self, request):
        """ Override only the request to add the user """
        try:
            return request.user
        except AttributeError:
            pass

        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        if user_auth_tuple is not None:
            request.user, _ = user_auth_tuple

            # Set last_seen on the user record if it has been > 10 mins
            # since the record was set.
            if not request.user.last_seen or (request.user.last_seen <
               timezone.now() - timedelta(minutes=LAST_SEEN_DELTA)):
                request.user.last_seen = timezone.now()
                request.user.save()
            return
Exemplo n.º 25
0
    def process_response(self, request, response):
        """ Override only the request to add the new token """
        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        # Check if request includes valid token
        if user_auth_tuple is not None:
            user, _auth = user_auth_tuple

            # Get the payload details
            jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
            payload = jwt_decode_handler(_auth)
            logging.debug("JWT payload found: {0}".format(payload))

            # Check whether we need to renew the token. This will happen if the token
            # hasn't been renewed in JWT_TOKEN_RENEWAL_DELTA
            exp = payload.get("exp")
            created_timestamp = exp - int(api_settings.JWT_EXPIRATION_DELTA.total_seconds())
            renewal_timestamp = created_timestamp + int(settings.JWT_TOKEN_RENEWAL_DELTA.total_seconds())
            now_timestamp = timegm(datetime.utcnow().utctimetuple())

            # If it has been less than JWT_TOKEN_RENEWAL_DELTA time since the
            # token was created then we will pass on created a renewed token
            # and just return the response unchanged.
            if now_timestamp < renewal_timestamp:
                logging.debug("JWT_TOKEN_RENEWAL_DELTA not exceeded: returning response unchanged.")
                return response

            # Get and check orig_iat
            orig_iat = payload.get("orig_iat")
            if orig_iat:
                # verify expiration
                expiration_timestamp = orig_iat + int(api_settings.JWT_TOKEN_RENEWAL_LIMIT.total_seconds())
                if now_timestamp > expiration_timestamp:
                    # Token has passed renew time limit - just return existing
                    # response. We need to test this process because it is
                    # probably the case that the response has already been
                    # set to an unauthorized status
                    # now_timestamp > expiration_timestamp.
                    logging.debug("JWT token has expired: returning response unchanged.")
                    return response

            else:
                # orig_iat field is required - just return existing response
                logging.debug("JWT token orig_iat field not defined: returning response unchanged.")
                return response

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            new_payload = jwt_payload_handler(user)
            new_payload["orig_iat"] = orig_iat

            # Attach the renewed token to the response
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            response["Refresh-Token"] = "JWT {0}".format(jwt_encode_handler(new_payload))

            logging.debug("JWT token has been renewed.")

            return response

        else:
            # No authenticated user - just return existing response
            logging.debug("No JWT authenticated user: returning response unchanged.")
            return response
Exemplo n.º 26
0
    def get(self, request, format=None):
        """
        Return a list of fund
        :param request:
        :param format:
        :return:
        """
        # Create the instance of JSONWebTokenAuthentication to do the authentication job
        authentication = JSONWebTokenAuthentication()
        auth_data = authentication.authenticate(request)
        if auth_data is None:
            raise exceptions.NotAuthenticated()

        owner = auth_data[0].investor

        result = []
        # 获取当前用户的定投期初数据
        initials = Initial.objects.filter(owner=owner.id)

        for initial in initials:
            # 根据基金id & 用户 获取基金档案数据
            try:
                asset_type = AssetType.objects.get(id=initial.fund.id)
                # 本金 = 定投期初金额 + 定投累积金额
                invest_records = InvestRecord.objects.filter(fund=initial.fund.id, owner=owner.id)
                # 计算成本
                pv = 0
                cur_data_time = None
                acc_amount = 0
                for invest_record in invest_records:
                    acc_amount += invest_record.amount
                    # 查找当前市值,以定投记录中时间最近的市值为准
                    if cur_data_time is None or cur_data_time < invest_record.date_time:
                        cur_data_time = invest_record.date_time
                        pv = invest_record.pv

                principal = float('%.2f' % (initial.start_amount + acc_amount))

                # 统计历史分红总计
                dividends = Dividend.objects.filter(fund=initial.fund.id)
                dividend_amount = 0
                for dividend in dividends:
                    dividend_amount += dividend.amount

                # 收益 = (现值 + 历史分红) - 成本
                profit = float('%.2f' % (pv + dividend_amount - principal))

                # 收益率 = 利润 / 成本
                profit_rate = float('%.4f' % (profit / principal))

                # 投资时长(秒) = 当前时间(秒) - 定投开始时间(秒)
                delta_time = datetime.now().timestamp() - initial.start_time.timestamp()

                # 投资天数 = 投资时长(秒)/ (24 * 60 * 60)
                delta_days = int(delta_time / (24 * 60 * 60))
                print('👉🏻 ---> delta_days is: ', delta_days)

                # 年化收益 = 收益率 / (投资天数 / 365)
                profit_rate_annual = float('%.4f' % (profit_rate / (delta_days / 365)))

                result.append({
                    'assetType': AssetTypeSerializer(asset_type).data,  # 基金
                    'principal': principal,                             # 本金
                    'pv': pv,                                           # 市值
                    'profit': profit,                                   # 收益
                    'profitRate': profit_rate,                          # 收益率
                    'profitRateAnnual': profit_rate_annual,             # 年化收益率
                    'startTime': initial.start_time.timestamp(),        # 起始时间
                    'startAmount': initial.start_amount                 # 起始金额
                })
            except AssetType.DoesNotExist:
                pass

        return Response(result, status=status.HTTP_200_OK)
Exemplo n.º 27
0
    def get_analysis_by_user(self, request, *args, **kwargs):
        """Get all asset of the user"""
        # Create the instance of JSONWebTokenAuthentication to do the authentication job
        authentication = JSONWebTokenAuthentication()

        # try:
        '''
        authentication.authenticate 会抛出异常,所以添加异常捕获
        '''
        auth_data = authentication.authenticate(request)
        if auth_data is None:
            raise exceptions.NotAuthenticated()

        user = auth_data[0].investor

        # user_id = request.query_params['id']
        # user = get_object_or_404(Investor, pk=user_id)
        assets_queryset = user.asset_set.all()
        assets_serializer = self.get_serializer(assets_queryset, many=True)

        buckets_queryset = Bucket.objects.all()
        buckets_serializer = BucketSerializer(buckets_queryset, many=True)

        analysis_list = []
        for bucket in buckets_serializer.data:
            analysis_item = {
                'bucket': bucket,
                'assets': [],
                'amount': 0,
                'suggestAmount': 0,
                'rate': 0.5,
                'suggestRate': 0.2,
                'title': '',
                'analysis': ''
            }

            # 所有资产总额
            total_amount = 0
            for asset in assets_serializer.data:
                total_amount += asset['pv']

                # 资产和金额归类
                if asset['type']['category']['level']['code'] == bucket['code']:
                    analysis_item['assets'].append(asset)
                    analysis_item['amount'] += asset['pv']

            analysis_item['suggestRate'] = bucket['rate']
            analysis_item['suggestAmount'] = round(total_amount * analysis_item['suggestRate'], 2)
            analysis_item['rate'] = round(analysis_item['amount'] / total_amount, 3)
            analysis_item['title'] = bucket['description']

            tip = ''
            if (analysis_item['rate'] - analysis_item['suggestRate']) > 0.1:
                if (bucket['code'] == '000001') : tip = '过于保守,可能会拉低收益'
                if (bucket['code'] == '000002') : tip = '过于激进,风险过高'
                analysis_item['analysis'] = '配置比例过高,%s!' % (tip,)
            elif (analysis_item['rate'] - analysis_item['suggestRate'] < 0.1):
                if (bucket['code'] == '000001') : tip = '过于保守,可能会拉低收益'
                if (bucket['code'] == '000002') : tip = '过于激进,风险过高'
                analysis_item['analysis'] = '配置比例过低,%s!' % (tip,)
            else:
                analysis_item['analysis'] = '资产配置健康!'

            analysis_list.append(analysis_item)

        return Response(analysis_list)
Exemplo n.º 28
0
    def process_response(self, request, response):
        """ Override only the request to add the new token """
        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        # Check if request includes valid token
        if user_auth_tuple is not None:
            user, _auth = user_auth_tuple

            # Get the payload details
            jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
            payload = jwt_decode_handler(_auth)
            logging.debug('JWT payload found: {0}'.format(payload))

            # Check whether we need to renew the token. This will happen if the token
            # hasn't been renewed in JWT_TOKEN_RENEWAL_DELTA
            exp = payload.get('exp')
            created_timestamp = exp - int(
                api_settings.JWT_EXPIRATION_DELTA.total_seconds())
            renewal_timestamp = created_timestamp + int(
                settings.JWT_TOKEN_RENEWAL_DELTA.total_seconds())
            now_timestamp = timegm(datetime.utcnow().utctimetuple())

            # If it has been less than JWT_TOKEN_RENEWAL_DELTA time since the
            # token was created then we will pass on created a renewed token
            # and just return the response unchanged.
            if now_timestamp < renewal_timestamp:
                logging.debug(
                    'JWT_TOKEN_RENEWAL_DELTA not exceeded: returning response unchanged.'
                )
                return response

            # Get and check orig_iat
            orig_iat = payload.get('orig_iat')
            if orig_iat:
                # verify expiration
                expiration_timestamp = orig_iat + int(
                    api_settings.JWT_TOKEN_RENEWAL_LIMIT.total_seconds())
                if now_timestamp > expiration_timestamp:
                    # Token has passed renew time limit - just return existing
                    # response. We need to test this process because it is
                    # probably the case that the response has already been
                    # set to an unauthorized status
                    # now_timestamp > expiration_timestamp.
                    logging.debug(
                        'JWT token has expired: returning response unchanged.')
                    return response

            else:
                # orig_iat field is required - just return existing response
                logging.debug(
                    'JWT token orig_iat field not defined: returning response unchanged.'
                )
                return response

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            new_payload = jwt_payload_handler(user)
            new_payload['orig_iat'] = orig_iat

            # Attach the renewed token to the response
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            response['Refresh-Token'] = "JWT {0}".format(
                jwt_encode_handler(new_payload))

            logging.debug('JWT token has been renewed.')

            return response

        else:
            # No authenticated user - just return existing response
            logging.debug(
                'No JWT authenticated user: returning response unchanged.')
            return response
Exemplo n.º 29
0
 def get_authenticate(self, request):
     authenticator = JSONWebTokenAuthentication()
     user = authenticator.authenticate(request)
     if user:
         return user[0]
     return request.user