Esempio n. 1
0
    def validate(self, data):
        password = data.get('password', None)
        new_password = data.get('new_password', None)
        verified_password = data.get('verified_password', None)

        user = self.context.get('request').user
        if not user.check_password(password):
            raise CustomAPIException('Your current password is incorrect.')

        if new_password != verified_password:
            raise CustomAPIException('Your passwords didnt match.')

        return data
Esempio n. 2
0
    def validate(self, attrs):
        license_plate = attrs.get('license_plate')
        request = self.context.get('request')
        if request.method == 'POST':
            if license_plate and Vehicle.objects.filter(
                    license_plate=license_plate).first():
                raise CustomAPIException(ErrorCode.LICENSE_PLATE)
        else:
            if self.instance.license_plate != license_plate \
                    and Vehicle.objects.filter(license_plate=license_plate).first():
                raise CustomAPIException(ErrorCode.LICENSE_PLATE)

        return attrs
 def verify_email(self, request, *args, **kwargs):
     token = request.query_params.get('code')
     user = validate_token_verify_email(token)
     if not user:
         raise CustomAPIException('verify email fail')
     handle_verify_email(user)
     return Response(data=None)
 def register_email(self, request, *args, **kwargs):
     token = generate_token_register_email(request.user)
     body = get_current_site(request).domain + '/api/account/email/verify/?code={}'.format(token)
     if not request.user.email:
         raise CustomAPIException('You do not have email information')
     send_mail_task.delay('VERIFY EMAIL', body, request.user.email)
     return Response(data=None)
def validate_token_verify_email(token):
    try:
        payload = jwt_decode_handler(token)
    except ExpiredSignatureError:
        raise CustomAPIException('Token verify email expired!')
    except DecodeError:
        raise CustomAPIException('Invalid Token!')
    except Exception:
        raise CustomAPIException('Invalid token.')

    try:
        user = User.objects.get(pk=payload.get('id'),
                                email=payload.get('email'))
    except User.DoesNotExist:
        raise CustomAPIException('Invalid token.')

    return user
Esempio n. 6
0
    def validate(self, attrs):
        attrs = super().validate(attrs)
        phone_number = attrs.get("phone_number", None)
        security_code = attrs.get("security_code", None)
        session_token = attrs.get("session_token", None)

        phone_verification_service = PhoneVerificationService()
        verification = phone_verification_service.validate_security_code(
            security_code, phone_number, session_token)

        if verification == phone_verification_service.SECURITY_CODE_INVALID:
            raise CustomAPIException('Security code is not valid')
        elif verification == phone_verification_service.SESSION_TOKEN_INVALID:
            raise CustomAPIException('Session token is not valid')
        elif verification == phone_verification_service.SECURITY_CODE_EXPIRED:
            raise CustomAPIException('Security code has expired')
        elif verification == phone_verification_service.SECURITY_CODE_VERIFIED:
            raise CustomAPIException('Security code is already verified')

        return attrs
    def validate(self, data):
        username = data.get('username', None)
        password = data.get('password', None)

        if not username or not password:
            raise serializers.ValidationError(
                'password and username field required')

        user = authenticate(username=username, password=password)
        if not user:
            raise CustomAPIException(ErrorCode.LOGIN_FAIL)
        return user
    def login(self, request):
        """Authenticate user through the provider and access_token"""
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        provider = serializer.data.get('provider', None)
        strategy = load_strategy(request)
        try:
            backend = load_backend(strategy=strategy,
                                   name=provider,
                                   redirect_uri=None)
        except MissingBackend:
            raise CustomAPIException(
                messenger='Please provide a valid provider')

        try:
            access_token = None
            if isinstance(backend, BaseOAuth2):
                access_token = serializer.data.get('access_token')
            user = backend.do_auth(access_token)
        except HTTPError:
            raise CustomAPIException('Invalid token')
        except AuthTokenError:
            raise CustomAPIException('Invalid credentials')

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        data = {"email": user.email, "username": user.username, "token": token}
        response = Response(data=data)
        if api_settings.JWT_AUTH_COOKIE:
            expiration = (datetime.datetime.utcnow() +
                          api_settings.JWT_EXPIRATION_DELTA)
            response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                token,
                                expires=expiration,
                                httponly=True)
        return response
Esempio n. 9
0
    def import_xlsx(self, request):
        excel_file = request.FILES["file"]
        try:
            wb = openpyxl.load_workbook(excel_file)
        except BadZipFile:
            raise CustomAPIException(**ErrorCode.FORMAT_FILE)

        excel_data = list()
        for worksheet in wb:
            for row in worksheet.iter_rows():
                row_data = list()
                for cell in row:
                    row_data.append(str(cell.value))
                excel_data.append(row_data)

        return Response(data=excel_data)