Beispiel #1
0
        def wrapper(self, request, *args, **kwargs):
            group_name = kwargs.get(group_url_kwarg, None)
            if not group_name:
                return HttpResponseNotFound(_("No team provided"))

            group = get_group_for_request(group_name, request)
            user = request.user

            # set the group attribute
            setattr(self, group_attr, group)

            if not group.public and not user.is_authenticated():
                return redirect_to_not_logged_in(request,
                                                 view=self,
                                                 group=group)

            deactivated_app_error = _check_deactivated_app_access(
                self, group, request)
            if deactivated_app_error:
                return deactivated_app_error

            if check_group_create_objects_access(group, user):
                return function(self, request, *args, **kwargs)

            # Access denied, redirect to 403 page and and display an error message
            return redirect_to_403(request, self, group=group)
Beispiel #2
0
 def save(self, *args, **kwargs):
     """ Sanity checks that the creator of this reflection has create-objects permissions on the target
         group, and if not *deletes* this reflection! """
     ret = super(BaseTaggableObjectReflection, self).save(*args, **kwargs)
     from cosinnus.utils.permissions import check_group_create_objects_access
     if not check_group_create_objects_access(self.group, self.creator):
         logger.warn(
             'Deleted a BaseTaggableObjectReflection after saving it for sanity - user did not have create objects permissions on the group!',
             extra={
                 'group': self.group,
                 'user': self.creator.id
             })
         self.delete()
     return ret
Beispiel #3
0
        def wrapper(self, request, *args, **kwargs):
            url_kwarg = group_url_kwarg or getattr(self, 'group_url_kwarg',
                                                   'group')
            attr = group_attr or getattr(self, 'group_attr', 'group')
            group_name = kwargs.get(url_kwarg, None)
            if not group_name:
                return HttpResponseNotFound(_("No team provided"))

            group = get_group_for_request(group_name, request)
            user = request.user

            # set the group attr
            setattr(self, attr, group)

            # catch anyonymous users trying to naviagte to private groups (else self.get_object() throws a Http404!)
            if not group.public and not user.is_authenticated:
                return redirect_to_not_logged_in(request,
                                                 view=self,
                                                 group=group)

            deactivated_app_error = _check_deactivated_app_access(
                self, group, request)
            if deactivated_app_error:
                return deactivated_app_error

            requested_object = None
            try:
                requested_object = self.get_object()
            except (AttributeError, TypeError):
                pass

            # objects can never be written by non-logged in members
            if not user.is_authenticated:
                return redirect_to_not_logged_in(request,
                                                 view=self,
                                                 group=group)

            if requested_object:
                # editing/deleting an object, check if we are owner or staff member or group admin or site admin
                if check_object_write_access(requested_object, user):
                    return function(self, request, *args, **kwargs)
            else:
                # creating a new object, check if we can create objects in the group
                if check_group_create_objects_access(group, user):
                    return function(self, request, *args, **kwargs)

            # Access denied, redirect to 403 page and and display an error message
            return redirect_to_403(request, self, group=group)
Beispiel #4
0
def can_create_objects_in(user, group):
    """
    Template filter to check if a user can create objects in a CosinnusGroup.
    This factors in all aspects of superusers and group memberships.
    """
    return check_group_create_objects_access(group, user)
Beispiel #5
0
def file_upload_inline(request, group):
    """ Inline file upload to be called from jQuery FileUpload.
        @param request.on_success: Determines what kind of data will be sent back, and in cosinnus.JS, 
                                    determines what will be done with the data. Options:
            - 'add_to_select2' (default): Will render a select2 pill and in JS, append it to the attach-file select2 field.
            - 'refresh_page' will add a message to the request and in JS refresh the browser page
            - 'render_object' will render the single file template(s) and in JS append them to the file list """
    if not request.is_ajax() or not request.method=='POST':
        return HttpResponseNotAllowed(['POST'])
    
    on_success = request.POST.get('on_success', 'add_to_select2')
    direct_upload = request.POST.get('direct_upload', False)
    make_private = request.POST.get('private_upload', False)
    
    
    # resolve group either from the slug, or like the permission group mixin does ist
    # (group type needs to also be used for that=
    group = get_group_for_request(group, request)
    if not group:
        logger.error('No group found when trying to upload a file!', extra={'group_slug': group, 
            'request': request, 'path': request.path})
        return JSONResponse({'status': 'error', 'message': _('Internal Error: Group not Found')})
    
    # do permission checking using has_write_access(request.user, group)
    if not check_group_create_objects_access(group, request.user):
        logger.error('Permission error while uploading an attached file directly!', 
             extra={'user': request.user, 'request': request, 'path': request.path, 'group_slug': group})
        return JSONResponse({'status': 'error', 'message': _('Permission for upload denied')})
    
    # add any other required kwargs (group) and stuff correctly so the form can be saved
    post = request.POST
    post._mutable = True
    post.update({
        'group_id': group.id
    })
    
    
    base_upload_folder = None
    upload_to_attachment_folder = False
    if 'target_folder' in post:
        base_upload_folder = get_object_or_404(FileEntry, id=int(post.get('target_folder')))
    if not base_upload_folder:
        # check if the group has a folder with slug 'uploads' and if not, create one
        base_upload_folder = get_or_create_attachment_folder(group)
        upload_to_attachment_folder = True
    
    file_info_array = json.loads(post.get('file_info', '[]'))
    result_list = []
    for file_index, dict_file in enumerate(request.FILES.getlist('file')):
        upload_folder = None
        # unless we are uploading as attachment, see if we have any further folder info for this file
        if not upload_to_attachment_folder and len(file_info_array) > file_index:
            # get relative path for the ith file, it should be the same as in the FILES list
            relative_path = file_info_array[file_index]['relative_path']
            name = file_info_array[file_index]['name']
            if relative_path:
                # sanity check, file name in file info must match FILES file name
                if not name == dict_file._name:
                    logger.warn('File upload sanity check failed: File order of file with relative path info and FILES list did not match! (Upload may have sorted the user\'s file in the wrong folder)', extra={
                        'file_info': file_info_array, 'FILES_list': request.FILES.getlist('file')})
                upload_folder = _create_folders_for_path_string(base_upload_folder, relative_path)
                # switch mode to refresh page if we had at least one folder upload
                on_success = 'refresh_page'
                
        if not upload_folder:
            upload_folder = base_upload_folder
            
        single_file_dict = MultiValueDict({'file': [dict_file]})
        post.update({
            'title': clean_single_line_text(dict_file._name),
        })
        form = FileForm(post, single_file_dict, group=group, initial={})
        if form.is_valid():
            # form.instance is the FileEntry, not the media tag
            form.instance.group = group
            form.instance.creator = request.user
            form.instance.path = upload_folder.path
            form.instance._filesize = form.instance.file.file.size
            if not direct_upload:
                form.instance.no_notification = True # disable notifications on non-direct (attached, etc) uploads
            saved_file = form.save()
            
            # flag for uploading the file visible only to oneself, as used in message attachments
            if make_private:
                saved_file.media_tag.visibility = BaseTagObject.VISIBILITY_USER
                saved_file.media_tag.save()
                
            # render either for the file list or for the attached objects
            if on_success == 'render_object':
                context = {
                    'file': saved_file,
                    'do_highlight': True
                }
                result_list.append(render_to_string('cosinnus_file/single_file_detailed.html', context, request))
            else:
                # pipe the file into the select2 JSON representation to be displayed as select2 pill 
                pill_id, pill_html = build_attachment_field_result('cosinnus_file.FileEntry', saved_file)
                result_list.append({'text': pill_html, 'id': pill_id})
        else:
            logger.warn('Form error while uploading an attached file directly!', 
                 extra={'form.errors': form.errors, 'user': request.user, 'request': request, 
                        'path': request.path, 'group_slug': group})
            message = _('The uploaded file was invalid.')
            if form.forms['obj'].errors.get('file', None):
                message = form.forms['obj'].errors.get('file', None)
            return JSONResponse({'status': 'error', 'message': message})
            
    if result_list:
        if on_success == 'refresh_page':
            messages.success(request, ungettext('%(count)d File was added successfully.', '%(count)d Files were added successfully.', len(result_list)) % {'count': len(result_list)})
        
        
        return JSONResponse({'status': 'ok', 'on_success': on_success, 'data': result_list})
    else:
        return JSONResponse({'status': 'error', 'message': _('The file you uploaded was too large or the file type was not permitted to be uploaded!')})