def get_user_jwt(request): # noqa: C901 """ Replacement for django session auth get_user & auth.get_user JSON Web Token authentication. Inspects the token for the user_id, attempts to get that user from the DB & assigns the user on the request object. Otherwise it defaults to AnonymousUser. This will work with existing decorators like LoginRequired ;) Returns: instance of user object or AnonymousUser object """ user = None drf_request = Request(request) try: # First try header based authentication user_jwt = JSONWebTokenAuthentication().authenticate(drf_request) # If still not found user, then try query param based authentication if # applicable as per view config if user_jwt is None: user_jwt = JSONWebTokenAuthenticationFromQueryParam().authenticate( drf_request) if user_jwt is not None: jwt_token = user_jwt[1] try: verify_and_decode_auth_token(jwt_token) # store the first part from the tuple (user, obj) user = user_jwt[0] except InvalidTokenType: pass except Exception: pass return user or AnonymousUser()
class CreateContactMessage(APIView): auth = JSONWebTokenAuthentication() mailer = AdminContactMessageMailer() def post(self, request): ''' :param request: :raise MailException :return: Request ''' request_data = request.data data = self.auth.authenticate(request) if not data: return Response({'errors': "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED) username = data[0] user = User.objects.get(username=username) serializer_context = {'author': user} serializer = CreateContactMessageSerializer(data=request_data, context=serializer_context) serializer.is_valid() if (serializer.errors): return Response({"errors": serializer.errors}, status.HTTP_400_BAD_REQUEST) contact_message = serializer.save() self.mailer.send(contact_message) return Response(serializer.data, status=status.HTTP_201_CREATED)
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)
def __call__(self, request): if not request.user.is_authenticated: # adminsite user user = None user_jwt = request.META.get('HTTP_AUTHORIZATION', '').split() if len(user_jwt) == 2 and user_jwt[0].lower() == 'jwt': # token presente try: user = JSONWebTokenAuthentication().authenticate( Request(request))[0] except Exception as err: return JsonResponse( { 'errors': [{ 'message': err.detail, 'status': err.status_code }] }, status=err.status_code) # controllo se l'utente si è autenticato if user is not None: request.user = user else: request.user = AnonymousUser() response = self.get_response(request) return response
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
def process_request(self, request): aa = request.COOKIES.get('token') if '/system/user/login/' == request.path: self.first = True return None elif '/common/download/' == request.path: return None elif '/system/user/getCode/' == request.path: if not self.first: return None elif self.first and not aa: response = JsonResponse({'code': 401}) response.status_code = 200 return response else: user_jwt = JSONWebTokenAuthentication().authenticate( Request(request)) if user_jwt is not None: user = user_jwt[0] request.user = user return None response = JsonResponse({'detail': 'Permission denied'}) response.status_code = 403 return response
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
def get_user_jwt_or_oauth2(request): user = get_user(request) if user.is_authenticated(): return user # JWT try: from rest_framework_jwt.authentication import JSONWebTokenAuthentication try: user_jwt = JSONWebTokenAuthentication().authenticate( Request(request)) if user_jwt is not None: return user_jwt[0] except: pass except ModuleNotFoundError: pass # OAuth2 try: from oauth2_provider.contrib.rest_framework import OAuth2Authentication try: user_o2 = OAuth2Authentication().authenticate(request) if user_o2 is not None: return user_o2[0] except: pass except ModuleNotFoundError: pass return user
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' })
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) return user
def get_serializer(self, *args, **kwargs): if 'data' in kwargs and 'token' not in kwargs['data']: authorizer = JSONWebTokenAuthentication() jwt_value = authorizer.get_jwt_value(self.request) if jwt_value is not None and len(jwt_value) > 0: kwargs['data']['token'] = jwt_value.decode('utf-8') serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs)
def get_authenticators(self): try: from rest_framework_jwt.authentication import JSONWebTokenAuthentication except ImportError: warnings.warn('djangorestframework-jwt must be installed for JWT authentication', ImportWarning) raise return [JSONWebTokenAuthentication()]
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
def __call__(self, request): try: auth = JSONWebTokenAuthentication().authenticate(request) if auth: request.user = auth[0] except exceptions.AuthenticationFailed: pass response = self.get_response(request) return response
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
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
def perform_create(self, serializer): (user, token) = JSONWebTokenAuthentication().authenticate(self.request) serializer.save( user=user, species=self.request.data.get('species'), area=self.request.data.get('area'), scale=self.request.data.get('scale'), phone=self.request.data.get('phone'), ) logger.debug('User Info Upload')
def get_user_jwt(request): user = None try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: user = user_jwt[0] except Exception as e: raise e return user or AnonymousUser()
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
def get_request_user(request): try: auth = JSONWebTokenAuthentication().authenticate(request) except exceptions.AuthenticationFailed: return None if auth is None: return None else: return auth[0]
def middleware(request): try: user_jwt = JSONWebTokenAuthentication().authenticate( Request(request)) user = user_jwt[0] andela_user_profile = AndelaUserProfile.objects.get(user=user) request.user = andela_user_profile except Exception: pass return get_response(request)
def get_user_jwt(request): user = None try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: # store the first part from the tuple (user, obj) user = user_jwt[0] except Exception as _: logger.exception('jwt exception') return user or AnonymousUser()
def get_user_from_jwt_value(jwt_value): try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) return JSONWebTokenAuthentication().authenticate_credentials(payload)
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_user_jwt(request): user = get_user(request) if user.is_authenticated(): return user try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: return user_jwt[0] except: pass return user
def get_user_jwt(request): try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) # print "user_jwt: ", user_jwt if user_jwt is not None: return user_jwt[0], user_jwt[1] else: return None, None except Exception, e: print "exception", e pass
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_user_jwt(request): user = get_user(request) if user.is_authenticated: return user try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: request.csrf_processing_done = True return user_jwt[0] except Exception: pass return user
def process_request(self, request): while_url_list = Url.objects.filter(user_type='anonymous').values_list( 'url', flat=True) for url in while_url_list: if re.match(url, request.path_info): return None user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: user = user_jwt[0] request.user = user return None response = JsonResponse({'detail': 'Permission denied'}) response.status_code = 403 return response
def process_request(self, request): if '/media' in request.path_info: jwt_auth = JSONWebTokenAuthentication() jwt_token = jwt_auth.get_jwt_value(request) if jwt_token: user_details = jwt_decode_handler(jwt_token) if user_details: request.user = User.objects.get( username=user_details['username']) logger.info( "[User-{0}-id-{1}] authenticated for media file {2}".format( request.user.username, request.user.id, request.path_info ))