Exemple #1
0
def do_reset_password(request, token=None, password=None, inner=False):
    action_exist = UserAction.objects.filter(
        token=token, type=UserAction.ACTION_RESET_PASSWORD).exists()

    context = dict()
    context["title"] = _("Reset Password")
    if action_exist:
        action = UserAction.objects.get(token=token,
                                        type=UserAction.ACTION_RESET_PASSWORD)

        context["valid"] = True
        user = action.user

        if user.is_active:

            if inner:
                form = ResetPasswordForm(data=request.POST)
                if form.is_valid():
                    password = form.cleaned_data["password1"]
                    _change_password(request, action, password)
                    context["message"] = _(
                        "Password has been reseted successfully!.")
                    return render(request, 'credentials/message.html', context)
                else:
                    context["has_error"] = True
                    context["message"] = _("Passwords aren't match!")
                    return render(request, 'credentials/password_reset.html',
                                  context)
            else:
                _change_password(request, action, password)
                return DoneResponse(
                    detail=_("La Contraseña ha sido restaurada!."),
                    code=codes.PASSWORD_RESTORED,
                    status=status.HTTP_201_CREATED,
                )
        else:
            if inner:
                context["has_error"] = True
                context["message"] = _("This an inactive account!")
                return render(request, 'credentials/password_reset.html',
                              context)
            else:
                raise ValidationError(detail=_("Cuenta inactiva"),
                                      code=codes.INACTIVE_ACCOUNT)
    else:
        if inner:
            context["has_error"] = True
            context["message"] = _("Invalid action!")
            return render(request, 'credentials/password_reset.html', context)
        else:
            raise ValidationError(detail=_("Token de transacción invalido"),
                                  code=codes.INVALID_TRANSACTION_TOKEN)
Exemple #2
0
 def validate(self, attrs):
     user = self.context["request"].user
     if user and user.is_authenticated():
         if "password" not in attrs or not user.check_password(
                 attrs["password"]):
             raise ValidationError(
                 detail=_("La contraseña actual no es valida"),
                 code=codes.INVALID_PASSWORD)
     else:
         raise ValidationError(
             detail=_("No tiene credenciales para ejecutar esta acción"),
             code=codes.PERMISSION_DENIED)
     return attrs
Exemple #3
0
def do_cancel_confirm(request, token=None, inner=False):
    action_exist = UserAction.objects.filter(
        token=token, type=UserAction.ACTION_DISABLE_ACCOUNT).exists()

    context = dict()
    context["title"] = _("Cancel account")

    if action_exist:
        action = UserAction.objects.get(token=token,
                                        type=UserAction.ACTION_DISABLE_ACCOUNT)

        action.user.is_active = False
        action.user.save()
        if not settings:
            action.user.delete()
        action.delete()

        message = _("Tu cuenta ha sido eliminada correctamente")
        if inner:
            context["message"] = message
            return render(request, 'credentials/message.html', context)
        else:
            return DoneResponse(
                detail=message,
                status=status.HTTP_201_CREATED,
                code=codes.ACCOUNT_DISABLED,
            )
    else:
        message = _("Acción inválida")
        if inner:
            context["message"] = message
            context["error"] = True
            return render(request, 'credentials/message.html', context)
        else:
            raise ValidationError(detail=message, code=codes.INVALID_ACTION)
Exemple #4
0
def do_change_email(request, token=None, inner=False):
    action_exist = UserAction.objects.filter(
        token=token, type=UserAction.ACTION_CHANGE_EMAIL).exists()

    context = dict()
    context["title"] = _("Change email")

    if action_exist:
        action = UserAction.objects.get(token=token,
                                        type=UserAction.ACTION_CHANGE_EMAIL)
        action.user.email = action.value
        action.user.save()

        action.delete()

        if inner:
            context["message"] = _("Tu correo ha sido actualizado con éxito")
            return render(request, 'credentials/message.html', context)
        else:
            return DoneResponse(
                detail=_("Correo actualizado con exito!"),
                status=status.HTTP_201_CREATED,
                code=codes.EMAIL_UPDATED,
            )
    else:
        if inner:
            context["message"] = _("Acción Invalida!")
            context["error"] = True
            return render(request, 'credentials/message.html', context)
        else:
            raise ValidationError(detail=_("Token de transacción invalido"),
                                  code=codes.INVALID_TRANSACTION_TOKEN)
Exemple #5
0
    def token(self, request):
        """
        # Endpoint to provide access tokens to authentication flow.
        ---
        request_serializer: LoginSerializer
        response_serializer: TokenResponseSerializer
        """
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = User.objects.get(
            Q(username=serializer.data["login"])
            | Q(email=serializer.data["login"]))

        if request.content_type == 'application/x-www-form-urlencoded':
            if not request.POST._mutable:
                mutable = request.POST._mutable
                request.POST._mutable = True
                request.data["grant_type"] = "password"
                request.data["username"] = user.username
                request.POST._mutable = mutable
            else:
                request.data["grant_type"] = "password"
                request.data["username"] = user.username

            return self.get_response_token(request)
        else:
            raise ValidationError(
                detail=_("Content-Type no soportado"),
                code=codes.UNSUPPORTED_CONTENT_TYPE,
            )
Exemple #6
0
    def validate(self, attrs):
        attrs = super(LoginSerializer, self).validate(attrs)

        if not User.objects.filter(Q(username=attrs["login"]) | Q(email=attrs["login"])).exists():
            raise ValidationError(
                detail=_("Credenciales invalidas"),
                code=codes.INVALID_CREDENTIALS,
            )
        else:
            user = User.objects.get(Q(username=attrs["login"]) | Q(email=attrs["login"]))
            if not user.check_password(attrs["password"]):
                raise ValidationError(
                    detail=_("Credenciales invalidas"),
                    code=codes.INVALID_CREDENTIALS,
                )

        return attrs
Exemple #7
0
    def validate(self, attrs):
        attrs = super(RefreshTokenSerializer, self).validate(attrs)

        if not RefreshToken.objects.filter(token=attrs["refresh_token"]).exists():
            raise ValidationError(
                detail=_("Refresh Token inválido"),
                code=codes.INVALID_REFRESH_TOKEN,
            )

        return attrs
Exemple #8
0
    def validate(self, attrs):
        attrs = super(RevokeTokenSerializer, self).validate(attrs)

        if not AccessToken.objects.filter(token=attrs["token"]).exists():
            raise ValidationError(
                detail=_("Access Token inválido"),
                code=codes.INVALID_ACCESS_TOKEN,
            )

        return attrs
Exemple #9
0
 def validate(self, attrs):
     attrs = super(UserUpdateSerializer, self).validate(attrs)
     if "username" in attrs:
         if User.objects.filter(username=attrs["username"]).exists():
             raise ValidationError(
                 detail=
                 _("Este nombre de usuario está siendo utilizado por otro usuario"
                   ),
                 code=codes.USED_USERNAME,
             )
     return attrs
Exemple #10
0
    def validate(self, attrs):
        attrs = super(AppMixin, self).validate(attrs)
        if not PlatformApp.objects.filter(
                client_id=attrs["client_id"],
                client_secret=attrs["client_secret"],
        ).exists():
            raise ValidationError(
                detail=_("Aplicación invalida"),
                code=codes.INVALID_APPLICATION,
            )

        return attrs
Exemple #11
0
    def post(self, request, *args, **kwargs):
        if request.content_type == 'application/x-www-form-urlencoded':
            self.serializer = self.get_serializer(data=self.request.data)
            self.serializer.is_valid(raise_exception=True)

            exist_app = self.app_model.objects.filter(
                client_id=self.serializer.data["client_id"],
                client_secret=self.serializer.data["client_secret"]).exists()

            if exist_app:
                self.login()
                return self.get_response(request)

            else:
                raise ValidationError(detail=_("Aplicacion invalida"),
                                      code=codes.INVALID_APPLICATION)
        else:
            raise ValidationError(
                detail=_("Content-Type no soportado"),
                code=codes.UNSUPPORTED_CONTENT_TYPE,
            )
Exemple #12
0
 def revoke(self, request):
     """
     # Endpoint to provide access token to Revoke token flow.
     ---
     request_serializer: RevokeTokenSerializer
     response_serializer: TokenResponseSerializer
     """
     serializer = RevokeTokenSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     if request.content_type == 'application/x-www-form-urlencoded':
         url, headers, body, status = self.create_revocation_response(
             request)
         response = HttpResponse(content=body or '', status=status)
         return self.make_response(response, headers)
     else:
         raise ValidationError(
             detail=_("Content-Type no soportado"),
             code=codes.UNSUPPORTED_CONTENT_TYPE,
         )
Exemple #13
0
    def check_username(self, request):
        """
        # Check if an username is available
        ---
        request_serializer: UsernameSerializer
        response_serializer: FormattedResponseSerializer
        """
        serializer = UsernameSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        username = serializer.data['username']
        is_used_username = User.objects.filter(username=username).exists()

        if is_used_username:
            raise ValidationError(
                detail=_("Este Nombre de Usuario esta siendo usado"),
                code=codes.REGISTERED_USER,
            )
        else:
            return Response(
                {"detail": _("Nombre de Usuario disponible")},
                status=status.HTTP_200_OK,
            )
Exemple #14
0
    def check_email(self, request):
        """
        # Check if an email is available
        ---
        request_serializer: EmailSerializer
        response_serializer: FormattedResponseSerializer
        """
        serializer = EmailSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        email = serializer.data['email']
        is_used_email = User.objects.filter(email=email).exists()

        if is_used_email:
            raise ValidationError(
                detail=_("Este correo esta siendo usado por otro usuario"),
                code=codes.REGISTERED_USER,
            )
        else:
            return Response(
                {"detail": _("Correo Electrónico disponible")},
                status=status.HTTP_200_OK,
            )
Exemple #15
0
    def reset_password(self, request):
        """
        # Send password reset token to user by username or email.
        ---
        request_serializer: EmailOrUsernameSerializer
        response_serializer: FormattedResponseSerializer
        """
        serializer = EmailOrUsernameSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        eou = serializer.data['email_or_username']
        user = User.objects.get(Q(username=eou) | Q(email=eou))

        if user.is_active:
            action_exist = UserAction.objects.filter(
                user=user, type=UserAction.ACTION_RESET_PASSWORD).exists()
            if action_exist:
                action = UserAction.objects.get(
                    user=user, type=UserAction.ACTION_RESET_PASSWORD)
            else:
                action = UserAction(user=user,
                                    type=UserAction.ACTION_RESET_PASSWORD)
            action.token = get_uuid()
            action.creation_date, action.expiration_date = get_lapse()
            action.save()
            messaging.send_reset_password(request, action)
            return Response(
                {
                    "detail":
                    _("Se ha enviado un correo para restaurar contraseña")
                },
                status=status.HTTP_201_CREATED,
            )
        else:
            raise ValidationError(
                detail=_("La cuenta de este usuario esta inactiva"),
                code=codes.INACTIVE_ACCOUNT,
            )
Exemple #16
0
def do_confirm_register(request, token=None, inner=False):
    action_exist = UserAction.objects.filter(
        token=token, type=UserAction.ACTION_ENABLE_ACCOUNT).exists()

    context = dict()
    context["title"] = _("Confirmación de Cuenta")

    if action_exist:
        action = UserAction.objects.get(token=token,
                                        type=UserAction.ACTION_ENABLE_ACCOUNT)

        user = action.user
        user.is_active = True
        user.save()

        messaging.send_welcome(request, action)
        action.delete()

        if inner:
            context["message"] = _("Tu cuenta ha sido activada exitosamente.")
            return render(request, 'credentials/message.html', context)

        else:
            return DoneResponse(
                detail=_("La cuenta ha sido activada!"),
                code=codes.ACCOUNT_IS_ACTIVATED,
                status=status.HTTP_201_CREATED,
            )
    else:
        if inner:
            context["message"] = _(
                "Esta Cuenta es inválida o ya fué activada.")
            context["error"] = True
            return render(request, 'credentials/message.html', context)
        else:
            raise ValidationError(detail=_("Token de transacción invalido"),
                                  code=codes.INVALID_TRANSACTION_TOKEN)
Exemple #17
0
    def refresh(self, request):
        """
        # Endpoint to provide access token to Refresh token flow.
        ---
        request_serializer: RefreshTokenSerializer
        response_serializer: TokenResponseSerializer
        """
        serializer = RefreshTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if request.content_type == 'application/x-www-form-urlencoded':
            if not request.POST._mutable:
                mutable = request.POST._mutable
                request.POST._mutable = True
                request.data["grant_type"] = "refresh_token"
                request.POST._mutable = mutable
            else:
                request.data["grant_type"] = "refresh_token"

            return self.get_response_token(request)
        else:
            raise ValidationError(
                detail=_("Content-Type no soportado"),
                code=codes.UNSUPPORTED_CONTENT_TYPE,
            )
Exemple #18
0
    def register(self, request):
        """
        # Register  a new user.

            NOTE. the 'photo' param is required only in this documentation.
        ---
        request_serializer: RegisterSerializer
        response_serializer: UserSerializer
        parameters_strategy: merge
        consumes:
            - application/json

        produces:
            - application/json
        """

        serializer = RegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        application = PlatformApp.objects.get(
            client_id=serializer.data["client_id"],
            client_secret=serializer.data["client_secret"],
        )

        #  ------------------------------------------------------------------------------
        #     ADD application perms in here
        #  ------------------------------------------------------------------------------

        _data = serializer.data.copy()
        del _data["client_id"]
        del _data["client_secret"]
        del _data["password"]

        registered, reason = self.is_user_already_registered(_data)

        if not registered:
            # Create user
            user = User(**_data)
            user.is_staff = False

            # Set activate
            user.is_active = not application.has_confirmation

            # Set password
            user.set_password(serializer.data["password"])
            user.save()

            action = UserAction(
                user=user,
                type=UserAction.ACTION_ENABLE_ACCOUNT,
            )

            action.token = get_uuid()
            action.creation_date, action.expiration_date = get_lapse()
            action.save()

            # Send email
            if application.has_confirmation:
                messaging.send_account_activation(request, action)
            else:
                messaging.send_welcome(request, action)

            user_registered_signal.send(sender=user.__class__, user=user)

            return Response(UserSerializer(user, many=False).data,
                            status=status.HTTP_201_CREATED)

        else:
            raise ValidationError(
                detail=reason,
                code=codes.REGISTERED_USER,
            )