Пример #1
0
    def post(self, request, *args, **kwargs):
        '''
          :param request: needs fields **email** & **password**
          :return:
            return the UserSerializer data (email, url, first_name,
            last_name, level, password and token)
        '''
        serializer = LDAPAuthLoginSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(data=serializer.errors,
                            status=HTTP_400_BAD_REQUEST)

        username = serializer.validated_data["username"]

        user = authenticate(
            username=username,
            password=serializer.validated_data["password"],
            from_api=True,
        )
        if user is None:
            return Response(
                data={
                    'message': 'Wrong auth credentials',
                    "_errors": ["WRONG_AUTH_CREDENTIALS"],
                },
                status=HTTP_401_UNAUTHORIZED,
            )

        user_logged_in.send(sender=get_user_model(), user=user)

        get_user_model().objects.filter(pk=user.pk).update(
            last_login=timezone.now())

        serializer = UserSerializer(instance=user,
                                    api_namespace=self.api_namespace)
        return Response(data=serializer.data, status=HTTP_200_OK)
Пример #2
0
    def post(self, request, *args, **kwargs):
        serializer = TwoFactorLoginSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(data=serializer.errors,
                            status=HTTP_400_BAD_REQUEST)

        email = serializer.validated_data["email"]

        ip = get_client_ip(request)
        now = pendulum.now('utc').format(settings.LOGGING['datefmt'])
        user = self.request.user
        base_message = f"[{now}|{ip}|{user}|AUTH] "

        try:
            user = UserModel.objects.get(email=email.lower())
        except ObjectDoesNotExist:
            log_request = (
                base_message +
                f"Connection attempt to unknown user {email} using MFA")
            logger_api_auth.info(log_request)
            return Response(
                data={
                    'message': 'Wrong auth credentials',
                    "_errors": ["WRONG_AUTH_CREDENTIALS"],
                },
                status=HTTP_401_UNAUTHORIZED,
            )
        expire_temporary_tokens(user)
        temp_token = user.temporary_tokens.filter(
            key=serializer.validated_data["token"]).first()
        if not temp_token:
            log_request = (base_message +
                           f"Invalid code when validating MFA for {email}")
            logger_api_auth.info(log_request)
            return Response(
                data={
                    'message': 'MFA temporary token invalid',
                    "_errors": ["MFA_TEMP_TOKEN_INVALID"],
                },
                status=HTTP_401_UNAUTHORIZED,
            )
        if temp_token.expired is True:
            log_request = base_message + f"MFA temporary token expired {email}"
            logger_api_auth.info(log_request)
            return Response(
                data={
                    'message': 'MFA temporary token expired',
                    "_errors": ["MFA_TEMP_TOKEN_EXPIRED"],
                },
                status=HTTP_401_UNAUTHORIZED,
            )
        email_device = user.emaildevice_set.filter(confirmed=True).first()

        verified = email_device.verify_token(
            token=serializer.validated_data["verification_code"])
        if not verified:
            log_request = (
                base_message +
                f"Connection attempt to user {email} with wrong MFA code")
            logger_api_auth.info(log_request)
            return Response(
                data={
                    'message': 'Wrong verification code',
                    "_errors": ["WRONG_VERIFICATION_CODE"],
                },
                status=HTTP_401_UNAUTHORIZED,
            )

        # Expire the token to use it only once
        temp_token.expired = True
        temp_token.save()
        serializer = UserSerializer(
            instance=user,
            api_namespace=self.api_namespace,
            context={'is_verified': True},
        )
        log_request = (
            base_message +
            f"Connection attempt to user {email} using MFA is successful")
        logger_api_auth.info(log_request)
        return Response(data=serializer.data, status=HTTP_200_OK)