Пример #1
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     if authentication.JWTAuthentication().authenticate(request):
         request.user = authentication.JWTAuthentication().authenticate(
             request)[0]  # Manually authenticate the token
         if request.user.is_authenticated:
             User.objects.filter(id=request.user.id).update(
                 last_request=timezone.now())
Пример #2
0
def test_token_valid(client, create_user):
    # token is valid
    result = (
        authentication.JWTAuthentication().get_validated_token(
            create_user['tokens']['access']
            )
        )
    assert result

    # token is not valid
    pytest.raises(
        exceptions.InvalidToken, authentication.JWTAuthentication().get_validated_token,
        '123gkjhs'
    )
Пример #3
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        increment_counter()

        try:
            user = authentication.JWTAuthentication().authenticate(request)
            if user:
                request.user = user
        except rest_framework_simplejwt.exceptions.InvalidToken:
            pass
Пример #4
0
def initialize_request(request):
    """
    Returns the initial request object.
    """
    # todo: get authenticators from setting file
    return Request(request,
                   authenticators=[
                       jwt_auth.JWTAuthentication(),
                       authentication.SessionAuthentication(),
                       authentication.TokenAuthentication()
                   ])
Пример #5
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        # try to get user by jwt token
        # except get user from request
        try:
            user = authentication.JWTAuthentication().authenticate(request)[0]
        except (InvalidToken, TypeError):
            user = request.user

        if user.is_authenticated:
            user_act = models.UserActivity.objects.filter(user=user)[0]
            user_act.last_request_date = now()
            user_act.save()
Пример #6
0
def get_user_info(request):
    User = get_user_model()
    if request.method == 'GET':
        # print(dir(request))
        # 获取请求参数token的值
        token = request.headers.get('AUTHORIZATION')
        token_msg = authentication.JWTAuthentication().get_validated_token(
            token)
        user_object = authentication.JWTAuthentication().get_user(token_msg)

        data = {
            "username": user_object.username,
            "first_name": user_object.first_name,
            "last_name": user_object.last_name,
            #  "avatar":user_object.avatar,
            #  "groups":user_object.groups,
            "roles": [user_object.usertype],
            #  "introduction":user_object.introduction
        }
        re_data = {"data": data, "code": 20000, "message": "success"}
        return JsonResponse(re_data)
Пример #7
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     assert hasattr(request, "user")
     try:
         auth_res = authentication.JWTAuthentication().authenticate(request)
     except InvalidToken:
         return JsonResponse(
             {"error": "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED
         )
     if auth_res:
         request.user = auth_res[0]
     if request.user.is_authenticated:
         request.user.last_activity = timezone.now()
         request.user.save()
Пример #8
0
    def __call__(self, request):
        """
        If request is using a JWT token, sets the 'user'
        attribute of the request to the autenticated user.
        """
        try:
            auth = authentication.JWTAuthentication().authenticate(request)
            if auth:
                request.user = auth[0]
        except:
            pass

        return self.get_response(request)
Пример #9
0
    def __call__(self, request):
        # If user is not authenticated with django auth system
        try:
            # Check its JWT
            if not request.user.is_authenticated:
                request.user = authentication.JWTAuthentication().authenticate(request)
                request.user = request.user[0] if request.user else AnonymousUser()

        except exceptions.InvalidToken:
            request.user = AnonymousUser()

        response = self.get_response(request)
        return response
Пример #10
0
def get_user_info(request):

    User = get_user_model()
    if request.method == 'GET':
        print("in get")
        # print(dir(request))
        #获取请求参数token的值
        token = request.headers.get('AUTHORIZATION')
        # test=request.META.get('CONTENT-TYPE')
        # print(test)
        # print(token)

        token_msg = authentication.JWTAuthentication().get_validated_token(
            token)
        # print(token_msg)
        user_object = authentication.JWTAuthentication().get_user(token_msg)
        # # print(dir(user_a))
        # # #顶一个空数组来接收token解析后的值
        # # toke_user = []
        # # toke_user = jwt_decode_handler(token)
        # # #获得user_id
        # # user_id = toke_user["user_id"]
        # # #通过user_id查询用户信息
        # user_info = User.objects.get(pk= user_id)
        # serializer = UserSerializer(user_info)
        # User_info=UserSerializer(user_object.id).data
        # print(User_info)
        data = {
            "username": user_object.username,
            "first_name": user_object.first_name,
            "last_name": user_object.last_name,
            "avatar": user_object.avatar,
            #  "groups":user_object.groups,
            "roles": user_object.role,
            "introduction": user_object.introduction
        }
        re_data = {"data": data, "code": 20000, "message": "success"}
        return JsonResponse(re_data)
Пример #11
0
 def greeting(self, data):
     token = authentication.JWTAuthentication().get_validated_token(data['token'])
     self.user = authentication.JWTAuthentication().get_user(token)
     self.player = Player.objects.get(user=self.user, room=self.room)
     self.player.socket_channel_name = self.channel_name
     self.player.active = True
     self.player.save(update_fields=('socket_channel_name', 'active'))
     if self.room.status == Room.PENDING:
         players = Player.objects.filter(room=self.room).values('id', 'username')
         self.send_json(define_event(self.player.id, self.user.username, self.player.host))
         async_to_sync(self.channel_layer.group_send)(self.room_group_name, {
             'type': 'send_message',
             'data': greeting_event(self.room.name, self.room.password, list(players))
         })
     else:
         data = {}
         if self.room.status == Room.ANSWERING:
             tasks = PlayerTask.objects.player_for_answer(self.player)
             data = start_event(group_by(tasks, 'questions', 'userId', 'username'))
         elif self.room.status == Room.VOTING:
             tasks = PlayerTask.objects.player_for_vote(self.player)
             data = vote_event(group_by(tasks, 'answers', 'questionId', 'question'))
         self.send_json(data)
Пример #12
0
    def process_request(self, request):
        """
        Gets the current user from the request and prepares and connects a signal receiver with the user already
        attached to it.
        """
        # Initialize thread local storage
        threadlocal.auditlog = {
            "signal_duid": (self.__class__, time.time()),
            "remote_addr": request.META.get("REMOTE_ADDR"),
        }

        # In case of proxy, set 'original' address
        if request.META.get("HTTP_X_FORWARDED_FOR"):
            threadlocal.auditlog["remote_addr"] = request.META.get(
                "HTTP_X_FORWARDED_FOR").split(",")[0]

        # --------------------
        """
        This line allows the user to be saved with the log entry my manually authenticating the token
        django-audit-log can't recognize from a DRF request whether a user is authenticated or not
        so we have to make a manual call to our authenticator - JWTAuthentication.
        Since middleware runs before the request authentication done by JWTAuthentication, this
        is the quickfix I came up with.
        It's in a try catch loop because if the user authenticates the first time, the authenticate
        function would return an error since the user object doesn't exists yet.
        Related issue: https://github.com/jazzband/django-auditlog/issues/115
        """
        try:
            user = authentication.JWTAuthentication().authenticate(request)
            if user:
                request.user = user[0]
        except Exception as e:
            print(e)
        # --------------------

        # Connect signal for automatic logging
        if hasattr(request, "user") and getattr(request.user,
                                                "is_authenticated", False):
            set_actor = partial(
                self.set_actor,
                user=request.user,
                signal_duid=threadlocal.auditlog["signal_duid"],
            )
            pre_save.connect(
                set_actor,
                sender=LogEntry,
                dispatch_uid=threadlocal.auditlog["signal_duid"],
                weak=False,
            )
Пример #13
0
    def __call__(self, request):
        user = None
        auth = None

        try:
            auth = authentication.JWTAuthentication().authenticate(request)
        except InvalidToken as e:
            auth = None

        if auth:
            user = auth[0]

        if user and user.is_authenticated:
            user.last_request = timezone.now()
            user.save()
        response = self.get_response(request)
        return response
Пример #14
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user')

        # need to separately detect user when used middleware with JWT (else Anonymous User)
        try:
            auth_res = authentication.JWTAuthentication().authenticate(request)
        except InvalidToken:
            return JsonResponse({'error': 'Invalid token'},
                                status=status.HTTP_401_UNAUTHORIZED)

        if auth_res:
            request.user = auth_res[0]

        # save last_activity on each authenticated request
        if request.user.is_authenticated:
            request.user.profile.last_activity = timezone.now()
            request.user.save()
Пример #15
0
    def process_request(self, request):
        """
        Processes request
        """
        if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
            jwt_user = authentication.JWTAuthentication().authenticate(request)
            if jwt_user:
                request.user = jwt_user[0]
            if hasattr(request, 'user') and request.user.is_authenticated:
                user = request.user
            else:
                user = None

            mark_whodid = curry(self.mark_whodid, user)
            signals.pre_save.connect(
                mark_whodid,
                dispatch_uid=(self.__class__, request),
                weak=False,
            )
Пример #16
0
    def setUp(self):
        self.username = '******'
        self.password = '******'
        self.email = '*****@*****.**'
        self.credentials = {
            'username': self.username,
            'password': self.password,
            'email': self.email,
        }
        self.update_profile = '/user/edit_profile'
        self.login_url = '/login/'
        self.signup_url = '/signup/'

        self.backend = authentication.JWTAuthentication()
        self.fake_token = 'ThisTokenIsFake'
        self.fake_header = 'Bearer ' + self.fake_token

        serializer = RegisteredUserSerializer(data=self.credentials)
        if serializer.is_valid():
            self.user = serializer.save()

        self.client = Client()
Пример #17
0
    def process_view(request, view_func, view_args, view_kwargs):
        if 'Authorization' in request.headers:
            try:
                user = authentication.JWTAuthentication().authenticate(
                    request)[0]
            except InvalidToken:
                return JsonResponse(
                    {
                        "detail":
                        "Given token not valid for any token type",
                        "code":
                        "token_not_valid",
                        "messages": [{
                            "token_class": "AccessToken",
                            "token_type": "access",
                            "message": "Token is invalid or expired"
                        }]
                    },
                    status=401)

            cache.set(user.username, timezone.now())
        return None
Пример #18
0
    def setUp(self):
        self.factory = APIRequestFactory()
        self.backend = authentication.JWTAuthentication()

        self.fake_token = b'TokenMcTokenface'
        self.fake_header = b'Bearer ' + self.fake_token
Пример #19
0
def check_user_token(request):
    # if the token is not valid, an invalid token response is automatically returned
    token = authentication.JWTAuthentication().get_validated_token(request.data['token'])
    # however, if valid token, proceed to find the user
    user = authentication.JWTAuthentication().get_user(token)
    return Response({"username": user.username}, status=status.HTTP_200_OK)
Пример #20
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     try:
         request.user = authentication.JWTAuthentication().authenticate(
                                                             request)[0]
     except Exception as e:
         pass
Пример #21
0
 def profile(self, request):
     email = authentication.JWTAuthentication().authenticate(request)[0]
     user = User.objects.filter(email=email).first()
     serializer = UserDetailSerializer(user)
     return Response(serializer.data)
Пример #22
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     request.user = authentication.JWTAuthentication().authenticate(
         request)[0]