Exemple #1
0
    def obj_create(self, bundle, **kwargs):
        story_id = kwargs.get('story_id')
        asset_id = kwargs.get('asset_id')

        if asset_id:
            try:
                asset = Asset.objects.get(asset_id=asset_id) 
                if not asset.has_perm(bundle.request.user, 'change'):
                    raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the asset matching the provided asset ID"))
            except ObjectDoesNotExist:
                raise ImmediateHttpResponse(response=http.HttpNotFound("An asset matching the provided asset ID could not be found"))
        elif story_id:
            try:
                story = Story.objects.get(story_id=story_id) 
                if not story.has_perm(bundle.request.user, 'change'):
                    raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the story matching the provided story ID"))
            except ObjectDoesNotExist:
                raise ImmediateHttpResponse(response=http.HttpNotFound("A story matching the provided story ID could not be found"))

        # Set the asset's owner to the request's user
        if bundle.request.user:
            kwargs['owner'] = bundle.request.user

        # Let the superclass create the object
        bundle = super(DataSetResource, self).obj_create(
            bundle, **kwargs)

        if asset_id:
            asset.datasets.add(bundle.obj)
        elif story_id:
            # Associate the newly created dataset with the story
            story.datasets.add(bundle.obj)

        return bundle
Exemple #2
0
    def delete_related_detail(self, request, **kwargs):
        bundle = Bundle(request=request)
        dataset_id = kwargs.get('dataset_id')
        story_id = kwargs.pop('story_id', None)
        asset_id = kwargs.pop('asset_id', None)

        if asset_id:
            try:
                asset = Asset.objects.get(asset_id=asset_id) 
                if not asset.has_perm(bundle.request.user, 'change'):
                    raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the asset matching the provided asset ID"))
            except ObjectDoesNotExist:
                raise ImmediateHttpResponse(response=http.HttpNotFound("An asset matching the provided asset ID could not be found"))
        elif story_id:
            try:
                story = Story.objects.get(story_id=story_id) 
                if not story.has_perm(bundle.request.user, 'change'):
                    raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the story matching the provided story ID"))
            except ObjectDoesNotExist:
                raise ImmediateHttpResponse(response=http.HttpNotFound("A story matching the provided story ID could not be found"))

        self.obj_get(bundle, dataset_id=dataset_id)

        if asset_id:
            asset.datasets.remove(bundle.obj)
        elif story_id:
            story.datasets.remove(bundle.obj)

        return http.HttpNoContent()
Exemple #3
0
    def login_help(self, request, **kwargs):
        """
        Set the status of the "show_login_help" flag.
        """
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        if 'pk' in kwargs:
            get_id = int(kwargs['pk'])
        else:
            get_id = int(request.GET.get('id', ''))

        # CHECK AUTHORIZATION
        if request and not request.user.is_superuser and get_id != request.user.id:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        deserialized = self.deserialize(request,
                                        request.raw_post_data,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_list_data(request, deserialized)

        if not 'show_login_help' in deserialized:
            raise BadRequest(_("Invalid data sent."))

        user = UserProxy.objects.get(id=get_id)
        profile = user.get_profile()

        profile.show_login_help = deserialized['show_login_help']
        profile.save()

        return self.create_response(request, {},
                                    response_class=http.HttpAccepted)
Exemple #4
0
    def obj_update(self, bundle, **kwargs):
        draw_id = kwargs['pk']
        try:
            draw = self._client.retrieve_draw(draw_id)
        except mongodb.MongoDriver.NotFoundError:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest("Draw not found"))
        if not draw.check_write_access(bundle.request.user):
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpUnauthorized("Only the owner can update"))

        for name, value in bundle.data.items():
            if not hasattr(draw, name):
                continue
            elif name in self.FROZEN_ATTRIBUTES + self.FORBIDDEN_ATTRIBUTES:
                if getattr(draw, name) != value:
                    raise exceptions.ImmediateHttpResponse(
                        response=http.HttpBadRequest("{0} is forbidden".format(
                            name)))
            else:
                setattr(draw, name, value)

        try:
            draw.validate()
        except bom.InvalidDraw as e:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest(e.serialize()))

        draw.add_audit("DRAW_PARAMETERS")
        self._client.save_draw(draw)
        bundle.obj = draw
        return bundle
Exemple #5
0
        def post(self, request, params=None, **kwargs):
            user = authenticate(username=params.username,
                                password=params.password)
            if user is None:
                return http.HttpUnauthorized('Invalid credentials')

            return self._construct_login_response(user)
    def dismiss_all(self, request, **kwargs):
        if (request.method != "PUT") or (not request.user.is_authenticated()):
            return http.HttpUnauthorized()

        Command.objects.filter(dismissed=False, complete=True).update(dismissed=True)

        return http.HttpNoContent()
Exemple #7
0
    def obj_create(self, bundle, request=None, **kwargs):
        story_id = kwargs.get('story_id')
        if story_id:
            try:
                story = Story.objects.get(story_id=story_id)
                if not story.has_perm(request.user, 'change'):
                    raise ImmediateHttpResponse(response=http.HttpUnauthorized(
                        "You are not authorized to change the story matching the provided story ID"
                    ))
            except ObjectDoesNotExist:
                raise ImmediateHttpResponse(response=http.HttpNotFound(
                    "A story matching the provided story ID could not be found"
                ))

        # Set the asset's owner to the request's user
        if request.user:
            kwargs['owner'] = request.user

        # Let the superclass create the object
        bundle = super(LocationResource,
                       self).obj_create(bundle, request, **kwargs)

        if story_id:
            # Associate the newly created object with the story
            story.locations.add(bundle.obj)
            story.save()

        return bundle
Exemple #8
0
 def discover_method(self, request=None, **kwargs):
     content = {}
     # Deduces request from bundle
     if request is None and "bundle" in kwargs:
         request = kwargs["bundle"].request
     # Refresh syntax cache at each request
     if hasattr(self, "syntax"): delattr(self, "syntax")
     # Get the current topic
     self.topic = self.get_topic_or_404(request=request)
     # Create a search instance
     self.search = Search(topic=self.topic)
     # Check for an optional method to do further dehydration.
     method = getattr(self, "summary_%s" % kwargs["pk"], None)
     if method:
         try:
             self.throttle_check(request)
             content = method(kwargs["bundle"], request)
             if isinstance(content, HttpResponse):
                 response = content
             else:
                 # Create an HTTP response
                 response = self.create_response(data=content,
                                                 request=request)
         except ForbiddenError as e:
             response = http.HttpForbidden(e)
         except UnauthorizedError as e:
             response = http.HttpUnauthorized(e)
     else:
         # Stop here, unkown summary type
         raise Http404("Sorry, not implemented yet!")
     # We force tastypie to render the response directly
     raise ImmediateHttpResponse(response=response)
Exemple #9
0
    def obj_update(self, bundle, request=None, **kwargs):

        if request is not None and \
           self.obj_get(pk=kwargs.get("pk")).user_id != request.user.pk:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        return super(DocumentResource, self).obj_update(bundle, request, **kwargs)
Exemple #10
0
    def upload(self, request, **kwargs):
        data = self.deserialize(request,
                                request.body,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))
        file_contents = base64.b64decode(data['uploaded_file'])
        filename = data['filename']
        content_type = data['content_type']
        author = request.user if not request.user.is_anonymous() else None

        try:
            swiftfile = SwiftFile.upload_file(file_contents=file_contents,
                                              filename=filename,
                                              content_type=content_type,
                                              author=author)
        except swiftclient.ClientException:
            return http.HttpUnauthorized(
                "You are not authorized in stackswift service, \
				please, make sure that you add your username and key to your settings")

        bundle = SwiftFileResource().build_bundle(obj=swiftfile,
                                                  request=request)
        bundle = SwiftFileResource().full_dehydrate(bundle)

        return self.create_response(request, {'file': bundle},
                                    response_class=http.HttpAccepted)
Exemple #11
0
    def obj_create(self, bundle, request, **kwargs):
        with statsd.timer('auth.browserid.verify'):
            profile, msg = browserid_authenticate(
                request,
                bundle.data['assertion'],
                browserid_audience=bundle.data['audience'],
                is_native=bundle.data.get('is_native', False))
        if profile is None:
            log.info('No profile')
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        request.user, request.amo_user = profile.user, profile
        request.groups = profile.groups.all()

        # TODO: move this to the signal.
        profile.log_login_attempt(True)
        user_logged_in.send(sender=profile.user.__class__,
                            request=request,
                            user=profile.user)
        bundle.data = {
            'error': None,
            'token': self.get_token(request.user.email),
            'settings': {
                'display_name': request.amo_user.display_name,
                'email': request.user.email,
            }
        }
        bundle.data.update(PermissionResource().dehydrate(
            Bundle(request=request)).data)
        return bundle
    def create(self, request=None, **kwargs):
        """POST method of DialCallback API"""
        logger.debug('DialCallback API authentication called!')
        auth_result = self._meta.authentication.is_authenticated(request)
        if not auth_result is True:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        logger.debug('DialCallback API authorization called!')
        auth_result = self._meta.authorization.is_authorized(request, object)

        logger.debug('DialCallback API validation called!')
        errors = self._meta.validation.is_valid(request)

        if not errors:
            logger.debug('DialCallback API get called!')
            opt_aleg_uuid = request.POST.get('DialALegUUID')
            opt_dial_bleg_uuid = request.POST.get('DialBLegUUID')
            opt_dial_bleg_status = request.POST.get('DialBLegStatus')
            #We are just analyzing the hangup
            if opt_dial_bleg_status != 'hangup':
                object_list = [{'result': 'OK - Bleg status is not Hangup'}]
                logger.debug('DialCallback API : Result 200!')
                obj = CustomXmlEmitter()
                return self.create_response(request,
                                            obj.render(request, object_list))
            callrequest = Callrequest.objects.get(aleg_uuid=opt_aleg_uuid)
            data = {}
            for element in CDR_VARIABLES:
                if not request.POST.get('variable_%s' % element):
                    data[element] = None
                else:
                    data[element] = request.POST.get('variable_%s' % element)

            from_plivo = request.POST.get('From')
            to_plivo = request.POST.get('To')

            create_voipcall(obj_callrequest=callrequest,
                            plivo_request_uuid=callrequest.request_uuid,
                            data=data,
                            data_prefix='',
                            leg='b',
                            from_plivo=from_plivo,
                            to_plivo=to_plivo)
            object_list = [{'result': 'OK'}]
            logger.debug('DialCallback API : Result 200!')
            obj = CustomXmlEmitter()

            return self.create_response(request,
                                        obj.render(request, object_list))
        else:
            if len(errors):
                if request:
                    desired_format = self.determine_format(request)
                else:
                    desired_format = self._meta.default_format

                serialized = self.serialize(request, errors, desired_format)
                response = http.HttpBadRequest(content=serialized,
                                               content_type=desired_format)
                raise ImmediateHttpResponse(response=response)
Exemple #13
0
    def build_filters(self, filters=None):
        """
        If `addon__exact` is a filter and its value cannot be coerced into an
        int, assume that it's a slug lookup.

        Run the query necessary to determine the app, and substitute the slug
        with the PK in the filter so tastypie will continue doing its thing.
        """
        built = super(RatingResource, self).build_filters(filters)
        if 'addon__exact' in built:
            try:
                int(built['addon__exact'])
            except ValueError:
                app = self.get_app(built['addon__exact'])
                if app:
                    built['addon__exact'] = str(app.pk)

        if built.get('user__exact', None) == 'mine':
            # This is a cheat. Would prefer /mine/ in the URL.
            user = get_user()
            if not user:
                # You must be logged in to use "mine".
                raise ImmediateHttpResponse(response=http.HttpUnauthorized())

            built['user__exact'] = user.pk
        return built
Exemple #14
0
  def is_authenticated_apikey_only(self, request):
    auth_result = ApiKeyTokenAuthentication(require_user=False).is_authenticated(request)

    if isinstance(auth_result, HttpResponse):
      raise ImmediateHttpResponse(response=auth_result)

    if not auth_result is True:
      raise ImmediateHttpResponse(response=http.HttpUnauthorized())
Exemple #15
0
 def apply_filters(self, request, applicable_filters):
     qs = super(OwnedResource, self).apply_filters(request,
                                                   applicable_filters)
     try:
         qs = qs.for_user(request.user)
     except NotAuthenticatedError as e:
         raise exceptions.ImmediateHttpResponse(http.HttpUnauthorized(e))
     return qs
    def dismiss_all(self, request, **kwargs):
        if (request.method != 'PUT') or (not request.user.is_authenticated()):
            return http.HttpUnauthorized()

        AlertState.objects.filter(dismissed=False).exclude(
            active=True, severity__in=[40, 30]).update(dismissed=True)

        return http.HttpNoContent()
Exemple #17
0
    def is_authorized(self, request, object=None):

        if request.method == "GET":
            return True

        if request.user.is_anonymous():
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        return True
Exemple #18
0
 def apply_authorization_limits(self, request, object_list):
     if request is not None and request.method in ['PUT', 'PATCH']:
         json_data = json.loads(request.raw_post_data)
         for key in json_data.keys():
             fld = self.fields.get(key, None)
             if fld is not None and getattr(fld, "final", False):
                 response = http.HttpUnauthorized("Error message")
                 raise ImmediateHttpResponse(response=response)
     return object_list
Exemple #19
0
    def download(self, request, **kwargs):
        swiftfile = SwiftFile.objects.get(pk=kwargs.get('id'))
        try:
            temp_url = swiftfile.get_temp_download_url()
        except swiftclient.ClientException:
            return http.HttpUnauthorized(
                "You are not authorized in stackswift service, \
				please, make sure that you add your username and key to your settings")
        return self.create_response(request, {'temp_url': temp_url},
                                    response_class=http.HttpAccepted)
Exemple #20
0
    def is_authenticated(self, request):
        ''' Overriding to delete www-authenticate, preventing browser popup '''
        auth_result = self._meta.authentication.is_authenticated(request)

        if isinstance(auth_result, HttpResponse):
            del auth_result['WWW-Authenticate']
            raise ImmediateHttpResponse(response=auth_result)

        if not auth_result is True:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())
Exemple #21
0
    def obj_get(self, request=None, **kwargs):
        """
        Returns mongodb document from provided id.
        """
        document = Document.objects.get(_id=ObjectId(kwargs.get("pk")))

        if request is not None and not document.is_visible(
                user_id=request.user.id):
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        return document
Exemple #22
0
def api_auth(request):
    """ authentication gate for the REST clients. Wraps the normal login method
    into JSON shell """
    if not request.method == "POST":
        return http.HttpMethodNotAllowed()

    form = AuthenticationForm(data=request.POST)
    if form.is_valid():
        login(request, form.get_user())
        return http.HttpAccepted()
    else:
        return http.HttpUnauthorized("Invalid credentials")
Exemple #23
0
 def permissions(self, request, **kwargs):
     self.method_check(request, allowed=['get'])
     self.is_authenticated(request)
     if request.user.is_authenticated():
         # Get the list of permission and sorts it alphabeticly
         permissions = list(request.user.get_all_permissions())
         permissions.sort()
         return self.create_response(request, {
             'permissions': permissions
         })
     else:
         return http.HttpUnauthorized('You need to be logged to list your permissions')
Exemple #24
0
    def is_authenticated(self, request, **kwargs):
        """
        Finds the user and checks their API key.

        Should return either ``True`` if allowed, ``False`` if not or an
        ``HttpResponse`` if you need something custom.
        """
        UserModel = get_user_model()

        try:
            email, api_key = self.extract_credentials(request)
        except ValueError:
            return self._unauthorized()

        if not email or not api_key:
            return self._unauthorized()

        try:
            user = UserModel._default_manager.get(email=email)
        except (UserModel.DoesNotExist, UserModel.MultipleObjectsReturned):
            return self._unauthorized()

        if not self.check_active(user):
            return False

        key_auth_check = self.get_key(user, api_key)
        if key_auth_check and not isinstance(key_auth_check,
                                             http.HttpUnauthorized):
            request.user = user
            if not getattr(request, 'vosae_user', None):
                if request.user.groups.filter(name=request.tenant.slug):
                    request.vosae_user = VosaeUser.objects.get(
                        tenant=request.tenant, email=request.user.email)
                else:
                    raise ImmediateHttpResponse(http.HttpUnauthorized())
            if not request.vosae_user.is_active():
                raise ImmediateHttpResponse(http.HttpUnauthorized())

        return key_auth_check
Exemple #25
0
    def get_related_object(self, request, **kwargs):
        try:
            story_id = kwargs.get('story_id')
            story = Story.objects.get(story_id=story_id)
            if not story.has_perm(request.user, 'change'):
                raise ImmediateHttpResponse(response=http.HttpUnauthorized(
                    "You are not authorized to change the story matching the provided story ID"
                ))
        except ObjectDoesNotExist:
            raise ImmediateHttpResponse(response=http.HttpNotFound(
                "A story matching the provided story ID could not be found"))

        return story
Exemple #26
0
 def post_detail(self, request, **kwargs):
     draw_id = kwargs['pk']
     try:
         draw = self._client.retrieve_draw(draw_id)
     except mongodb.MongoDriver.NotFoundError:
         return http.HttpBadRequest("Draw not found")
     try:
         data = json.loads(request.body)
     except TypeError:
         data = json.loads(request.body.decode('utf-8'))
     if 'add_user' in data:
         if not draw.check_write_access(request.user):
             raise exceptions.ImmediateHttpResponse(
                 response=http.HttpUnauthorized(
                     "Only the owner can add users"))
         new_users = {
             str(user)
             for user in data['add_user'] if '@' in str(user)
         }
         new_users = [user for user in new_users if user not in draw.users]
         draw.users.extend(new_users)
         self._client.save_draw(draw)
         invite_user(new_users, draw)
     if 'remove_user' in data:
         if not draw.check_write_access(request.user):
             raise exceptions.ImmediateHttpResponse(
                 response=http.HttpUnauthorized(
                     "Only the owner can remove users"))
         try:
             draw.users.remove(str(data['remove_user']))
             self._client.save_draw(draw)
         except ValueError:
             pass
     if request.user.is_authenticated(
     ) and request.user.pk not in draw.users:
         draw.users.append(request.user.pk)
         self._client.save_draw(draw)
     return http.HttpCreated()
Exemple #27
0
 def me(self, request, **kwargs):
     self.method_check(request, allowed=['get'])
     self.is_authenticated(request)
     if request.user.is_authenticated():
         bundle = self.build_bundle(obj=request.user, request=request)
         bundle = self.full_dehydrate(bundle)
         # Get the list of permission and sorts it alphabeticly
         permissions = list(request.user.get_all_permissions())
         permissions.sort()
         # Add user's permissions
         bundle.data["permissions"] = permissions
         return self.create_response(request, bundle)
     else:
         return http.HttpUnauthorized('You need to be logged.')
Exemple #28
0
    def user_login(self, request, **_):
        self.method_check(request, allowed=['post'])
        self.throttle_check(request)
        try:
            data = json.loads(request.body)
        except TypeError:
            data = json.loads(request.body.decode('utf-8'))

        email = data.pop('email')
        password = data.pop('password')

        user = authenticate(username=email, password=password)
        if user:
            if user.is_active:
                if 'keep-logged' in request.POST:
                    request.session.set_expiry(31556926)  # 1 year
                login(request, user)
                user = self._client.retrieve_user(user.pk)
                user.last_login = datetime.datetime.utcnow().replace(
                    tzinfo=pytz.utc)
                self._client.save_user(user)
                return self.create_response(request, "User authenticated")
            else:
                raise exceptions.ImmediateHttpResponse(
                    response=http.HttpUnauthorized(
                        "The user is not activated"))
        else:
            try:
                self._client.retrieve_user(email)
            except mongodb.MongoDriver.NotFoundError:
                raise exceptions.ImmediateHttpResponse(
                    response=http.HttpNotFound(
                        "The email {0} is not registered".format(email)))
            else:
                raise exceptions.ImmediateHttpResponse(
                    response=http.HttpUnauthorized("Incorrect password"))
    def obj_delete(self, request=None, **kwargs):
        """
        - Removes comment if user is authorized
        - Fires comment_delete signal
        """
        comment = self.obj_get(**kwargs)
        if (request.user.is_anonymous()
                or not request.user.pk == comment.get("user_id")):
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        super(CommentResource, self).obj_delete(request, **kwargs)

        comment_delete.send(sender=self,
                            comment_id=comment.id,
                            instance=comment)
Exemple #30
0
    def obj_create(self, bundle, **kwargs):
        identifier_key = bundle.data['key']
        identifier = OutboundMessageIdentifier.objects.get(
            key=bundle.data['key'])
        owner = identifier.outbound_message.message.writeitinstance.owner

        if owner != bundle.request.user:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        answer_content = bundle.data['content']
        answer = OutboundMessageIdentifier.create_answer(
            identifier_key, answer_content)
        bundle.obj = answer
        bundle.data['id'] = bundle.obj.id
        return bundle