示例#1
0
    def put(self, request, repo_id, format=None):
        """ Update permission in repo share invitation.
        """
        # argument check
        path = request.data.get('path', None)
        if not path:
            return api_error(status.HTTP_400_BAD_REQUEST, 'path invalid.')

        token = request.data.get('token', None)
        if not token:
            return api_error(status.HTTP_400_BAD_REQUEST, 'token invalid.')

        permission = request.data.get('permission', PERMISSION_READ)
        if permission not in (PERMISSION_READ, PERMISSION_READ_WRITE):
            return api_error(status.HTTP_400_BAD_REQUEST,
                             'permission invalid.')

        # recourse check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Library %s not found.' % repo_id)

        if seafile_api.get_dir_id_by_path(repo.id, path) is None:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Folder %s not found.' % path)

        # permission check
        username = request.user.username
        if is_org_context(request):
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
        else:
            repo_owner = seafile_api.get_repo_owner(repo_id)

        if username != repo_owner and not is_repo_admin(username, repo_id):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # mian
        try:
            shared_obj = RepoShareInvitation.objects.get_by_token_and_path(
                token=token, repo_id=repo_id, path=path)
            if not shared_obj:
                error_msg = 'repo share invitation not found.'
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)
            if shared_obj.permission == permission:
                error_msg = 'repo share invitation already has %s premission.' % permission
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            shared_obj.permission = permission
            shared_obj.save()
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
示例#2
0
    def delete(self, request, group_id, repo_id):
        """ Delete a group library.

        Permission checking:
        1. is group admin;
        1. is repo owner;
        1. repo is shared to group with `admin` permission;
        """

        group_id = int(group_id)

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        is_org = False
        if is_org_context(request):
            is_org = True

        group_repo = seafile_api.get_group_shared_repo_by_path(
            repo_id, None, group_id, is_org)
        if not group_repo:
            error_msg = 'Group library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # only group admin or repo owner can delete group repo.
        username = request.user.username
        repo_owner = get_repo_owner(request, repo_id)

        if not is_group_admin(group_id, username) and \
                repo_owner != username and \
                not is_repo_admin(username, repo_id):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        permission = check_group_share_in_permission(repo_id, group_id, is_org)

        if is_org:
            org_id = ccnet_api.get_org_id_by_group(group_id)
            seafile_api.del_org_group_repo(repo_id, org_id, group_id)
        else:
            seafile_api.unset_group_repo(repo_id, group_id, username)

        origin_repo_id = group_repo.origin_repo_id or repo_id
        origin_path = group_repo.origin_path or '/'
        send_perm_audit_msg('delete-repo-perm', username, group_id,
                            origin_repo_id, origin_path, permission)

        # delete extra share permission
        ExtraGroupsSharePermission.objects.delete_share_permission(
            repo_id, group_id)

        return Response({'success': True})
示例#3
0
文件: repo.py 项目: ysf002/seahub
def can_set_folder_perm_by_user(username, repo, repo_owner):
    """ user can get/update/add/delete folder perm feature must comply with the following
            repo:repo is not virtual
            permission: is admin or repo owner.
    """
    if repo.is_virtual:
        return False
    is_admin = is_repo_admin(username, repo.id)
    if username != repo_owner and not is_admin:
        return False
    return True
示例#4
0
    def delete(self, request, group_id, repo_id):
        """ Delete a group library.

        Permission checking:
        1. is repo owner;
        2. is repo admin;
        3. is group admin;
        """

        group_id = int(group_id)

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        is_org = False
        if is_org_context(request):
            is_org = True

        group_repo = seafile_api.get_group_shared_repo_by_path(repo_id,
                None, group_id, is_org)
        if not group_repo:
            error_msg = 'Group library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # only group admin or repo owner can delete group repo.
        username = request.user.username
        repo_owner = get_repo_owner(request, repo_id)

        if not is_group_admin(group_id, username) and \
                repo_owner != username and \
                not is_repo_admin(username, repo_id):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        permission = check_group_share_in_permission(repo_id, group_id, is_org)

        if is_org:
            org_id = ccnet_api.get_org_id_by_group(group_id)
            seafile_api.del_org_group_repo(repo_id, org_id, group_id)
        else:
            seafile_api.unset_group_repo(repo_id, group_id, username)

        origin_repo_id = group_repo.origin_repo_id or repo_id
        origin_path = group_repo.origin_path or '/'
        send_perm_audit_msg('delete-repo-perm', username, group_id,
                origin_repo_id, origin_path, permission)

        # delete extra share permission
        ExtraGroupsSharePermission.objects.delete_share_permission(repo_id, group_id)

        return Response({'success': True})
示例#5
0
文件: repo.py 项目: haiwen/seahub
def can_set_folder_perm_by_user(username, repo, repo_owner):
    """ user can get/update/add/delete folder perm feature must comply with the following
            setting: ENABLE_FOLDER_PERM
            repo:repo is not virtual
            permission: is admin or repo owner.
    """
    if not ENABLE_FOLDER_PERM:
        return False
    if repo.is_virtual:
        return False
    is_admin = is_repo_admin(username, repo.id)
    if username != repo_owner and not is_admin:
        return False
    return True
示例#6
0
    def put(self, request, repo_id, permission_id):
        """Update a custom share permission
        """
        username = request.user.username
        # argument check
        permission = request.data.get('permission', None)
        if not permission:
            error_msg = 'permission invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        permission_name = request.data.get('permission_name', None)
        if not permission_name:
            error_msg = 'permission_name invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        description = request.data.get('description', '')

        # permission check
        if not is_repo_admin(username, repo_id):
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            permission_obj = CustomSharePermissions.objects.get(
                id=permission_id)
            if not permission_obj:
                return api_error(status.HTTP_404_NOT_FOUND,
                                 'Permission %s not found.' % permission_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # main
        try:
            permission_obj.name = permission_name
            permission_obj.description = description
            permission_obj.permission = permission
            permission_obj.save()
            res = permission_obj.to_dict()
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'permission': res})
示例#7
0
    def get(self, request, repo_id, format=None):
        """ List repo share invitations.
        """
        # argument check
        path = request.GET.get('path', None)
        if not path:
            return api_error(status.HTTP_400_BAD_REQUEST, 'path invalid.')

        # recourse check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if seafile_api.get_dir_id_by_path(repo.id, path) is None:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Folder %s not found.' % path)

        # permission check
        username = request.user.username
        if is_org_context(request):
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
        else:
            repo_owner = seafile_api.get_repo_owner(repo_id)

        if username != repo_owner and not is_repo_admin(username, repo_id):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # main
        shared_list = list()
        try:
            shared_queryset = RepoShareInvitation.objects.list_by_repo_id_and_path(
                repo_id, path)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        for obj in shared_queryset:
            data = obj.invitation.to_dict()
            data['permission'] = obj.permission
            data['inviter_name'] = email2nickname(obj.invitation.inviter)

            shared_list.append(data)

        return Response({'repo_share_invitation_list': shared_list})
示例#8
0
    def delete(self, request, repo_id, permission_id):
        """Delete a custom share permission
        """
        username = request.user.username
        # permission check
        if not is_repo_admin(username, repo_id):
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            permission_obj = CustomSharePermissions.objects.get(
                id=permission_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
        if not permission_obj:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'custom permission %s not found.' % permission_id)

        # main
        try:
            permission_obj = CustomSharePermissions.objects.get(
                id=permission_id)
            if not permission_obj:
                return api_error(status.HTTP_404_NOT_FOUND,
                                 'Permission %s not found.' % permission_id)
            permission_obj.delete()
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
示例#9
0
    def post(self, request, repo_id, format=None):
        """ Batch add repo share invitations.
        """
        # argument check
        path = request.data.get('path', None)
        if not path:
            return api_error(status.HTTP_400_BAD_REQUEST, 'path invalid.')

        itype = request.data.get('type', '').lower()
        if not itype or itype != GUEST_USER:
            return api_error(status.HTTP_400_BAD_REQUEST, 'type invalid.')

        accepters = request.data.get('accepters', None)
        if not accepters or not isinstance(accepters, list):
            return api_error(status.HTTP_400_BAD_REQUEST, 'accepters invalid.')

        permission = request.data.get('permission', PERMISSION_READ)
        if permission not in (PERMISSION_READ, PERMISSION_READ_WRITE):
            return api_error(status.HTTP_400_BAD_REQUEST,
                             'permission invalid.')

        # recourse check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Library %s not found.' % repo_id)

        if seafile_api.get_dir_id_by_path(repo.id, path) is None:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Folder %s not found.' % path)

        # permission check
        username = request.user.username
        if is_org_context(request):
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
        else:
            repo_owner = seafile_api.get_repo_owner(repo_id)

        if username != repo_owner and not is_repo_admin(username, repo_id):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # main
        result = {}
        result['failed'] = []
        result['success'] = []
        inviter_name = email2nickname(request.user.username)

        try:
            invitation_queryset = Invitation.objects.order_by(
                '-invite_time').filter(inviter=request.user.username,
                                       accept_time=None)
            shared_queryset = RepoShareInvitation.objects.list_by_repo_id_and_path(
                repo_id=repo_id, path=path)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        for accepter in accepters:

            if not accepter.strip():
                continue

            accepter = accepter.lower()

            if not is_valid_email(accepter):
                result['failed'].append({
                    'email':
                    accepter,
                    'error_msg':
                    _('Email %s invalid.') % accepter
                })
                continue

            if block_accepter(accepter):
                result['failed'].append({
                    'email':
                    accepter,
                    'error_msg':
                    _('The email address is not allowed to be invited as a guest.'
                      )
                })
                continue

            try:
                user = User.objects.get(accepter)
                # user is active return exist
                if user.is_active is True:
                    result['failed'].append({
                        'email':
                        accepter,
                        'error_msg':
                        _('User %s already exists.') % accepter
                    })
                    continue
            except User.DoesNotExist:
                pass

            if invitation_queryset.filter(accepter=accepter).exists():
                invitation = invitation_queryset.filter(accepter=accepter)[0]
                invitation.expire_time = timezone.now() + timedelta(
                    hours=int(INVITATIONS_TOKEN_AGE))
                invitation.save()
            else:
                invitation = Invitation.objects.add(
                    inviter=request.user.username, accepter=accepter)

            if shared_queryset.filter(invitation=invitation).exists():
                result['failed'].append({
                    'email':
                    accepter,
                    'error_msg':
                    _('This item has been shared to %s.') % accepter
                })
                continue

            try:
                RepoShareInvitation.objects.add(invitation=invitation,
                                                repo_id=repo_id,
                                                path=path,
                                                permission=permission)
            except Exception as e:
                logger.error(e)
                result['failed'].append({
                    'email':
                    accepter,
                    'error_msg':
                    _('Internal Server Error'),
                })

            data = invitation.to_dict()
            data['permission'] = permission
            data['inviter_name'] = inviter_name

            result['success'].append(data)

            send_sucess = invitation.send_to(email=accepter)

            if not send_sucess:
                result['failed'].append({
                    'email':
                    accepter,
                    'error_msg':
                    _('Failed to send email, email service is not properly configured, please contact administrator.'
                      ),
                })

        return Response(result)
示例#10
0
    def post(self, request, format=None):
        """Add a new wiki.
        """
        username = request.user.username

        org_id = -1
        if is_org_context(request):
            org_id = request.user.org.org_id

        repo_id = request.POST.get('repo_id', '')
        if not repo_id:
            msg = 'Repo id is invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, msg)

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # check perm
        if not (request.user.permissions.can_publish_repo() and request.user.permissions.can_generate_share_link()):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        is_owner = is_repo_owner(request, repo_id, username)

        if not is_owner:
            repo_admin = is_repo_admin(username, repo_id)

            if not repo_admin:
                is_group_repo_admin = is_group_repo_staff(request, repo_id, username)

                if not is_group_repo_admin:
                    error_msg = _('Permission denied.')
                    return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            wiki = Wiki.objects.add(wiki_name=repo.repo_name, username=username,
                    repo_id=repo.repo_id, org_id=org_id, permission='public')
        except DuplicateWikiNameError:
            msg = _('%s is taken by others, please try another name.') % repo.repo_name
            return api_error(status.HTTP_400_BAD_REQUEST, msg)
        except IntegrityError:
            msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

        # create home page if not exist
        page_name = "home.md"
        if not seafile_api.get_file_id_by_path(repo_id, "/" + page_name):
            try:
                seafile_api.post_empty_file(repo_id, '/', page_name, username)
            except SearpcError as e:
                logger.error(e)
                msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

        fs = FileShare.objects.get_dir_link_by_path(username, repo_id, '/')
        if not fs:
            fs = FileShare.objects.create_dir_link(username, repo_id, '/',
                    permission='view_download', org_id=org_id)

        return Response(wiki.to_dict())
示例#11
0
    def delete(self, request, repo_id, format=None):
        username = request.user.username
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Library %s not found.' % repo_id)

        path = request.GET.get('p', '/')
        if seafile_api.get_dir_id_by_path(repo.id, path) is None:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Folder %s not found.' % path)

        repo_owner = self.get_repo_owner(request, repo_id)
        if repo_owner != username and not is_repo_admin(username, repo_id):
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        shared_to_user, shared_to_group = self.handle_shared_to_args(request)
        if shared_to_user:
            shared_to = request.GET.get('username')
            if shared_to is None or not is_valid_username(shared_to):
                return api_error(status.HTTP_400_BAD_REQUEST,
                                 'Email %s invalid.' % shared_to)

            permission = check_user_share_out_permission(
                repo_id, path, shared_to, is_org_context(request))

            if is_org_context(request):
                # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                org_id = request.user.org.org_id
                if path == '/':
                    seaserv.seafserv_threaded_rpc.org_remove_share(
                        org_id, repo_id, repo_owner, shared_to)
                else:
                    seafile_api.org_unshare_subdir_for_user(
                        org_id, repo_id, path, repo_owner, shared_to)

            else:
                if path == '/':
                    seaserv.remove_share(repo_id, repo_owner, shared_to)
                else:
                    seafile_api.unshare_subdir_for_user(
                        repo_id, path, repo_owner, shared_to)

            # Delete share permission at ExtraSharePermission table.
            if path == '/':
                ExtraSharePermission.objects.delete_share_permission(
                    repo_id, shared_to)
            send_perm_audit_msg('delete-repo-perm', username, shared_to,
                                repo_id, path, permission)

        if shared_to_group:
            group_id = request.GET.get('group_id')
            try:
                group_id = int(group_id)
            except ValueError:
                return api_error(status.HTTP_400_BAD_REQUEST,
                                 'group_id %s invalid' % group_id)

            # hacky way to get group repo permission
            is_org = is_org_context(request)
            permission = check_group_share_out_permission(
                repo_id, path, group_id, is_org)

            if is_org:
                # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                org_id = request.user.org.org_id
                if path == '/':
                    seaserv.del_org_group_repo(repo_id, org_id, group_id)
                else:
                    seafile_api.org_unshare_subdir_for_group(
                        org_id, repo_id, path, repo_owner, group_id)
            else:
                if path == '/':
                    seafile_api.unset_group_repo(repo_id, group_id, username)
                else:
                    seafile_api.unshare_subdir_for_group(
                        repo_id, path, repo_owner, group_id)

            # delete share permission if repo is deleted
            if path == '/':
                ExtraGroupsSharePermission.objects.delete_share_permission(
                    repo_id, group_id)
            send_perm_audit_msg('delete-repo-perm', username, group_id,
                                repo_id, path, permission)

        return HttpResponse(json.dumps({'success': True}),
                            status=200,
                            content_type=json_content_type)
示例#12
0
    def put(self, request, repo_id, format=None):
        username = request.user.username
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Library %s not found.' % repo_id)

        path = request.GET.get('p', '/')
        if seafile_api.get_dir_id_by_path(repo.id, path) is None:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Folder %s not found.' % path)

        if repo.encrypted and path != '/':
            return api_error(status.HTTP_400_BAD_REQUEST, 'Folder invalid.')

        share_type = request.data.get('share_type')
        if share_type != 'user' and share_type != 'group':
            return api_error(status.HTTP_400_BAD_REQUEST,
                             'share_type invalid.')

        repo_owner = self.get_repo_owner(request, repo_id)
        if repo_owner != username and not is_repo_admin(username, repo_id):
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        permission = request.data.get('permission', PERMISSION_READ)
        if permission not in get_available_repo_perms():
            return api_error(status.HTTP_400_BAD_REQUEST,
                             'permission invalid.')

        result = {}
        result['failed'] = []
        result['success'] = []

        if share_type == 'user':
            share_to_users = request.data.getlist('username')
            for to_user in share_to_users:
                if not is_valid_username(to_user):
                    result['failed'].append({
                        'email': to_user,
                        'error_msg': _('username invalid.')
                    })
                    continue

                try:
                    User.objects.get(email=to_user)
                except User.DoesNotExist:
                    result['failed'].append({
                        'email':
                        to_user,
                        'error_msg':
                        _('User %s not found.') % to_user
                    })
                    continue

                if self.has_shared_to_user(request, repo_id, path, to_user):
                    result['failed'].append({
                        'email':
                        to_user,
                        'error_msg':
                        _('This item has been shared to %s.') %
                        email2nickname(to_user)
                    })
                    continue

                try:
                    org_id = None
                    if is_org_context(request):
                        org_id = request.user.org.org_id

                        if not is_org_user(to_user, int(org_id)):
                            org_name = request.user.org.org_name
                            error_msg = 'User %s is not member of organization %s.' \
                                    % (to_user, org_name)

                            result['failed'].append({
                                'email': to_user,
                                'error_msg': error_msg
                            })
                            continue

                        # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                        repo_owner = seafile_api.get_org_repo_owner(repo_id)
                        # can't share to owner
                        if to_user == repo_owner:
                            error_msg = "Library can not be shared to owner"
                            return api_error(status.HTTP_400_BAD_REQUEST,
                                             error_msg)

                        share_dir_to_user(repo, path, repo_owner, username,
                                          to_user, permission, org_id)
                    else:
                        if is_org_user(to_user):
                            error_msg = 'User %s is a member of organization.' % to_user
                            result['failed'].append({
                                'email': to_user,
                                'error_msg': error_msg
                            })
                            continue

                        repo_owner = seafile_api.get_repo_owner(repo_id)
                        # can't share to owner
                        if to_user == repo_owner:
                            error_msg = "Library can not be shared to owner"
                            return api_error(status.HTTP_400_BAD_REQUEST,
                                             error_msg)

                        share_dir_to_user(repo, path, repo_owner, username,
                                          to_user, permission, None)

                    avatar_url, is_default, date_uploaded = api_avatar_url(
                        to_user, 72)
                    result['success'].append({
                        "share_type":
                        "user",
                        "user_info": {
                            "name": to_user,
                            "nickname": email2nickname(to_user),
                            "contact_email": email2contact_email(to_user),
                            "avatar_url": avatar_url,
                        },
                        "permission":
                        PERMISSION_READ_WRITE
                        if permission == PERMISSION_ADMIN else permission,
                        "is_admin":
                        permission == PERMISSION_ADMIN
                    })

                    # send a signal when sharing repo successful
                    share_repo_to_user_successful.send(sender=None,
                                                       from_user=username,
                                                       to_user=to_user,
                                                       repo=repo,
                                                       path=path,
                                                       org_id=org_id)

                    send_perm_audit_msg('add-repo-perm', username, to_user,
                                        repo_id, path, permission)
                except SearpcError as e:
                    logger.error(e)
                    result['failed'].append({
                        'email':
                        to_user,
                        'error_msg':
                        'Internal Server Error'
                    })
                    continue

        if share_type == 'group':
            group_ids = request.data.getlist('group_id')
            for gid in group_ids:
                try:
                    gid = int(gid)
                except ValueError:
                    result['failed'].append(
                        {'error_msg': 'group_id %s invalid.' % gid})
                    continue

                group = ccnet_api.get_group(gid)
                if not group:
                    result['failed'].append(
                        {'error_msg': 'Group %s not found' % gid})
                    continue

                if not config.ENABLE_SHARE_TO_ALL_GROUPS and \
                        not is_group_member(gid, username):
                    result['failed'].append({
                        'group_name': group.group_name,
                        'error_msg': 'Permission denied.'
                    })
                    continue

                if self.has_shared_to_group(request, repo_id, path, gid):
                    result['failed'].append({
                        'group_name':
                        group.group_name,
                        'error_msg':
                        _('This item has been shared to %s.') %
                        group.group_name
                    })
                    continue

                try:
                    org_id = None
                    if is_org_context(request):
                        # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                        repo_owner = seafile_api.get_org_repo_owner(repo_id)
                        org_id = request.user.org.org_id

                        share_dir_to_group(repo, path, repo_owner, username,
                                           gid, permission, org_id)
                    else:
                        repo_owner = seafile_api.get_repo_owner(repo_id)

                        share_dir_to_group(repo, path, repo_owner, username,
                                           gid, permission, None)

                    result['success'].append({
                        "share_type":
                        "group",
                        "group_info": {
                            "id": gid,
                            "name": group.group_name,
                        },
                        "permission":
                        PERMISSION_READ_WRITE
                        if permission == PERMISSION_ADMIN else permission,
                        "is_admin":
                        permission == PERMISSION_ADMIN
                    })

                    share_repo_to_group_successful.send(sender=None,
                                                        from_user=username,
                                                        group_id=gid,
                                                        repo=repo,
                                                        path=path,
                                                        org_id=org_id)

                    send_perm_audit_msg('add-repo-perm', username, gid,
                                        repo_id, path, permission)
                except SearpcError as e:
                    logger.error(e)
                    result['failed'].append({
                        'group_name':
                        group.group_name,
                        'error_msg':
                        'Internal Server Error'
                    })
                    continue

        return HttpResponse(json.dumps(result),
                            status=200,
                            content_type=json_content_type)
示例#13
0
    def post(self, request, repo_id, format=None):
        """Update shared item permission.
        """
        username = request.user.username
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Library %s not found.' % repo_id)

        path = request.GET.get('p', '/')
        if seafile_api.get_dir_id_by_path(repo.id, path) is None:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'Folder %s not found.' % path)

        permission = request.data.get('permission', PERMISSION_READ)
        if permission not in get_available_repo_perms():
            return api_error(status.HTTP_400_BAD_REQUEST,
                             'permission invalid.')

        repo_owner = self.get_repo_owner(request, repo_id)
        if repo_owner != username and not is_repo_admin(username, repo_id):
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        shared_to_user, shared_to_group = self.handle_shared_to_args(request)
        if shared_to_user:
            shared_to = request.GET.get('username')
            if shared_to is None or not is_valid_username(shared_to):
                return api_error(status.HTTP_400_BAD_REQUEST,
                                 'Email %s invalid.' % shared_to)

            try:
                User.objects.get(email=shared_to)
            except User.DoesNotExist:
                return api_error(status.HTTP_400_BAD_REQUEST,
                                 'Invalid user, should be registered')

            if is_org_context(request):
                # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                repo_owner = seafile_api.get_org_repo_owner(repo_id)
                org_id = request.user.org.org_id

                update_user_dir_permission(repo_id, path, repo_owner,
                                           shared_to, permission, org_id)
            else:
                repo_owner = seafile_api.get_repo_owner(repo_id)

                update_user_dir_permission(repo_id, path, repo_owner,
                                           shared_to, permission)

            send_perm_audit_msg('modify-repo-perm', username, shared_to,
                                repo_id, path, permission)

        if shared_to_group:
            gid = request.GET.get('group_id')
            try:
                gid = int(gid)
            except ValueError:
                return api_error(status.HTTP_400_BAD_REQUEST,
                                 'group_id %s invalid.' % gid)
            group = seaserv.get_group(gid)
            if not group:
                return api_error(status.HTTP_404_NOT_FOUND,
                                 'Group %s not found.' % gid)

            if is_org_context(request):
                # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                repo_owner = seafile_api.get_org_repo_owner(repo_id)
                org_id = request.user.org.org_id

                update_group_dir_permission(repo_id, path, repo_owner, gid,
                                            permission, org_id)
            else:
                repo_owner = seafile_api.get_repo_owner(repo_id)

                update_group_dir_permission(repo_id, path, repo_owner, gid,
                                            permission, None)

            send_perm_audit_msg('modify-repo-perm', username, gid, repo_id,
                                path, permission)

        return HttpResponse(json.dumps({'success': True}),
                            status=200,
                            content_type=json_content_type)
示例#14
0
    def post(self, request):

        # argument check
        operation = request.data.get('operation', None)
        if not operation:
            error_msg = 'operation invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # operation could be `share`, `unshare`, `delete`, `transfer`
        # we now only use `share`, `unshare`
        if operation not in ('share', 'unshare'):
            error_msg = 'operation can only be "share", "unshare".'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []

        username = request.user.username
        repo_id_list = request.data.getlist('repo_id')
        valid_repo_id_list = []

        # filter out invalid repo id
        for repo_id in repo_id_list:

            if not seafile_api.get_repo(repo_id):
                result['failed'].append({
                    'repo_id':
                    repo_id,
                    'error_msg':
                    'Library %s not found.' % repo_id
                })
                continue

            repo_owner = get_repo_owner(request, repo_id)
            if repo_owner != username and not is_repo_admin(username, repo_id):
                result['failed'].append({
                    'repo_id': repo_id,
                    'error_msg': 'Permission denied.'
                })
                continue

            valid_repo_id_list.append(repo_id)

        # share repo
        if operation == 'share':

            share_type = request.data.get('share_type', None)
            if not share_type:
                error_msg = 'share_type invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if share_type not in ('user', 'group'):
                error_msg = 'share_type can only be "user", "group".'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            permission = request.data.get('permission', 'rw')
            if permission not in [
                    PERMISSION_READ, PERMISSION_READ_WRITE, PERMISSION_ADMIN
            ]:
                error_msg = 'permission invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            # share repo to user
            if share_type == 'user':
                to_username = request.data.get('username', None)
                if not to_username:
                    error_msg = 'username invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                try:
                    User.objects.get(email=to_username)
                except User.DoesNotExist:
                    error_msg = 'User %s not found.' % to_username
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)

                # check if to_user is an org user
                try:
                    org_of_to_user = ccnet_api.get_orgs_by_user(to_username)
                except Exception as e:
                    logger.error(e)
                    org_of_to_user = []

                if is_org_context(request):
                    org_id = request.user.org.org_id
                    org_name = request.user.org.org_name
                    if len(org_of_to_user
                           ) == 0 or org_id != org_of_to_user[0].org_id:
                        error_msg = 'User %s is not member of organization %s.' \
                                % (to_username, org_name)
                        return api_error(status.HTTP_403_FORBIDDEN, error_msg)
                else:
                    if len(org_of_to_user) >= 1:
                        error_msg = 'User %s is member of organization %s.' \
                                % (to_username, org_of_to_user[0].org_name)
                        return api_error(status.HTTP_403_FORBIDDEN, error_msg)

                for repo_id in valid_repo_id_list:
                    if self.has_shared_to_user(request, repo_id, to_username):
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'This item has been shared to %s.' % to_username
                        })
                        continue

                    try:
                        org_id = None
                        if is_org_context(request):
                            org_id = request.user.org.org_id
                            seaserv.seafserv_threaded_rpc.org_add_share(
                                org_id, repo_id, username, to_username,
                                permission)
                        else:
                            seafile_api.share_repo(repo_id, username,
                                                   to_username, permission)

                        # send a signal when sharing repo successful
                        repo = seafile_api.get_repo(repo_id)
                        share_repo_to_user_successful.send(sender=None,
                                                           from_user=username,
                                                           to_user=to_username,
                                                           repo=repo,
                                                           path='/',
                                                           org_id=org_id)

                        result['success'].append({
                            "repo_id": repo_id,
                            "username": to_username,
                            "permission": permission
                        })

                        send_perm_audit_msg('add-repo-perm', username,
                                            to_username, repo_id, '/',
                                            permission)
                    except Exception as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'Internal Server Error'
                        })

            # share repo to group
            if share_type == 'group':
                to_group_id = request.data.get('group_id', None)
                if not to_group_id:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                try:
                    to_group_id = int(to_group_id)
                except ValueError:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                group = ccnet_api.get_group(to_group_id)
                if not group:
                    error_msg = 'Group %s not found.' % to_group_id
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)

                group_name = group.group_name
                if not is_group_member(to_group_id, username):
                    error_msg = 'User %s is not member of group %s.' % (
                        username, group_name)
                    return api_error(status.HTTP_403_FORBIDDEN, error_msg)

                for repo_id in valid_repo_id_list:
                    if self.has_shared_to_group(request, repo_id, to_group_id):
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'This item has been shared to %s.' % group_name
                        })
                        continue

                    try:
                        org_id = None
                        if is_org_context(request):
                            org_id = request.user.org.org_id
                            seafile_api.add_org_group_repo(
                                repo_id, org_id, to_group_id, username,
                                permission)
                        else:
                            seafile_api.set_group_repo(repo_id, to_group_id,
                                                       username, permission)

                        # send a signal when sharing repo successful
                        repo = seafile_api.get_repo(repo_id)
                        share_repo_to_group_successful.send(
                            sender=None,
                            from_user=username,
                            group_id=to_group_id,
                            repo=repo,
                            path='/',
                            org_id=org_id)

                        result['success'].append({
                            "repo_id": repo_id,
                            "group_id": to_group_id,
                            "group_name": group_name,
                            "permission": permission
                        })

                        send_perm_audit_msg('add-repo-perm', username,
                                            to_group_id, repo_id, '/',
                                            permission)

                    except SearpcError as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'Internal Server Error'
                        })

        # unshare repo
        if operation == 'unshare':

            share_type = request.data.get('share_type', None)
            if not share_type:
                error_msg = 'share_type invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if share_type not in ('user', 'group'):
                error_msg = 'share_type can only be "user", "group".'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            # unshare repo from user
            if share_type == 'user':
                to_username = request.data.get('username', None)
                if not to_username:
                    error_msg = 'username invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                for repo_id in valid_repo_id_list:

                    if not self.has_shared_to_user(request, repo_id,
                                                   to_username):
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'This item has not been shared to %s.' %
                            to_username
                        })
                        continue

                    repo_owner = get_repo_owner(request, repo_id)
                    try:
                        # get share permission before unshare operation
                        permission = check_user_share_out_permission(
                            repo_id, '/', to_username, is_org_context(request))

                        if is_org_context(request):
                            # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                            org_id = request.user.org.org_id
                            seafile_api.org_remove_share(
                                org_id, repo_id, repo_owner, to_username)
                        else:
                            seafile_api.remove_share(repo_id, repo_owner,
                                                     to_username)

                        # Delete share permission at ExtraSharePermission table.
                        ExtraSharePermission.objects.delete_share_permission(
                            repo_id, to_username)

                        # send message
                        send_perm_audit_msg('delete-repo-perm', username,
                                            to_username, repo_id, '/',
                                            permission)

                        result['success'].append({
                            "repo_id": repo_id,
                            "username": to_username,
                        })
                    except Exception as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'Internal Server Error'
                        })

            # unshare repo from group
            if share_type == 'group':
                to_group_id = request.data.get('group_id', None)
                if not to_group_id:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                try:
                    to_group_id = int(to_group_id)
                except ValueError:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                group = ccnet_api.get_group(to_group_id)
                group_name = group.group_name if group else ''

                for repo_id in valid_repo_id_list:
                    if not self.has_shared_to_group(request, repo_id,
                                                    to_group_id):
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'This item has not been shared to %s.' % group_name
                        })
                        continue

                    try:
                        # get share permission before unshare operation
                        permission = check_group_share_out_permission(
                            repo_id, '/', to_group_id, is_org_context(request))

                        org_id = None
                        if is_org_context(request):
                            org_id = request.user.org.org_id
                            seafile_api.del_org_group_repo(
                                repo_id, org_id, to_group_id)
                        else:
                            seafile_api.unset_group_repo(
                                repo_id, to_group_id, username)

                        # Delete share permission at ExtraSharePermission table.
                        ExtraGroupsSharePermission.objects.delete_share_permission(
                            repo_id, to_group_id)

                        # send message
                        send_perm_audit_msg('delete-repo-perm', username,
                                            to_group_id, repo_id, '/',
                                            permission)

                        result['success'].append({
                            "repo_id": repo_id,
                            "group_id": to_group_id,
                            "group_name": group_name,
                        })
                    except SearpcError as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id':
                            repo_id,
                            'error_msg':
                            'Internal Server Error'
                        })

        return Response(result)
示例#15
0
    def post(self, request):

        # argument check
        operation = request.data.get('operation', None)
        if not operation:
            error_msg = 'operation invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # operation could be `share`, `unshare`, `delete`, `transfer`
        # we now only use `share`, `unshare`
        if operation not in ('share', 'unshare'):
            error_msg = 'operation can only be "share", "unshare".'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []

        username = request.user.username
        repo_id_list = request.data.getlist('repo_id')
        valid_repo_id_list = []

        # filter out invalid repo id
        for repo_id in repo_id_list:

            if not seafile_api.get_repo(repo_id):
                result['failed'].append({
                    'repo_id': repo_id,
                    'error_msg': 'Library %s not found.' % repo_id
                })
                continue

            repo_owner = get_repo_owner(request, repo_id)
            if repo_owner != username and not is_repo_admin(username, repo_id):
                result['failed'].append({
                    'repo_id': repo_id,
                    'error_msg': 'Permission denied.'
                })
                continue

            valid_repo_id_list.append(repo_id)

        # share repo
        if operation == 'share':

            share_type = request.data.get('share_type', None)
            if not share_type:
                error_msg = 'share_type invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if share_type not in ('user', 'group'):
                error_msg = 'share_type can only be "user", "group".'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            permission = request.data.get('permission', 'rw')
            if permission not in get_available_repo_perms():
                error_msg = 'permission invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            # share repo to user
            if share_type == 'user':
                to_username = request.data.get('username', None)
                if not to_username:
                    error_msg = 'username invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                try:
                    User.objects.get(email=to_username)
                except User.DoesNotExist:
                    error_msg = 'User %s not found.' % to_username
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)

                # check if to_user is an org user
                try:
                    org_of_to_user = ccnet_api.get_orgs_by_user(to_username)
                except Exception as e:
                    logger.error(e)
                    org_of_to_user = []

                if is_org_context(request):
                    org_id = request.user.org.org_id
                    org_name = request.user.org.org_name
                    if len(org_of_to_user) == 0 or org_id != org_of_to_user[0].org_id:
                        error_msg = 'User %s is not member of organization %s.' \
                                % (to_username, org_name)
                        return api_error(status.HTTP_403_FORBIDDEN, error_msg)
                else:
                    if len(org_of_to_user) >= 1:
                        error_msg = 'User %s is member of organization %s.' \
                                % (to_username, org_of_to_user[0].org_name)
                        return api_error(status.HTTP_403_FORBIDDEN, error_msg)

                for repo_id in valid_repo_id_list:
                    if self.has_shared_to_user(request, repo_id, to_username):
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'This item has been shared to %s.' % to_username
                            })
                        continue

                    try:
                        org_id = None
                        if is_org_context(request):
                            org_id = request.user.org.org_id
                            seaserv.seafserv_threaded_rpc.org_add_share(org_id,
                                    repo_id, username, to_username, permission)
                        else:
                            seafile_api.share_repo(
                                    repo_id, username, to_username, permission)

                        # send a signal when sharing repo successful
                        repo = seafile_api.get_repo(repo_id)
                        share_repo_to_user_successful.send(sender=None,
                                                           from_user=username,
                                                           to_user=to_username,
                                                           repo=repo, path='/',
                                                           org_id=org_id)

                        result['success'].append({
                            "repo_id": repo_id,
                            "username": to_username,
                            "permission": permission
                        })

                        send_perm_audit_msg('add-repo-perm', username, to_username,
                                            repo_id, '/', permission)
                    except Exception as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'Internal Server Error'
                            })

            # share repo to group
            if share_type == 'group':
                to_group_id = request.data.get('group_id', None)
                if not to_group_id:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                try:
                    to_group_id = int(to_group_id)
                except ValueError:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                group = ccnet_api.get_group(to_group_id)
                if not group:
                    error_msg = 'Group %s not found.' % to_group_id
                    return api_error(status.HTTP_404_NOT_FOUND, error_msg)

                group_name = group.group_name
                if not is_group_member(to_group_id, username):
                    error_msg = 'User %s is not member of group %s.' % (username, group_name)
                    return api_error(status.HTTP_403_FORBIDDEN, error_msg)

                for repo_id in valid_repo_id_list:
                    if self.has_shared_to_group(request, repo_id, to_group_id):
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'This item has been shared to %s.' % group_name
                            })
                        continue

                    try:
                        org_id = None
                        if is_org_context(request):
                            org_id = request.user.org.org_id
                            seafile_api.add_org_group_repo(
                                    repo_id, org_id, to_group_id, username, permission)
                        else:
                            seafile_api.set_group_repo(
                                    repo_id, to_group_id, username, permission)

                        # send a signal when sharing repo successful
                        repo = seafile_api.get_repo(repo_id)
                        share_repo_to_group_successful.send(sender=None,
                                                            from_user=username,
                                                            group_id=to_group_id,
                                                            repo=repo, path='/',
                                                            org_id=org_id)

                        result['success'].append({
                            "repo_id": repo_id,
                            "group_id": to_group_id,
                            "group_name": group_name,
                            "permission": permission
                        })

                        send_perm_audit_msg('add-repo-perm', username, to_group_id,
                                            repo_id, '/', permission)

                    except SearpcError as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'Internal Server Error'
                            })

        # unshare repo
        if operation == 'unshare':

            share_type = request.data.get('share_type', None)
            if not share_type:
                error_msg = 'share_type invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            if share_type not in ('user', 'group'):
                error_msg = 'share_type can only be "user", "group".'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            # unshare repo from user
            if share_type == 'user':
                to_username = request.data.get('username', None)
                if not to_username:
                    error_msg = 'username invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                for repo_id in valid_repo_id_list:

                    if not self.has_shared_to_user(request, repo_id, to_username):
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'This item has not been shared to %s.' % to_username
                            })
                        continue

                    repo_owner = get_repo_owner(request, repo_id)
                    try:
                        # get share permission before unshare operation
                        permission = check_user_share_out_permission(repo_id,
                                '/', to_username, is_org_context(request))

                        if is_org_context(request):
                            # when calling seafile API to share authority related functions, change the uesrname to repo owner.
                            org_id = request.user.org.org_id
                            seafile_api.org_remove_share(org_id, repo_id, repo_owner, to_username)
                        else:
                            seafile_api.remove_share(repo_id, repo_owner, to_username)

                        # Delete share permission at ExtraSharePermission table.
                        ExtraSharePermission.objects.delete_share_permission(repo_id,
                                to_username)

                        # send message
                        send_perm_audit_msg('delete-repo-perm', username,
                                to_username, repo_id, '/', permission)

                        result['success'].append({
                            "repo_id": repo_id,
                            "username": to_username,
                        })
                    except Exception as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'Internal Server Error'
                        })

            # unshare repo from group
            if share_type == 'group':
                to_group_id = request.data.get('group_id', None)
                if not to_group_id:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                try:
                    to_group_id = int(to_group_id)
                except ValueError:
                    error_msg = 'group_id invalid.'
                    return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

                group = ccnet_api.get_group(to_group_id)
                group_name = group.group_name if group else ''

                for repo_id in valid_repo_id_list:
                    if not self.has_shared_to_group(request, repo_id, to_group_id):
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'This item has not been shared to %s.' % group_name
                        })
                        continue

                    try:
                        # get share permission before unshare operation
                        permission = check_group_share_out_permission(repo_id,
                                '/', to_group_id, is_org_context(request))

                        org_id = None
                        if is_org_context(request):
                            org_id = request.user.org.org_id
                            seafile_api.del_org_group_repo(repo_id, org_id, to_group_id)
                        else:
                            seafile_api.unset_group_repo(
                                    repo_id, to_group_id, username)

                        # Delete share permission at ExtraSharePermission table.
                        ExtraGroupsSharePermission.objects.delete_share_permission(repo_id,
                                to_group_id)

                        # send message
                        send_perm_audit_msg('delete-repo-perm', username,
                                to_group_id, repo_id, '/', permission)

                        result['success'].append({
                            "repo_id": repo_id,
                            "group_id": to_group_id,
                            "group_name": group_name,
                        })
                    except SearpcError as e:
                        logger.error(e)
                        result['failed'].append({
                            'repo_id': repo_id,
                            'error_msg': 'Internal Server Error'
                        })

        return Response(result)
示例#16
0
def list_lib_dir(request, repo_id):
    '''
        New ajax API for list library directory
    '''
    content_type = 'application/json; charset=utf-8'
    result = {}

    repo = get_repo(repo_id)
    if not repo:
        err_msg = _('Library does not exist.')
        return HttpResponse(json.dumps({'error': err_msg}),
                            status=400,
                            content_type=content_type)

    username = request.user.username

    path = request.GET.get('p', '/')
    path = normalize_dir_path(path)
    dir_id = seafile_api.get_dir_id_by_path(repo.id, path)
    if not dir_id:
        err_msg = 'Folder not found.'
        return HttpResponse(json.dumps({'error': err_msg}),
                            status=404,
                            content_type=content_type)

    # perm for current dir
    user_perm = check_folder_permission(request, repo_id, path)
    if not user_perm:
        return convert_repo_path_when_can_not_view_folder(
            request, repo_id, path)

    if repo.encrypted \
            and not seafile_api.is_password_set(repo.id, username):
        err_msg = _('Library is encrypted.')
        return HttpResponse(json.dumps({
            'error': err_msg,
            'lib_need_decrypt': True
        }),
                            status=403,
                            content_type=content_type)

    head_commit = get_commit(repo.id, repo.version, repo.head_cmmt_id)
    if not head_commit:
        err_msg = _('Error: no head commit id')
        return HttpResponse(json.dumps({'error': err_msg}),
                            status=500,
                            content_type=content_type)

    dir_list = []
    file_list = []

    dirs = seafserv_threaded_rpc.list_dir_with_perm(repo_id, path, dir_id,
                                                    username, -1, -1)
    starred_files = get_dir_starred_files(username, repo_id, path)

    for dirent in dirs:
        dirent.last_modified = dirent.mtime
        if stat.S_ISDIR(dirent.mode):
            dpath = posixpath.join(path, dirent.obj_name)
            if dpath[-1] != '/':
                dpath += '/'
            dir_list.append(dirent)
        else:
            if repo.version == 0:
                file_size = seafile_api.get_file_size(repo.store_id,
                                                      repo.version,
                                                      dirent.obj_id)
            else:
                file_size = dirent.size
            dirent.file_size = file_size if file_size else 0

            dirent.starred = False
            fpath = posixpath.join(path, dirent.obj_name)
            if fpath in starred_files:
                dirent.starred = True

            file_list.append(dirent)

    if is_org_context(request):
        repo_owner = seafile_api.get_org_repo_owner(repo.id)
    else:
        repo_owner = seafile_api.get_repo_owner(repo.id)

    result["repo_owner"] = repo_owner
    result["is_repo_owner"] = False
    result["has_been_shared_out"] = False
    result["is_admin"] = is_repo_admin(username, repo_id)
    if repo_owner == username:
        result["is_repo_owner"] = True
        try:
            result["has_been_shared_out"] = repo_has_been_shared_out(
                request, repo_id)
        except Exception as e:
            logger.error(e)

    if result["is_admin"]:
        result["has_been_shared_out"] = True

    result["is_virtual"] = repo.is_virtual
    result["repo_name"] = repo.name
    result["user_perm"] = user_perm
    # check quota for fileupload
    result["no_quota"] = True if seaserv.check_quota(repo.id) < 0 else False
    result["encrypted"] = repo.encrypted

    dirent_list = []
    for d in dir_list:
        d_ = {}
        d_['is_dir'] = True
        d_['obj_name'] = d.obj_name
        d_['last_modified'] = d.last_modified
        d_['last_update'] = translate_seahub_time(d.last_modified)
        d_['p_dpath'] = posixpath.join(path, d.obj_name)
        d_['perm'] = d.permission  # perm for sub dir in current dir
        dirent_list.append(d_)

    size = int(request.GET.get('thumbnail_size', THUMBNAIL_DEFAULT_SIZE))

    for f in file_list:
        f_ = {}
        f_['is_file'] = True
        f_['obj_name'] = f.obj_name
        f_['last_modified'] = f.last_modified
        f_['last_update'] = translate_seahub_time(f.last_modified)
        f_['starred'] = f.starred
        f_['file_size'] = filesizeformat(f.file_size)
        f_['obj_id'] = f.obj_id
        f_['perm'] = f.permission  # perm for file in current dir

        if not repo.encrypted and ENABLE_THUMBNAIL:
            # used for providing a way to determine
            # if send a request to create thumbnail.

            fileExt = os.path.splitext(f.obj_name)[1][1:].lower()
            file_type = FILEEXT_TYPE_MAP.get(fileExt)
            if file_type == IMAGE:
                f_['is_img'] = True

            if file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL:
                f_['is_video'] = True

            if file_type == XMIND:
                f_['is_xmind'] = True

            if file_type in (IMAGE, XMIND) or \
                    file_type == VIDEO and ENABLE_VIDEO_THUMBNAIL:
                # if thumbnail has already been created, return its src.
                # Then web browser will use this src to get thumbnail instead of
                # recreating it.
                thumbnail_file_path = os.path.join(THUMBNAIL_ROOT, str(size),
                                                   f.obj_id)
                thumbnail_exist = os.path.exists(thumbnail_file_path)
                if thumbnail_exist:
                    file_path = posixpath.join(path, f.obj_name)
                    src = get_thumbnail_src(repo_id, size, file_path)
                    f_['encoded_thumbnail_src'] = urlquote(src)

        if is_pro_version():
            f_['is_locked'] = True if f.is_locked else False
            f_['lock_owner'] = f.lock_owner
            f_['lock_owner_name'] = email2nickname(f.lock_owner)

            f_['locked_by_me'] = False
            if f.lock_owner == username:
                f_['locked_by_me'] = True

            if f.lock_owner == ONLINE_OFFICE_LOCK_OWNER and \
                    user_perm == PERMISSION_READ_WRITE:
                f_['locked_by_me'] = True

        dirent_list.append(f_)

    result["dirent_list"] = dirent_list

    return HttpResponse(json.dumps(result), content_type=content_type)
示例#17
0
文件: wikis.py 项目: haiwen/seahub
    def post(self, request, format=None):
        """Add a new wiki.
        """
        username = request.user.username

        org_id = -1
        if is_org_context(request):
            org_id = request.user.org.org_id

        repo_id = request.POST.get('repo_id', '')
        if not repo_id:
            msg = 'Repo id is invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, msg)

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # check perm
        if not request.user.permissions.can_publish_repo():
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        is_owner = is_repo_owner(request, repo_id, username)

        if not is_owner:
            repo_admin = is_repo_admin(username, repo_id)

            if not repo_admin:
                is_group_repo_admin = is_group_repo_staff(request, repo_id, username)

                if not is_group_repo_admin:
                    error_msg = _('Permission denied.')
                    return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            wiki = Wiki.objects.add(wiki_name=repo.repo_name, username=username,
                    repo_id=repo.repo_id, org_id=org_id, permission='public')
        except DuplicateWikiNameError:
            msg = _('%s is taken by others, please try another name.') % repo.repo_name
            return api_error(status.HTTP_400_BAD_REQUEST, msg)
        except IntegrityError:
            msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

        # create home page if not exist
        page_name = "home.md"
        if not seafile_api.get_file_id_by_path(repo_id, "/" + page_name):
            try:
                seafile_api.post_empty_file(repo_id, '/', page_name, username)
            except SearpcError as e:
                logger.error(e)
                msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

        fs = FileShare.objects.get_dir_link_by_path(username, repo_id, '/')
        if not fs:
            fs = FileShare.objects.create_dir_link(username, repo_id, '/',
                    permission='view_download', org_id=org_id)

        return Response(wiki.to_dict())
示例#18
0
文件: wikis.py 项目: luojun13/seahub
    def post(self, request, format=None):
        """Add a new wiki.
        """
        use_exist_repo = request.POST.get('use_exist_repo', '')
        if not use_exist_repo:
            msg = 'Use exist repo is invalid'
            return api_error(status.HTTP_400_BAD_REQUEST, msg)

        name = request.POST.get('name', '')
        if not name:
            msg = 'Name is invalid'
            return api_error(status.HTTP_400_BAD_REQUEST, msg)

        if not is_valid_wiki_name(name):
            msg = _(
                'Name can only contain letters, numbers, blank, hyphen or underscore.'
            )
            return api_error(status.HTTP_400_BAD_REQUEST, msg)

        username = request.user.username

        org_id = -1
        if is_org_context(request):
            org_id = request.user.org.org_id

        if use_exist_repo == 'false':
            try:
                wiki = Wiki.objects.add(name, username, org_id=org_id)
            except DuplicateWikiNameError:
                msg = _(
                    '%s is taken by others, please try another name.') % name
                return api_error(status.HTTP_400_BAD_REQUEST, msg)
            except IntegrityError:
                msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

            # create home page
            page_name = "home.md"
            try:
                seafile_api.post_empty_file(wiki.repo_id, '/', page_name,
                                            request.user.username)
            except SearpcError as e:
                logger.error(e)
                msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

            return Response(wiki.to_dict())

        if use_exist_repo == 'true':
            repo_id = request.POST.get('repo_id', '')
            if not repo_id:
                msg = 'Repo id is invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, msg)

            repo = seafile_api.get_repo(repo_id)
            if not repo:
                error_msg = 'Library %s not found.' % repo_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

            # check perm
            is_owner = is_repo_owner(request, repo_id, username)

            if not is_owner:
                repo_admin = is_repo_admin(username, repo_id)

                if not repo_admin:
                    is_group_repo_admin = is_group_repo_staff(
                        request, repo_id, username)

                    if not is_group_repo_admin:
                        error_msg = _('Permission denied.')
                        return api_error(status.HTTP_403_FORBIDDEN, error_msg)

            try:
                wiki = Wiki.objects.add(wiki_name=repo.repo_name,
                                        username=username,
                                        repo_id=repo.repo_id,
                                        org_id=org_id)
            except DuplicateWikiNameError:
                msg = _('%s is taken by others, please try another name.'
                        ) % repo.repo_name
                return api_error(status.HTTP_400_BAD_REQUEST, msg)
            except IntegrityError:
                msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, msg)

            # create home page if not exist
            page_name = "home.md"
            if not seafile_api.get_file_id_by_path(repo_id, "/" + page_name):
                try:
                    seafile_api.post_empty_file(repo_id, '/', page_name,
                                                username)
                except SearpcError as e:
                    logger.error(e)
                    msg = 'Internal Server Error'
                    return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                                     msg)

            return Response(wiki.to_dict())