def check_field_name(self, field_name: str) -> str:
     """Checks to see if field_name is actually a field on the model."""
     # only when related_name is set on field, the field becomes a key on
     # model, otherwise it becomes fieldname_set
     if not hasattr(self.model, field_name):
         raise e.ValidationError({
             "error":
             f'"{field_name}" is not a property name on {self.model.__name__}'
         })
     target_field = self.get_model_field(field_name)
     if (target_field and isinstance(
             target_field,
         (
             ManyToManyRel,
             ManyToManyField,
             ManyToOneRel,
             ForeignKey,
         ),
     ) and isinstance(
             getattr(self.model, field_name, None),
         (
             related_descriptors.ForwardManyToOneDescriptor,
             related_descriptors.ForwardOneToOneDescriptor,
             related_descriptors.ReverseOneToOneDescriptor,
             related_descriptors.ReverseManyToOneDescriptor,
             related_descriptors.ManyToManyDescriptor,
         ),
     )):
         return field_name
     else:
         raise e.ValidationError(
             f"Property {field_name} on {self.model.__name__} is not a valid relation."
         )
Beispiel #2
0
        def validate(self, attr):
            vc = m.VerificationCode.filter_unexpired(
                text=attr["verification_code"],
                email__address=attr["new_email_address"],
                action=m.VerificationCode.Action.VERIFY_EMAIL,
            )

            # check verification code
            if vc.exists():
                attr.update({"verification_code": vc})
            else:
                raise e.ValidationError(
                    dict(verification_code=_("Incorrect validation code")))
            """
            Verification code must be validated before password
            """
            # if user has password set, then password is required
            if self.instance.has_usable_password():
                if "password" not in attr:
                    raise e.ValidationError(
                        dict(password="******"))
                elif not self.instance.check_password(attr["password"]):
                    raise e.ValidationError(
                        dict(password="******"))

            return attr
Beispiel #3
0
        def validate(self, attr):
            user = self.instance
            verification_code = m.VerificationCode.filter_unexpired(
                mobile__user=user,
                action=m.VerificationCode.Action.DISABLE_ACCOUNT,
                text=attr["verification_code"],
            ).first()
            if not verification_code:
                verification_code = m.VerificationCode.filter_unexpired(
                    email__user=user,
                    action=m.VerificationCode.Action.DISABLE_ACCOUNT,
                    text=attr["verification_code"],
                ).first()
            if not verification_code:
                raise e.ValidationError(
                    dict(verification_code="Incorrect verification code."))

            attr.update({"verification_code": verification_code})

            if user.has_usable_password():
                password = attr.get("password", None)
                if not user.check_password(password):
                    raise e.ValidationError(
                        dict(password="******"))

            return attr
Beispiel #4
0
 def validate(self, attr):
     if attr["new_password"] != attr["new_password_again"]:
         raise e.ValidationError(
             dict(new_password_again=_(
                 "Password was inconsistent. Make sure you type the same password again."
             )))
     return attr
Beispiel #5
0
 def validate_verification_code(self, verification_code):
     vc = m.VerificationCode.filter_unexpired(
         text=verification_code,
         action=m.VerificationCode.Action.CHANGE_PASSWORD)
     if vc.exists():
         return vc
     else:
         raise e.ValidationError(
             dict(verification_code=_("Incorrect validation code")))
Beispiel #6
0
 def validate_new_email_address(self, new_email_address):
     email = m.Email.objects.filter(address=new_email_address).first()
     if email and email.verified:
         LOG.debug(f"conflig user {self.instance}, {email.user}")
         raise e.ValidationError(
             dict(new_email_address=_(
                 f'The email address "{new_email_address}" is used by another account.'
                 " Please first permanently disable that account.")))
     else:
         return new_email_address
Beispiel #7
0
 def delete(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
     if not p.has_perms_shortcut(self.user_object, self.model_object, "d"):
         raise APIPermissionDenied(self.model_object, "d")
     try:
         serializer = self.get_serializer(self.model_object, data=self.request_data)
         if hasattr(serializer, "delete_obj"):
             serializer.delete_obj()
         else:
             self.model_object.delete()
     except ProtectedError as excpt:
         raise e.ValidationError(str(excpt))
     else:
         return Response(status=204)
Beispiel #8
0
        def validate(self, attr):
            mobile = m.Mobile.objects.filter(
                country_code=attr["new_country_code"],
                number=attr["new_mobile_number"]).first()
            if mobile:
                if mobile.verified:
                    raise e.ValidationError(
                        dict(new_mobile_number=_(
                            "This mobile number is used by another account."
                            " Please first permanently disable that account."))
                    )

            # check verification code
            vc = m.VerificationCode.filter_unexpired(
                text=attr["verification_code"],
                mobile__country_code=attr["new_country_code"],
                mobile__number=attr["new_mobile_number"],
                action=m.VerificationCode.Action.VERIFY_MOBILE,
            )
            if vc.exists():
                attr.update({"verification_code": vc})
            else:
                raise e.ValidationError(
                    dict(verification_code=_("Incorrect validation code")))
            """
            Verification code must be validated before password
            """
            # if user has password set, then password is required
            if self.instance.has_usable_password():
                if "password" not in attr:
                    raise e.ValidationError(
                        dict(password="******"))
                elif not self.instance.check_password(attr["password"]):
                    raise e.ValidationError(
                        dict(password="******"))

            return attr
    def post(self, request):
        ser = self.Serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        id_token = ser.validated_data["id_token"]
        try:
            # Specify the CLIENT_ID of the app that accesses the backend:
            idinfo = verify_oauth2_token(id_token, requests.Request(),
                                         secrets.GOOGLE_SIGNIN_CLIENT_ID)

            # Or, if multiple clients access the backend server:
            # idinfo = id_token.verify_oauth2_token(token, requests.Request())
            # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
            #     raise ValueError('Could not verify audience.')

            if idinfo["iss"] not in [
                    "accounts.google.com",
                    "https://accounts.google.com",
            ]:
                raise ValueError("Wrong issuer.")

            # If auth request is from a G Suite domain:
            # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
            #     raise ValueError('Wrong hosted domain.')

            # ID token is valid. Get the user's Google Account ID from the decoded token.
            LOGGER.debug(f"login as {idinfo=}")
            email_address = idinfo.get("email", None)
            email, _created_email = m.Email.objects.get_or_create(
                address=email_address, )
            user, _created = m.User.objects.update_or_create(
                email=email,
                defaults={
                    "first_name": idinfo.get("family_name", ""),
                    "last_name": idinfo.get("given_name", ""),
                },
            )
            if user.is_active:
                auth.login(request, user)
            else:
                raise e.ValidationError(
                    dict(email_address=_(
                        f"The account {email.address} has been disabled.")))
        except ValueError:
            return Response({"success": False})
        else:
            return Response({
                "success": True,
                "user": s.UserSerializer(instance=user).data
            })
 def delete(self, request: HttpRequest, *args: Any,
            **kwargs: Any) -> HttpResponse:
     """Handles DELETE request."""
     self.check_3way_permissions(
         self.user_object,
         self.model_object,
         self.field_name,
         new_vals=self.__field_val_queryset.difference(
             self.__body_pk_queryset),
         perms="w",
     )
     if not hasattr(self.field_val, "remove"):
         raise e.ValidationError(
             f"Cannot remove {self.field_name} from {self.model.__name__} due to non-null constraints."
         )
     # silently ignore invalid pks
     selected_products = self.field_model.objects.filter(
         id__in=self.__body_pk_ls).intersection(self.field_val.all())
     self.field_val.remove(*selected_products)
     return self.__return_get_result_if_permitted(request, *args, **kwargs)