def share_to_group(request, repo, group, permission): """Share repo to group with given permission. """ repo_id = repo.id group_id = group.id group_name = group.group_name from_user = request.user.username if is_org_context(request): org_id = request.user.org.org_id group_repo_ids = seafile_api.get_org_group_repoids(org_id, group.id) else: group_repo_ids = seafile_api.get_group_repoids(group.id) if repo.id in group_repo_ids: msg = _(u'"%(repo)s" is already in group %(group)s. <a href="%(href)s">View</a>') % { 'repo': repo.name, 'group': group.group_name, 'href': reverse('group_info', args=[group.id])} messages.error(request, msg) return try: if is_org_context(request): org_id = request.user.org.org_id seafile_api.add_org_group_repo(repo_id, org_id, group_id, from_user, permission) else: seafile_api.set_group_repo(repo_id, group_id, from_user, permission) except Exception, e: logger.error(e) msg = _(u'Failed to share %(repo)s to %(group)s, please try again later.') % \ {'repo': repo.name, 'group': group_name} messages.error(request, msg)
def share_to_user(request, repo, to_user, permission): """Share repo to a user with given permission. """ repo_id = repo.id from_user = request.user.username if from_user == to_user: return False # permission check if is_org_context(request): org_id = request.user.org.org_id if not seaserv.ccnet_threaded_rpc.org_user_exists(org_id, to_user): return False else: if not is_registered_user(to_user): return False try: if is_org_context(request): org_id = request.user.org.org_id org_share_repo(org_id, repo_id, from_user, to_user, permission) else: seafile_api.share_repo(repo_id, from_user, to_user, permission) except SearpcError as e: return False logger.error(e) else: # send a signal when sharing repo successful share_repo_to_user_successful.send(sender=None, from_user=from_user, to_user=to_user, repo=repo) return True
def share_to_group(request, repo, group, permission): """Share repo to group with given permission. """ repo_id = repo.id group_id = group.id from_user = request.user.username if is_org_context(request): org_id = request.user.org.org_id group_repo_ids = seafile_api.get_org_group_repoids(org_id, group.id) else: group_repo_ids = seafile_api.get_group_repoids(group.id) if repo.id in group_repo_ids: return False try: if is_org_context(request): org_id = request.user.org.org_id seafile_api.add_org_group_repo(repo_id, org_id, group_id, from_user, permission) else: seafile_api.set_group_repo(repo_id, group_id, from_user, permission) return True except Exception, e: logger.error(e) return False
def get(self, request, format=None): """ List all shared out folders. Permission checking: 1. all authenticated user can perform this action. """ shared_repos = [] username = request.user.username try: if is_org_context(request): org_id = request.user.org.org_id shared_repos += seafile_api.get_org_share_out_repo_list(org_id, username, -1, -1) shared_repos += seaserv.seafserv_threaded_rpc.get_org_group_repos_by_owner(org_id, username) else: shared_repos += seafile_api.get_share_out_repo_list(username, -1, -1) shared_repos += seafile_api.get_group_repos_by_owner(username) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) returned_result = [] shared_repos.sort(lambda x, y: cmp(x.repo_name, y.repo_name)) for repo in shared_repos: if not repo.is_virtual: continue result = {} result['repo_id'] = repo.origin_repo_id result['repo_name'] = repo.origin_repo_name result['path'] = repo.origin_path result['folder_name'] = repo.name result['share_type'] = repo.share_type result['share_permission'] = repo.permission if repo.share_type == 'personal': result['user_name'] = email2nickname(repo.user) result['user_email'] = repo.user result['contact_email'] = Profile.objects.get_contact_email_by_user(repo.user) if repo.share_type == 'group': group = ccnet_api.get_group(repo.group_id) if not group: if is_org_context(request): seafile_api.org_unshare_subdir_for_group(org_id, repo.repo_id, repo.origin_path, username, repo.group_id) else: seafile_api.unshare_subdir_for_group( repo.repo_id, repo.origin_path, username, repo.group_id) continue result['group_id'] = repo.group_id result['group_name'] = group.group_name returned_result.append(result) return Response(returned_result)
def unsetinnerpub(request, repo_id): """Unshare repos in organization or in share admin page. Only system admin, organization admin or repo owner can perform this op. """ repo = get_repo(repo_id) perm = request.GET.get('permission', None) if perm is None: return render_error(request, _(u'Argument is not valid')) if not repo: messages.error(request, _('Failed to unshare the library, as it does not exist.')) return HttpResponseRedirect(reverse('share_admin')) # permission check username = request.user.username if is_org_context(request): org_id = request.user.org.org_id repo_owner = seafile_api.get_org_repo_owner(repo.id) is_repo_owner = True if repo_owner == username else False if not (request.user.org.is_staff or is_repo_owner): raise Http404 else: repo_owner = seafile_api.get_repo_owner(repo.id) is_repo_owner = True if repo_owner == username else False if not (request.user.is_staff or is_repo_owner): raise Http404 try: if is_org_context(request): org_id = request.user.org.org_id seaserv.seafserv_threaded_rpc.unset_org_inner_pub_repo(org_id, repo.id) else: seaserv.unset_inner_pub_repo(repo.id) origin_repo_id, origin_path = get_origin_repo_info(repo.id) if origin_repo_id is not None: perm_repo_id = origin_repo_id perm_path = origin_path else: perm_repo_id = repo.id perm_path = '/' send_perm_audit_msg('delete-repo-perm', username, 'all', perm_repo_id, perm_path, perm) messages.success(request, _('Unshare "%s" successfully.') % repo.name) except SearpcError: messages.error(request, _('Failed to unshare "%s".') % repo.name) referer = request.META.get('HTTP_REFERER', None) next = settings.SITE_ROOT if referer is None else referer return HttpResponseRedirect(next)
def get_shared_link(request): """ Handle ajax request to generate file or dir shared link. """ content_type = 'application/json; charset=utf-8' repo_id = request.GET.get('repo_id', '') share_type = request.GET.get('type', 'f') # `f` or `d` path = request.GET.get('p', '') use_passwd = True if int(request.POST.get('use_passwd', '0')) == 1 else False passwd = request.POST.get('passwd') if use_passwd else None try: expire_days = int(request.POST.get('expire_days', 0)) except ValueError: expire_days = 0 if expire_days <= 0: expire_date = None else: expire_date = timezone.now() + relativedelta(days=expire_days) if not (repo_id and path): err = _('Invalid arguments') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) if share_type != 'f' and path == '/': err = _('You cannot share the library in this way.') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) username = request.user.username if share_type == 'f': fs = FileShare.objects.get_file_link_by_path(username, repo_id, path) if fs is None: fs = FileShare.objects.create_file_link(username, repo_id, path, passwd, expire_date) if is_org_context(request): org_id = request.user.org.org_id OrgFileShare.objects.set_org_file_share(org_id, fs) else: fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path) if fs is None: fs = FileShare.objects.create_dir_link(username, repo_id, path, passwd, expire_date) if is_org_context(request): org_id = request.user.org.org_id OrgFileShare.objects.set_org_file_share(org_id, fs) token = fs.token shared_link = gen_shared_link(token, fs.s_type) data = json.dumps({'token': token, 'shared_link': shared_link}) return HttpResponse(data, status=200, content_type=content_type)
def list_group_shared_items(self, request, repo_id, path): username = request.user.username if is_org_context(request): org_id = request.user.org.org_id if path == '/': share_items = seafile_api.list_org_repo_shared_group(org_id, username, repo_id) else: share_items = seafile_api.get_org_shared_groups_for_subdir(org_id, repo_id, path, username) else: if path == '/': share_items = seafile_api.list_repo_shared_group_by_user(username, repo_id) else: share_items = seafile_api.get_shared_groups_for_subdir(repo_id, path, username) ret = [] for item in share_items: ret.append({ "share_type": "group", "group_info": { "id": item.group_id, "name": seaserv.get_group(item.group_id).group_name, }, "permission": item.perm, }) return ret
def get(self, request): """ List groups that user can share a library to. """ if config.ENABLE_SHARE_TO_ALL_GROUPS: if CUSTOM_GET_GROUPS: groups = custom_get_groups(request) else: groups = ccnet_api.get_all_groups(-1, -1) else: username = request.user.username if is_org_context(request): org_id = request.user.org.org_id groups = ccnet_api.get_org_groups_by_user(org_id, username) else: groups = ccnet_api.get_groups(username) try: avatar_size = int(request.GET.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE)) except ValueError: avatar_size = GROUP_AVATAR_DEFAULT_SIZE result = [self._get_group_info(request, group, avatar_size) for group in groups] return Response(result)
def repo_has_been_shared_out(request, repo_id): has_been_shared_out = False username = request.user.username if is_org_context(request): org_id = request.user.org.org_id is_inner_org_pub_repo = False # check if current repo is pub-repo org_pub_repos = seafile_api.list_org_inner_pub_repos_by_owner( org_id, username) for org_pub_repo in org_pub_repos: if repo_id == org_pub_repo.id: is_inner_org_pub_repo = True break if seafile_api.org_repo_has_been_shared(repo_id, including_groups=True) or is_inner_org_pub_repo: has_been_shared_out = True else: if seafile_api.repo_has_been_shared(repo_id, including_groups=True) or \ (not request.cloud_mode and seafile_api.is_inner_pub_repo(repo_id)): has_been_shared_out = True return has_been_shared_out
def rename_group_with_new_name(request, group_id, new_group_name): """Rename a group with new name. Arguments: - `request`: - `group_id`: - `new_group_name`: Raises: BadGroupNameError: New group name format is not valid. ConflictGroupNameError: New group name confilicts with existing name. """ if not validate_group_name(new_group_name): raise BadGroupNameError # Check whether group name is duplicated. username = request.user.username org_id = -1 if is_org_context(request): org_id = request.user.org.org_id checked_groups = seaserv.get_org_groups_by_user(org_id, username) else: if request.cloud_mode: checked_groups = seaserv.get_personal_groups_by_user(username) else: checked_groups = get_all_groups(-1, -1) for g in checked_groups: if g.group_name == new_group_name: raise ConflictGroupNameError ccnet_threaded_rpc.set_group_name(group_id, new_group_name)
def get_group_repos_by_owner(request): username = request.user.username if is_org_context(request): org_id = request.user.org.org_id return get_org_group_repos_by_owner(org_id, username) else: return seaserv.get_group_repos_by_owner(username)
def get_unencry_rw_repos_by_user(request): """Get all unencrypted repos a logged-in user can read and write. """ username = request.user.username if not username: return [] def has_repo(repos, repo): for r in repos: if repo.id == r.id: return True return False org_id = request.user.org.org_id if is_org_context(request) else None owned_repos, shared_repos, groups_repos, public_repos = get_user_repos( username, org_id=org_id) accessible_repos = [] for r in owned_repos: if not has_repo(accessible_repos, r) and not r.encrypted: accessible_repos.append(r) for r in shared_repos + groups_repos + public_repos: if not has_repo(accessible_repos, r) and not r.encrypted: if check_folder_permission(request, r.id, '/') == 'rw': accessible_repos.append(r) return accessible_repos
def delete(self, request, repo_id, org_id, format=None): """ Delete repo user share permission. Permission checking: 1. is group admin """ # parameter check to_user = request.data.get('username', None) if not to_user: error_msg = 'username invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check repo_owner = get_repo_owner(request, repo_id) group_id = get_group_id_by_repo_owner(repo_owner) username = request.user.username if not is_group_admin(group_id, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) path = request.data.get('path', '/') SeafileAPI.delete_shared_user_by_repo_path( repo_id, repo_owner, to_user, path, org_id=org_id) permission = check_user_share_out_permission(repo_id, path, to_user, is_org_context(request)) send_perm_audit_msg('delete-repo-perm', username, to_user, repo_id, path, permission) return Response({'success': True})
def list_user_shared_items(self, request, repo_id, path): username = request.user.username if is_org_context(request): org_id = request.user.org.org_id if path == '/': share_items = seafile_api.list_org_repo_shared_to(org_id, username, repo_id) else: share_items = seafile_api.get_org_shared_users_for_subdir(org_id, repo_id, path, username) else: if path == '/': share_items = seafile_api.list_repo_shared_to(username, repo_id) else: share_items = seafile_api.get_shared_users_for_subdir(repo_id, path, username) ret = [] for item in share_items: ret.append({ "share_type": "user", "user_info": { "name": item.user, "nickname": email2nickname(item.user), }, "permission": item.perm, }) return ret
def repo_online_gc(request, repo_id): if request.method != 'POST': raise Http404 repo = get_repo(repo_id) if not repo: raise Http404 referer = request.META.get('HTTP_REFERER', None) next = settings.SITE_ROOT if referer is None else referer 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) is_repo_owner = True if repo_owner == username else False if not is_repo_owner: messages.error(request, _('Permission denied')) return HttpResponseRedirect(next) day = int(request.POST.get('day')) try: seafile_api.clean_up_repo_history(repo.id, day) except SearpcError as e: logger.error(e) messages.error(request, _('Internal server error')) return HttpResponseRedirect(next) return HttpResponseRedirect(next)
def get(self, request): """ List all groups. """ org_id = None username = request.user.username if is_org_context(request): org_id = request.user.org.org_id user_groups = seaserv.get_org_groups_by_user(org_id, username) else: user_groups = seaserv.get_personal_groups_by_user(username) try: size = int(request.GET.get('avatar_size', GROUP_AVATAR_DEFAULT_SIZE)) except ValueError: size = GROUP_AVATAR_DEFAULT_SIZE try: with_repos = int(request.GET.get('with_repos', 0)) except ValueError: with_repos = 0 if with_repos not in (0, 1): error_msg = _(u'Argument can only be 0 or 1') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) groups = [] for g in user_groups: group_info = get_group_info(request, g.id , size) if with_repos: if org_id: group_repos = seafile_api.get_org_group_repos(org_id, g.id) else: group_repos = seafile_api.get_repos_by_group(g.id) repos = [] for r in group_repos: repo = { "id": r.id, "name": r.name, "desc": r.desc, "size": r.size, "size_formatted": filesizeformat(r.size), "mtime": r.last_modified, "mtime_relative": translate_seahub_time(r.last_modified), "encrypted": r.encrypted, "permission": r.permission, "owner": r.user, "owner_nickname": email2nickname(r.user), "share_from_me": True if username == r.user else False, } repos.append(repo) group_info['repos'] = repos groups.append(group_info) return Response(groups)
def post(self, request): """Add a group in address book. parent_group: -1 - no parent group; > 0 - have parent group. group_owner: default to system admin group_staff: default to system admin """ group_name = request.data.get('group_name', '').strip() if not group_name: error_msg = 'name %s invalid.' % group_name return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _(u'Name can only contain letters, numbers, blank, hyphen or underscore.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _(u'The name already exists.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Group owner is 'system admin' group_owner = request.data.get('group_owner', '') try: parent_group = int(request.data.get('parent_group', -1)) except ValueError: error_msg = 'parent_group invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if parent_group < 0 and parent_group != -1: error_msg = 'parent_group invalid' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # TODO: check parent group exists try: if is_org_context(request): # request called by org admin org_id = request.user.org.org_id group_id = ccnet_api.create_org_group( org_id, group_name, group_owner, parent_group_id=parent_group) else: group_id = ccnet_api.create_group(group_name, group_owner, parent_group_id=parent_group) seafile_api.set_group_quota(group_id, -2) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # get info of new group group_info = address_book_group_to_dict(group_id) return Response(group_info, status=status.HTTP_200_OK)
def group_add(request): """Add a new group""" if request.method != 'POST': raise Http404 username = request.user.username result = {} content_type = 'application/json; charset=utf-8' user_can_add_group = request.user.permissions.can_add_group() if not user_can_add_group: result['error'] = _(u'You do not have permission to create group.') return HttpResponse(json.dumps(result), status=403, content_type=content_type) # check plan num_of_groups = getattr(request.user, 'num_of_groups', -1) if num_of_groups > 0: current_groups = len(request.user.joined_groups) if current_groups > num_of_groups: result['error'] = _(u'You can only create %d groups.<a href="http://seafile.com/">Upgrade account.</a>') % num_of_groups return HttpResponse(json.dumps(result), status=403, content_type=content_type) form = GroupAddForm(request.POST) if form.is_valid(): group_name = form.cleaned_data['group_name'] # Check whether group name is duplicated. org_id = -1 if is_org_context(request): org_id = request.user.org.org_id checked_groups = seaserv.get_org_groups_by_user(org_id, username) else: if request.cloud_mode: checked_groups = seaserv.get_personal_groups_by_user(username) else: checked_groups = get_all_groups(-1, -1) for g in checked_groups: if g.group_name == group_name: result['error'] = _(u'There is already a group with that name.') return HttpResponse(json.dumps(result), status=400, content_type=content_type) # Group name is valid, create that group. try: if org_id > 0: create_org_group(org_id, group_name, username) else: create_group(group_name, username) return HttpResponse(json.dumps({'success': True}), content_type=content_type) except SearpcError, e: result['error'] = _(e.msg) return HttpResponse(json.dumps(result), status=500, content_type=content_type)
def get_inner_pub_repo_list(request): username = request.user.username if is_org_context(request): org_id = request.user.org.org_id return list_org_inner_pub_repos_by_owner(org_id, username) elif request.cloud_mode: return seaserv.list_inner_pub_repos_by_owner(username) else: return []
def get_owned_repo_list(request): """List owned repos. """ username = request.user.username if is_org_context(request): org_id = request.user.org.org_id return seafile_api.get_org_owned_repo_list(org_id, username) else: return seafile_api.get_owned_repo_list(username)
def get_shared_link(request): """ Handle ajax request to generate file or dir shared link. """ if not request.is_ajax(): raise Http404 content_type = 'application/json; charset=utf-8' repo_id = request.GET.get('repo_id', '') share_type = request.GET.get('type', 'f') # `f` or `d` path = request.GET.get('p', '') if not (repo_id and path): err = _('Invalid arguments') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) if share_type != 'f' and path == '/': err = _('You cannot share the library in this way.') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) username = request.user.username if share_type == 'f': fs = FileShare.objects.get_file_link_by_path(username, repo_id, path) if fs is None: fs = FileShare.objects.create_file_link(username, repo_id, path) if is_org_context(request): org_id = request.user.org.org_id OrgFileShare.objects.set_org_file_share(org_id, fs) else: fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path) if fs is None: fs = FileShare.objects.create_dir_link(username, repo_id, path) if is_org_context(request): org_id = request.user.org.org_id OrgFileShare.objects.set_org_file_share(org_id, fs) token = fs.token shared_link = gen_shared_link(token, fs.s_type) data = json.dumps({'token': token, 'shared_link': shared_link}) return HttpResponse(data, status=200, content_type=content_type)
def share_permission_admin(request): """Change repo share permission in ShareAdmin. """ share_type = request.GET.get('share_type', '') content_type = 'application/json; charset=utf-8' form = RepoShareForm(request.POST) form.is_valid() email_or_group = form.cleaned_data['email_or_group'] repo_id = form.cleaned_data['repo_id'] permission = form.cleaned_data['permission'] from_email = request.user.username if share_type == 'personal': if not is_valid_username(email_or_group): return HttpResponse(json.dumps({'success': False}), status=400, content_type=content_type) try: seafile_api.set_share_permission(repo_id, from_email, email_or_group, permission) except SearpcError: return HttpResponse(json.dumps({'success': False}), status=500, content_type=content_type) return HttpResponse(json.dumps({'success': True}), content_type=content_type) elif share_type == 'group': try: seafile_api.set_group_repo_permission(int(email_or_group), repo_id, permission) except SearpcError: return HttpResponse(json.dumps({'success': False}), status=500, content_type=content_type) return HttpResponse(json.dumps({'success': True}), content_type=content_type) elif share_type == 'public': try: if is_org_context(request): org_id = request.user.org.org_id seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo( org_id, repo_id, permission) else: seafile_api.add_inner_pub_repo(repo_id, permission) except SearpcError: return HttpResponse(json.dumps({'success': False}), status=500, content_type=content_type) return HttpResponse(json.dumps({'success': True}), content_type=content_type) else: return HttpResponse(json.dumps({'success': False}), status=400, content_type=content_type)
def share_to_user(request, repo, to_user, permission): """Share repo to a user with given permission. """ repo_id = repo.id from_user = request.user.username if from_user == to_user: msg = _(u'You can not share libray to yourself.') messages.error(request, msg) return # permission check if is_org_context(request): org_id = request.user.org.org_id if not seaserv.ccnet_threaded_rpc.org_user_exists(org_id, to_user): msg = _(u'Failed to share to %s, user is not found.') % to_user messages.error(request, msg) return else: if not is_registered_user(to_user): msg = _(u'Failed to share to %s, as the email is not registered.') % to_user messages.error(request, msg) return try: if is_org_context(request): org_id = request.user.org.org_id org_share_repo(org_id, repo_id, from_user, to_user, permission) else: seafile_api.share_repo(repo_id, from_user, to_user, permission) except SearpcError as e: logger.error(e) msg = _(u'Failed to share to %s, please try again later.') % to_user messages.error(request, msg) else: # send a signal when sharing repo successful share_repo_to_user_successful.send(sender=None, from_user=from_user, to_user=to_user, repo=repo) msg = _(u'Shared to %(email)s successfully, go check it at <a href="%(share)s">Shares</a>.') % \ {'email': to_user, 'share': reverse('share_admin')} messages.success(request, msg)
def get_repo_owner(request, repo_id): if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo_id) else: # for admin panel # administrator may get org repo's owner repo_owner = seafile_api.get_repo_owner(repo_id) if not repo_owner: repo_owner = seafile_api.get_org_repo_owner(repo_id) return repo_owner
def create_group_repo(request, group_id): """Create a repo and share it to current group""" content_type = 'application/json; charset=utf-8' def json_error(err_msg): result = {'error': err_msg} return HttpResponseBadRequest(json.dumps(result), content_type=content_type) group_id = int(group_id) group = get_group(group_id) if not group: return json_error(_(u'Failed to create: the group does not exist.')) # Check whether user belongs to the group. username = request.user.username if not is_group_user(group_id, username): return json_error(_(u'Failed to create: you are not in the group.')) form = SharedRepoCreateForm(request.POST) if not form.is_valid(): return json_error(str(form.errors.values()[0])) # Form is valid, create group repo repo_name = form.cleaned_data['repo_name'] repo_desc = form.cleaned_data['repo_desc'] permission = form.cleaned_data['permission'] encryption = int(form.cleaned_data['encryption']) uuid = form.cleaned_data['uuid'] magic_str = form.cleaned_data['magic_str'] encrypted_file_key = form.cleaned_data['encrypted_file_key'] if is_org_context(request): org_id = request.user.org.org_id try: if encryption: repo_id = seafile_api.create_org_enc_repo( uuid, repo_name, repo_desc, username, magic_str, encrypted_file_key, enc_version=2, org_id=org_id) else: repo_id = seafile_api.create_org_repo(repo_name, repo_desc, username, None, org_id) except SearpcError, e: logger.error(e) return json_error(_(u'Failed to create')) try: seafile_api.add_org_group_repo(repo_id, org_id, group.id, username, permission) except SearpcError, e: logger.error(e) return json_error(_(u'Failed to create: internal error.'))
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})
def list_inner_pub_repos(request): """List inner pub repos. """ username = request.user.username if is_org_context(request): org_id = request.user.org.org_id return seaserv.list_org_inner_pub_repos(org_id, username) if not request.cloud_mode: return seaserv.list_inner_pub_repos(username) return []
def get_group_repos_by_owner(request): """List repos that @user share to groups. Returns: A list of repos. """ username = request.user.username if is_org_context(request): org_id = request.user.org.org_id return get_org_group_repos_by_owner(org_id, username) else: return seaserv.get_group_repos_by_owner(username)
def repo_remove_share(request): """ If repo is shared from one person to another person, only these two peson can remove share. If repo is shared from one person to a group, then only the one share the repo and group staff can remove share. """ repo_id = request.GET.get('repo_id', '') group_id = request.GET.get('gid', '') from_email = request.GET.get('from', '') if not is_valid_username(from_email): return render_error(request, _(u'Argument is not valid')) username = request.user.username # if request params don't have 'gid', then remove repos that share to # to other person; else, remove repos that share to groups if not group_id: to_email = request.GET.get('to', '') if not is_valid_username(to_email): return render_error(request, _(u'Argument is not valid')) if username != from_email and username != to_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_context(request): org_id = request.user.org.org_id org_remove_share(org_id, repo_id, from_email, to_email) else: seaserv.remove_share(repo_id, from_email, to_email) else: try: group_id = int(group_id) except: return render_error(request, _(u'group id is not valid')) group = seaserv.get_group(group_id) if not group: return render_error(request, _(u"Failed to unshare: the group doesn't exist.")) if not seaserv.check_group_staff(group_id, username) \ and username != from_email: return render_permission_error(request, _(u'Failed to remove share')) if is_org_group(group_id): org_id = get_org_id_by_group(group_id) del_org_group_repo(repo_id, org_id, group_id) else: seafile_api.unset_group_repo(repo_id, group_id, from_email) messages.success(request, _('Successfully removed share')) next = request.META.get('HTTP_REFERER', SITE_ROOT) return HttpResponseRedirect(next)
def render_recycle_root(request, repo_id): repo = get_repo(repo_id) if not repo: raise Http404 scan_stat = request.GET.get('scan_stat', None) try: deleted_entries = seafile_api.get_deleted(repo_id, 0, '/', scan_stat) except SearpcError as e: logger.error(e) referer = request.META.get('HTTP_REFERER', None) next = settings.SITE_ROOT if referer is None else referer return HttpResponseRedirect(next) if not deleted_entries: new_scan_stat = None else: new_scan_stat = deleted_entries[-1].scan_stat trash_more = True if new_scan_stat is not None else False deleted_entries = deleted_entries[0:-1] for dirent in deleted_entries: if stat.S_ISDIR(dirent.mode): dirent.is_dir = True else: dirent.is_dir = False # Entries sort by deletion time in descending order. deleted_entries.sort(lambda x, y : cmp(y.delete_time, x.delete_time)) 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) is_repo_owner = True if repo_owner == username else False enable_clean = False if is_repo_owner: enable_clean = True return render_to_response('repo_dir_recycle_view.html', { 'show_recycle_root': True, 'repo': repo, 'repo_dir_name': repo.name, 'dir_entries': deleted_entries, 'scan_stat': new_scan_stat, 'trash_more': trash_more, 'enable_clean': enable_clean, }, context_instance=RequestContext(request))
def get_or_create_sub_repo_by_path(self, request, repo, path): username = request.user.username sub_repo = self.get_sub_repo_by_path(request, repo, path) if not sub_repo: name = os.path.basename(path) # create a sub-lib, # use name as 'repo_name' & 'repo_desc' for sub_repo if is_org_context(request): org_id = request.user.org.org_id sub_repo_id = seaserv.seafserv_threaded_rpc.create_org_virtual_repo( org_id, repo.id, path, name, name, username) else: sub_repo_id = seafile_api.create_virtual_repo( repo.id, path, name, name, username) sub_repo = seafile_api.get_repo(sub_repo_id) return sub_repo
def delete_user_account(request): username = request.user.username if username == '*****@*****.**': messages.error(request, _(u'Demo account can not be deleted.')) next = request.META.get('HTTP_REFERER', settings.SITE_ROOT) return HttpResponseRedirect(next) user = User.objects.get(email=username) user.delete() clear_token(username) if is_org_context(request): org_id = request.user.org.org_id seaserv.ccnet_threaded_rpc.remove_org_user(org_id, username) return HttpResponseRedirect(settings.LOGIN_URL)
def get_group_repos(request, groups): """Get repos shared to groups. """ group_repos = [] if is_org_context(request): org_id = request.user.org.org_id # For each group I joined... for grp in groups: # Get group repos, and for each group repos... for r_id in seafile_api.get_org_group_repoids(org_id, grp.id): repo_owner = seafile_api.get_org_repo_owner(r_id) # Convert repo properties due to the different collumns in Repo # and SharedRepo r = get_repo(r_id) if not r: continue r.repo_id = r.id r.repo_name = r.name r.repo_desc = r.desc r.last_modified = get_repo_last_modify(r) r.share_type = 'group' r.user = repo_owner r.user_perm = check_folder_permission(request, r_id, '/') r.group = grp group_repos.append(r) else: # For each group I joined... for grp in groups: # Get group repos, and for each group repos... for r_id in seafile_api.get_group_repoids(grp.id): repo_owner = seafile_api.get_repo_owner(r_id) # Convert repo properties due to the different collumns in Repo # and SharedRepo r = get_repo(r_id) if not r: continue r.repo_id = r.id r.repo_name = r.name r.repo_desc = r.desc r.last_modified = get_repo_last_modify(r) r.share_type = 'group' r.user = repo_owner r.user_perm = check_folder_permission(request, r_id, '/') r.group = grp group_repos.append(r) return group_repos
def share_to_public(request, repo, permission): """Share repo to public with given permission. """ try: if is_org_context(request): org_id = request.user.org.org_id seaserv.seafserv_threaded_rpc.set_org_inner_pub_repo( org_id, repo.id, permission) elif request.cloud_mode: return # no share to public in cloud mode else: seafile_api.add_inner_pub_repo(repo.id, permission) except Exception, e: logger.error(e) messages.error( request, _(u'Failed to share to all members, please try again later.'))
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. Also remove all passwords used to decrypt repos. """ request.session.flush() if hasattr(request, 'user'): from seahub.base.accounts import User if isinstance(request.user, User): if is_org_context(request): org_id = request.user.org.org_id request.user.remove_org_repo_passwds(org_id) else: request.user.remove_repo_passwds() from seahub.auth.models import AnonymousUser request.user = AnonymousUser()
def delete(self, request, repo_id): repo = seafile_api.get_repo(repo_id) if not repo: # for case of `seafile-data` has been damaged # no `repo object` will be returned from seafile api # delete the database record anyway try: seafile_api.remove_repo(repo_id) 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}) # check permission username = request.user.username repo_owner = get_repo_owner(request, repo_id) if username != repo_owner: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check repo status repo_status = repo.status if repo_status != 0: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) org_id = None if is_org_context(request): org_id = request.user.org.org_id # remove repo seafile_api.remove_repo(repo_id) repo_deleted.send(sender=None, org_id=org_id, operator=username, repo_owner=repo_owner, repo_id=repo_id, repo_name=repo.name) return Response('success', status=status.HTTP_200_OK)
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})
def _decorated(view, request, repo_id, *args, **kwargs): 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 permission 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) username = request.user.username if repo.is_virtual or username != repo_owner: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) return func(view, request, repo_id, *args, **kwargs)
def delete(self, request, group_id): """ Delete a specific group """ username = request.user.username org_id = None if is_org_context(request): org_id = request.user.org.org_id try: remove_group_common(group_id, username, org_id=org_id) except SearpcError as e: logger.error(e) error_msg = _(u'Internal Server Error') return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return Response({'success': True})
def get(self, request, format=None): """List all wikis. """ # parse request params filter_by = { 'mine': False, 'shared': False, 'group': False, 'org': False, } rtype = request.GET.get('type', "") if not rtype: # set all to True, no filter applied filter_by = filter_by.fromkeys(filter_by.iterkeys(), True) for f in rtype.split(','): f = f.strip() filter_by[f] = True username = request.user.username org_id = request.user.org.org_id if is_org_context(request) else None (owned, shared, groups, public) = get_user_repos(username, org_id) filter_repo_ids = [] if filter_by['mine']: filter_repo_ids += ([r.id for r in owned]) if filter_by['shared']: filter_repo_ids += ([r.id for r in shared]) if filter_by['group']: filter_repo_ids += ([r.id for r in groups]) if filter_by['org']: filter_repo_ids += ([r.id for r in public]) filter_repo_ids = list(set(filter_repo_ids)) ret = [ x.to_dict() for x in Wiki.objects.filter(repo_id__in=filter_repo_ids) ] return Response({'data': ret})
def _decorated(view, request, repo_id, *args, **kwargs): 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 permission 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) username = request.user.username if repo.is_virtual or username != repo_owner: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # check arguments group_id = request.data.get('group_id', None) path = request.data.get('folder_path', None) perm = request.data.get('permission', None) try: group_id = int(group_id) except ValueError: error_msg = 'group_id invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if not seaserv.get_group(group_id): error_msg = 'Group %s not found.' % group_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) if path: path = path.rstrip('/') if path != '/' else path if seafile_api.get_dir_id_by_path(repo_id, path) is None: error_msg = 'Folder %s not found.' % path return api_error(status.HTTP_404_NOT_FOUND, error_msg) if request.method in ('POST', 'PUT') and perm not in ('r', 'rw'): error_msg = 'permission invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) return func(view, request, repo_id, *args, **kwargs)
def post(self, request, group_id): """ Add a group member. """ username = request.user.username # only group owner/admin can add a group member if not is_group_admin_or_owner(group_id, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) email = request.data.get('email', None) try: User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: if is_group_member(group_id, email): error_msg = _('User %s is already a group member.' ) % email2nickname(email) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if is_org_context(request): org_id = request.user.org.org_id if not ccnet_api.org_user_exists(org_id, email): error_msg = _('User %s not found in organization.' ) % email2nickname(email) return api_error(status.HTTP_404_NOT_FOUND, error_msg) ccnet_api.group_add_member(group_id, username, email) add_user_to_group.send(sender=None, group_staff=username, group_id=group_id, added_user=email) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) member_info = get_group_member_info(request, group_id, email) return Response(member_info, status=status.HTTP_201_CREATED)
def can_access_repo_setting(request, repo_id, username): repo = seafile_api.get_repo(repo_id) if not repo: return (False, None) # no settings for virtual repo if ENABLE_SUB_LIBRARY and repo.is_virtual: return (False, None) # check permission 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) is_owner = True if username == repo_owner else False if not is_owner: return (False, None) return (True, repo)
def create_default_library(request): """Create a default library for user. Arguments: - `username`: """ username = request.user.username # Disable user guide no matter user permission error or creation error, # so that the guide popup only show once. UserOptions.objects.disable_user_guide(username) if not request.user.permissions.can_add_repo(): return if is_org_context(request): org_id = request.user.org.org_id default_repo = seafile_api.create_org_repo(name=_("My Library"), desc=_("My Library"), username=username, passwd=None, org_id=org_id) else: default_repo = seafile_api.create_repo(name=_("My Library"), desc=_("My Library"), username=username, passwd=None) sys_repo_id = get_system_default_repo_id() if sys_repo_id is None: return try: dirents = seafile_api.list_dir_by_path(sys_repo_id, '/') for e in dirents: obj_name = e.obj_name seafile_api.copy_file(sys_repo_id, '/', obj_name, default_repo, '/', obj_name, username, 0) except SearpcError as e: logger.error(e) return UserOptions.objects.set_default_repo(username, default_repo) return default_repo
def get(self, request): """get shared forms """ username = request.user.username org_id = -1 if is_org_context(request): org_id = request.user.org.org_id if org_id and org_id > 0: groups = ccnet_api.get_org_groups_by_user(org_id, username) else: groups = ccnet_api.get_groups(username, return_ancestors=True) group_ids = [group.id for group in groups] group_name_map = { group_id: group_id_to_name(group_id) for group_id in group_ids } try: shared_queryset = DTableFormShare.objects.list_by_group_ids( group_ids) except Exception as e: logger.error(e) error_msg = 'Internal Server Error.' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) shared_list = list() for item in shared_queryset: form = item.form if form.share_type != SHARED_GROUPS: continue data = form.to_dict() group_id = item.group_id data["group_name"] = group_name_map.get(group_id) data["group_id"] = group_id shared_list.append(data) return Response({'shared_list': shared_list}, status=status.HTTP_200_OK)
def get_shared_link(request): """ Handle ajax request to generate file or dir shared link. """ if not request.is_ajax(): raise Http404 content_type = 'application/json; charset=utf-8' repo_id = request.GET.get('repo_id', '') share_type = request.GET.get('type', 'f') # `f` or `d` path = request.GET.get('p', '') if not (repo_id and path): err = _('Invalid arguments') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) if share_type != 'f' and path == '/': err = _('You cannot share the library in this way.') data = json.dumps({'error': err}) return HttpResponse(data, status=400, content_type=content_type) username = request.user.username if share_type == 'f': fs = FileShare.objects.get_file_link_by_path(username, repo_id, path) if fs is None: fs = FileShare.objects.create_file_link(username, repo_id, path) else: fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path) if fs is None: fs = FileShare.objects.create_dir_link(username, repo_id, path) if is_org_context(request): org_id = request.user.org.org_id OrgFileShare.objects.set_org_file_share(org_id, fs) token = fs.token shared_link = gen_shared_link(token, fs.s_type) data = json.dumps({'token': token, 'shared_link': shared_link}) return HttpResponse(data, status=200, content_type=content_type)
def post(self, request): """ Create a group """ if not self._can_add_group(request): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) username = request.user.username group_name = request.data.get('name', '') group_name = group_name.strip() # Check whether group name is validate. if not validate_group_name(group_name): error_msg = _( u'Group name can only contain letters, numbers, blank, hyphen, dot, single quote or underscore' ) return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # Check whether group name is duplicated. if check_group_name_conflict(request, group_name): error_msg = _(u'There is already a group with that name.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # create group. try: if is_org_context(request): org_id = request.user.org.org_id group_id = seaserv.ccnet_threaded_rpc.create_org_group( org_id, group_name, username) else: group_id = seaserv.ccnet_threaded_rpc.create_group( group_name, username) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # get info of new group group_info = get_group_info(request, group_id) return Response(group_info, status=status.HTTP_201_CREATED)
def get(self, request, format=None): """ Search group. Permission checking: 1. default(NOT guest) user; """ # argument check q = request.GET.get('q', None) if not q: error_msg = 'q invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) # permission check if not self._can_use_global_address_book(request): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if CLOUD_MODE: if is_org_context(request): org_id = request.user.org.org_id groups = ccnet_api.get_org_groups(org_id, -1, -1) elif settings.ENABLE_GLOBAL_ADDRESSBOOK: groups = ccnet_api.get_all_groups(-1, -1) else: username = request.user.username groups = ccnet_api.get_groups(username) else: groups = ccnet_api.get_all_groups(-1, -1) result = [] for group in groups: group_name = group.group_name if not group_name: continue if q.lower() in group_name.lower(): group_info = get_group_info(group.id) result.append(group_info) return Response(result)
def check_group_name_conflict(request, new_group_name): """Check if new group name conflict with existed group. return "True" if conflicted else "False" """ org_id = -1 username = request.user.username if is_org_context(request): org_id = request.user.org.org_id checked_groups = seaserv.get_org_groups_by_user(org_id, username) else: if request.cloud_mode: checked_groups = seaserv.get_personal_groups_by_user(username) else: checked_groups = seaserv.ccnet_threaded_rpc.get_all_groups(-1, -1) for g in checked_groups: if g.group_name == new_group_name: return True return False
def _get_account_info(self, request): info = {} email = request.user.username p = Profile.objects.get_profile_by_user(email) if is_org_context(request): org_id = request.user.org.org_id is_org_staff = request.user.org.is_staff info['is_org_staff'] = is_org_staff else: quota_total = request.user.permissions.role_asset_quota() quota_total = get_quota_from_string( quota_total) if quota_total else -2 quota_usage = Workspaces.objects.get_owner_total_storage( request.user.username) if quota_total is not None and quota_total > 0: info['space_usage'] = str( float(quota_usage) / quota_total * 100) + '%' else: # no space quota set in config info['space_usage'] = '0%' info['total'] = quota_total info['usage'] = quota_usage url, _, _ = api_avatar_url(email, int(72)) info['avatar_url'] = url info['email'] = email info['name'] = email2nickname(email) info['login_id'] = p.login_id if p and p.login_id else "" info['contact_email'] = p.contact_email if p else "" info['institution'] = p.institution if p and p.institution else "" info['is_staff'] = request.user.is_staff if getattr(settings, 'MULTI_INSTITUTION', False): info['is_inst_admin'] = request.user.inst_admin interval = UserOptions.objects.get_dtable_updates_email_interval(email) info[ 'email_notification_interval'] = 0 if interval is None else interval return info
def list_user_shared_items(self, request, repo_id, path): 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 if path == '/': share_items = seafile_api.list_org_repo_shared_to( org_id, repo_owner, repo_id) else: share_items = seafile_api.get_org_shared_users_for_subdir( org_id, repo_id, path, repo_owner) else: repo_owner = seafile_api.get_repo_owner(repo_id) if path == '/': share_items = seafile_api.list_repo_shared_to( repo_owner, repo_id) else: share_items = seafile_api.get_shared_users_for_subdir( repo_id, path, repo_owner) # change is_admin to True if user is repo admin. admin_users = ExtraSharePermission.objects.get_admin_users_by_repo( repo_id) ret = [] for item in share_items: avatar_url, is_default, date_uploaded = api_avatar_url( item.user, 72) ret.append({ "share_type": "user", "user_info": { "name": item.user, "nickname": email2nickname(item.user), "contact_email": email2contact_email(item.user), "avatar_url": avatar_url, }, "permission": item.perm, "is_admin": item.user in admin_users }) return ret
def delete(self, request, group_id): """ Dismiss a specific group Permission: 1. group owner """ org_id = None if is_org_context(request): org_id = request.user.org.org_id username = request.user.username try: # only group owner can dismiss a group if not is_group_owner(group_id, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # if there are dtables in this group, prohibit deletion of groups owner = '%s@seafile_group' % group_id workspace = Workspaces.objects.get_workspace_by_owner(owner) if DTables.objects.filter(workspace=workspace, deleted=False).exists(): error_msg = 'Disable group deletion before deleting table(s).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: seafile_api.remove_repo(workspace.repo_id) workspace.delete() remove_group_common(group_id, username, org_id=org_id) 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})
def get(self, request, repo_id): """ Return repo info Permission checking: 1. all authenticated user can perform this action. """ # 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) # permission check permission = check_folder_permission(request, repo_id, '/') if permission is None: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) 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_id": repo.id, "repo_name": repo.name, "owner_email": repo_owner, "owner_name": email2nickname(repo_owner), "owner_contact_email": email2contact_email(repo_owner), "size": repo.size, "encrypted": repo.encrypted, "file_count": repo.file_count, "permission": permission, } return Response(result)
def get(self, request, group_id, format=None): """ List all group repos Permission checking: 1. only admin can perform this action. """ if not request.user.admin_permissions.can_manage_group(): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') group_id = int(group_id) group = ccnet_api.get_group(group_id) if not group: error_msg = 'Group %d not found.' % group_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) if is_org_context(request): org_id = request.user.org.org_id repos = seafile_api.get_org_group_repos(org_id, group_id) else: org_id = ccnet_api.get_org_id_by_group(group_id) if org_id != -1: repos = seafile_api.get_org_group_repos(org_id, group_id) else: repos = seafile_api.get_repos_by_group(group_id) group_repos_info = [] for repo in repos: repo_info = get_group_repo_info(repo) group_repos_info.append(repo_info) group_libraries = { 'group_id': group_id, 'group_name': group.group_name, 'libraries': group_repos_info } return Response(group_libraries)
def get(self, request, repo_id, format=None): """ Get all file/folder in a library """ repo = seafile_api.get_repo(repo_id) parent_dir = request.GET.get('parent_dir', '/') parent_dir = normalize_dir_path(parent_dir) dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir) if not dir_id: error_msg = 'Folder %s not found.' % parent_dir return api_error(status.HTTP_404_NOT_FOUND, error_msg) 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) try: dirs = seafile_api.list_dir_with_perm(repo_id, parent_dir, dir_id, repo_owner, -1, -1) except SearpcError as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) return_results = {} return_results['repo_name'] = repo.repo_name return_results['repo_id'] = repo.repo_id return_results['is_system_library'] = True if \ repo.id == get_system_default_repo_id() else False return_results['dirent_list'] = [] for dirent in dirs: dirent_info = get_dirent_info(dirent) return_results['dirent_list'].append(dirent_info) return Response(return_results)
def delete(self, request, repo_id, org_id, format=None): """ Delete repo group share permission. Permission checking: 1. is group admin """ # parameter check 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) # permission check username = request.user.username repo_owner = get_repo_owner(request, repo_id) group_id = get_group_id_by_repo_owner(repo_owner) if not is_group_admin(group_id, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) path = request.data.get('path', '/') SeafileAPI.delete_shared_group_by_repo_path( repo_id, repo_owner, to_group_id, path, org_id) permission = check_group_share_out_permission( repo_id, path, group_id, is_org_context(request)) send_perm_audit_msg('delete-repo-perm', username, group_id, repo_id, path, permission) return Response({'success': True})
def get(self, request): """ List Common Datasets user can access through group params: from_dtable_id, optional, if given, return sets from_dtable can access """ username = request.user.username org_id = -1 if is_org_context(request): org_id = request.user.org.org_id datasets = DTableCommonDataset.objects.filter(org_id=org_id) from_dtable_id = request.GET.get('from_dtable_id', '') if from_dtable_id: try: from_dtable = DTables.objects.get(pk=from_dtable_id) except DTables.DoesNotExist: error_msg = 'from_dtable %s not found.' % from_dtable_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) available_sets = [ dataset for dataset in datasets if dataset.can_access_by_dtable(from_dtable) ] else: available_sets = [ dataset for dataset in datasets if dataset.can_access_by_user_through_group(username) ] dataset_list = [] for dataset in available_sets: data = dataset.to_dict() data['can_manage'] = dataset.can_manage_by_user(username) dataset_list.append(data) return Response({'dataset_list': dataset_list})
def get(self, request, repo_id): """ Return repo share info Permission checking: 1. all authenticated user can perform this action. """ # 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) # permission check permission = check_folder_permission(request, repo_id, '/') if not permission: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if is_org_context(request): org_id = request.user.org.org_id repo_owner = seafile_api.get_org_repo_owner(org_id, repo_id) shared_users = seafile_api.list_org_repo_shared_to( repo_owner, repo_id) shared_groups = seafile_api.list_org_repo_shared_group( org_id, repo_owner, repo_id) else: repo_owner = seafile_api.get_repo_owner(repo_id) shared_users = seafile_api.list_repo_shared_to(repo_owner, repo_id) shared_groups = seafile_api.list_repo_shared_group_by_user( repo_owner, repo_id) result = { "shared_user_emails": [item.user for item in shared_users], "shared_group_ids": [item.group_id for item in shared_groups], } return Response(result)
def get_group_info(request, group_id, avatar_size=GROUP_AVATAR_DEFAULT_SIZE): group = ccnet_api.get_group(group_id) try: avatar_url, is_default, date_uploaded = api_grp_avatar_url( group.id, avatar_size) except Exception as e: logger.error(e) avatar_url = get_default_group_avatar_url() isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp) group_info = { "id": group.id, "parent_group_id": group.parent_group_id, "name": group.group_name, "owner": group.creator_name, "created_at": isoformat_timestr, "avatar_url": request.build_absolute_uri(avatar_url), "admins": get_group_admins(group.id), } # parent_group_id = 0: non department group # parent_group_id = -1: top department group # parent_group_id = n(n > 0): sub department group, n is parent group's id if group.parent_group_id != 0: group_info['group_quota'] = seafile_api.get_group_quota(group_id) group_info['group_quota_usage'] = '' if is_pro_version(): if is_org_context(request): org_id = request.user.org.org_id group_info[ 'group_quota_usage'] = seafile_api.org_get_group_quota_usage( org_id, group_id) else: group_info[ 'group_quota_usage'] = seafile_api.get_group_quota_usage( group_id) return group_info
def delete(self, request, group_id): """ Dismiss a specific group """ org_id = None if is_org_context(request): org_id = request.user.org.org_id username = request.user.username try: # only group owner can dismiss a group if not is_group_owner(group_id, username): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) remove_group_common(group_id, username, org_id=org_id) except SearpcError 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})