1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-03 07:55:36 +00:00

repo admin manage share/upload links (#4408)

* repo admin manage share/upload links

* [repo share/upload links] bugfix & improvement

Co-authored-by: lian <lian@seafile.com>
Co-authored-by: llj <lingjun.li1@gmail.com>
This commit is contained in:
lian
2020-03-09 16:30:27 +08:00
committed by GitHub
parent 54fe3d0fbc
commit e27c0350d0
6 changed files with 521 additions and 1 deletions

View File

@@ -0,0 +1,210 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Modal, ModalHeader, ModalBody, NavLink } from 'reactstrap';
import { seafileAPI } from '../../utils/seafile-api';
import { siteRoot, gettext } from '../../utils/constants';
import { Utils } from '../../utils/utils';
import toaster from '../toast';
import Loading from '../loading';
const repoShareUploadLinkItemPropTypes = {
item: PropTypes.object.isRequired,
activeTab: PropTypes.string.isRequired,
deleteItem: PropTypes.func.isRequired
};
class RepoShareUploadLinkItem extends React.Component {
constructor(props) {
super(props);
this.state = {
isOperationShow: false
};
}
onMouseEnter = () => {
this.setState({isOperationShow: true});
};
onMouseLeave = () => {
this.setState({isOperationShow: false});
};
onDeleteLink = (e) => {
e.preventDefault();
this.props.deleteItem(this.props.item.token);
};
render() {
let objUrl;
let item = this.props.item;
let path = item.path === '/' ? '/' : item.path.slice(0, item.path.length - 1);
if (this.props.activeTab === 'shareLinks') {
if (item.is_dir) {
objUrl = `${siteRoot}library/${item.repo_id}/${encodeURIComponent(item.repo_name)}${Utils.encodePath(path)}`;
} else {
objUrl = `${siteRoot}lib/${item.repo_id}/file${Utils.encodePath(item.path)}`;
}
}
if (this.props.activeTab === 'uploadLinks') {
objUrl = `${siteRoot}library/${item.repo_id}/${encodeURIComponent(item.repo_name)}${Utils.encodePath(path)}`;
}
return (
<tr onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>
<td className="name">{item.creator_name}</td>
<td>
<a href={objUrl} target="_blank" className="text-inherit">{item.obj_name}</a>
</td>
<td>
<a href={item.link} target="_blank" className="text-inherit">{item.link}</a>
</td>
<td>
<span
className={`sf2-icon-x3 action-icon ${this.state.isOperationShow ? '' : 'invisible'}`}
onClick={this.onDeleteLink}
title={gettext('Delete')}
/>
</td>
</tr>
);
}
}
RepoShareUploadLinkItem.propTypes = repoShareUploadLinkItemPropTypes;
const RepoShareUploadLinksDialogPropTypes = {
repo: PropTypes.object.isRequired,
toggleDialog: PropTypes.func.isRequired
};
class RepoShareUploadLinksDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
activeTab: 'shareLinks',
repoShareUploadLinkList: [],
errorMsg: ''
};
}
componentDidMount() {
this.getItems('share-link');
}
getItems = (itemType) => {
const repoID = this.props.repo.repo_id;
const request = itemType == 'share-link' ?
seafileAPI.listRepoShareLinks(repoID) :
seafileAPI.listRepoUploadLinks(repoID);
request.then((res) => {
this.setState({
loading: false,
repoShareUploadLinkList: res.data,
});
}).catch(error => {
this.setState({
isLoading: false,
errorMsg: Utils.getErrorMsg(error, true)
});
});
}
deleteItem = (token) => {
const repoID = this.props.repo.repo_id;
const request = this.state.activeTab == 'shareLinks' ?
seafileAPI.deleteRepoShareLink(repoID, token) :
seafileAPI.deleteRepoUploadLink(repoID, token);
request.then((res) => {
const repoShareUploadLinkList = this.state.repoShareUploadLinkList.filter(item => {
return item.token !== token;
});
this.setState({
repoShareUploadLinkList: repoShareUploadLinkList
});
}).catch(error => {
toaster.danger(Utils.getErrorMsg(error));
});
};
toggle = (tab) => {
if (this.state.activeTab !== tab) {
this.setState({activeTab: tab});
}
if (tab == 'shareLinks') {
this.getItems('share-link');
}
if (tab == 'uploadLinks') {
this.getItems('upload-link');
}
};
render() {
const { loading, errorMsg, activeTab } = this.state;
const itemName = '<span class="op-target">' + Utils.HTMLescape(this.props.repo.repo_name) + '</span>';
const title = gettext('{placeholder} Share/Upload Links').replace('{placeholder}', itemName);
return (
<Modal isOpen={true} style={{maxWidth: '800px'}}>
<ModalHeader toggle={this.props.toggleDialog}>
<span dangerouslySetInnerHTML={{__html: title}}></span>
</ModalHeader>
<ModalBody className="p-0 pb-4">
<div className="main-panel-center">
<div className="cur-view-container">
<div className="cur-view-path share-upload-nav">
<ul className="nav">
<li className="nav-item">
<NavLink className={activeTab === 'shareLinks' ? 'active' : ''} onClick={this.toggle.bind(this, 'shareLinks')}>{gettext('Share Links')}</NavLink>
</li>
<li className="nav-item">
<NavLink className={activeTab === 'uploadLinks' ? 'active' : ''} onClick={this.toggle.bind(this, 'uploadLinks')}>{gettext('Upload Links')}</NavLink>
</li>
</ul>
</div>
<div className="cur-view-content" style={{minHeight: '20rem', maxHeight: '20rem'}}>
{loading && <Loading />}
{!loading && errorMsg && <p className="error text-center mt-8">{errorMsg}</p>}
{!loading && !errorMsg &&
<table>
<thead>
<tr>
<th width="22%">{gettext('Creator')}</th>
<th width="20%">{gettext('Name')}</th>
<th width="48%">{gettext('Link')}</th>
<th width="10%"></th>
</tr>
</thead>
<tbody>
{this.state.repoShareUploadLinkList.map((item, index) => {
return (
<RepoShareUploadLinkItem
key={index}
item={item}
activeTab={this.state.activeTab}
deleteItem={this.deleteItem}
/>
);
})}
</tbody>
</table>
}
</div>
</div>
</div>
</ModalBody>
</Modal>
);
}
}
RepoShareUploadLinksDialog.propTypes = RepoShareUploadLinksDialogPropTypes;
export default RepoShareUploadLinksDialog;

View File

@@ -19,6 +19,7 @@ import LibSubFolderPermissionDialog from '../../components/dialog/lib-sub-folder
import Rename from '../../components/rename';
import MylibRepoMenu from './mylib-repo-menu';
import RepoAPITokenDialog from '../../components/dialog/repo-api-token-dialog';
import RepoShareUploadLinksDialog from '../../components/dialog/repo-share-upload-links-dialog';
const propTypes = {
repo: PropTypes.object.isRequired,
@@ -48,6 +49,7 @@ class MylibRepoListItem extends React.Component {
isLabelRepoStateDialogOpen: false,
isFolderPermissionDialogShow: false,
isAPITokenDialogShow: false,
isRepoShareUploadLinksDialogOpen: false
};
}
@@ -105,6 +107,9 @@ class MylibRepoListItem extends React.Component {
case 'API Token':
this.onAPITokenToggle();
break;
case 'Share Links':
this.toggleRepoShareUploadLinksDialog();
break;
default:
break;
}
@@ -180,6 +185,10 @@ class MylibRepoListItem extends React.Component {
this.setState({isAPITokenDialogShow: !this.state.isAPITokenDialogShow});
}
toggleRepoShareUploadLinksDialog = () => {
this.setState({isRepoShareUploadLinksDialogOpen: !this.state.isRepoShareUploadLinksDialogOpen});
}
onUnfreezedItem = () => {
this.setState({
highlight: false,
@@ -425,6 +434,15 @@ class MylibRepoListItem extends React.Component {
</ModalPortal>
)}
{this.state.isRepoShareUploadLinksDialogOpen && (
<ModalPortal>
<RepoShareUploadLinksDialog
repo={repo}
toggleDialog={this.toggleRepoShareUploadLinksDialog}
/>
</ModalPortal>
)}
</Fragment>
);
}

View File

@@ -53,7 +53,7 @@ class MylibRepoMenu extends React.Component {
generatorOperations = () => {
let repo = this.props.repo;
let showResetPasswordMenuItem = repo.encrypted && enableResetEncryptedRepoPassword && isEmailConfigured;
let operations = ['Rename', 'Transfer', 'History Setting', 'API Token'];
let operations = ['Rename', 'Transfer', 'History Setting', 'API Token', 'Share Links'];
if (repo.encrypted) {
operations.push('Change Password');
}
@@ -108,6 +108,9 @@ class MylibRepoMenu extends React.Component {
case 'API Token':
translateResult = 'API Token'; // translation is not needed here
break;
case 'Share Links':
translateResult = gettext('Share Links');
break;
default:
break;
}

View File

@@ -0,0 +1,148 @@
# Copyright (c) 2012-2016 Seafile Ltd.
import os
import logging
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from seaserv import seafile_api
from seahub.api2.utils import api_error
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.authentication import TokenAuthentication
from seahub.base.templatetags.seahub_tags import email2nickname, \
email2contact_email
from seahub.utils import gen_shared_link
from seahub.utils.repo import is_repo_admin
from seahub.utils.timeutils import datetime_to_isoformat_timestr
from seahub.wiki.models import Wiki
from seahub.share.models import FileShare
logger = logging.getLogger(__name__)
def get_share_link_info(fileshare):
data = {}
token = fileshare.token
path = fileshare.path
if path:
obj_name = '/' if path == '/' else os.path.basename(path.rstrip('/'))
else:
obj_name = ''
if fileshare.expire_date:
expire_date = datetime_to_isoformat_timestr(fileshare.expire_date)
else:
expire_date = ''
if fileshare.ctime:
ctime = datetime_to_isoformat_timestr(fileshare.ctime)
else:
ctime = ''
creator_email = fileshare.username
data['creator_email'] = creator_email
data['creator_name'] = email2nickname(creator_email)
data['creator_contact_email'] = email2contact_email(creator_email)
data['path'] = path
data['obj_name'] = obj_name
data['is_dir'] = True if fileshare.s_type == 'd' else False
data['token'] = token
data['link'] = gen_shared_link(token, fileshare.s_type)
data['ctime'] = ctime
data['expire_date'] = expire_date
return data
class RepoShareLinks(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
def get(self, request, repo_id):
""" Get all share links of a repo.
Permission checking:
1. repo owner or admin;
"""
# 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
username = request.user.username
if not is_repo_admin(username, repo_id):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
result = []
fileshares = FileShare.objects.filter(repo_id=repo_id)
for fileshare in fileshares:
link_info = get_share_link_info(fileshare)
link_info['repo_id'] = repo_id
link_info['repo_name'] = repo.name
result.append(link_info)
return Response(result)
class RepoShareLink(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
def delete(self, request, repo_id, token):
""" Delete share link.
Permission checking:
1. repo owner or admin;
"""
# resource check
try:
fileshare = FileShare.objects.get(token=token)
except FileShare.DoesNotExist:
error_msg = 'Share link %s not found.' % token
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
# permission check
username = request.user.username
if not is_repo_admin(username, fileshare.repo_id):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
has_published_library = False
if fileshare.path == '/':
try:
Wiki.objects.get(repo_id=fileshare.repo_id)
has_published_library = True
except Wiki.DoesNotExist:
pass
if has_published_library:
error_msg = 'There is an associated published library.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
try:
fileshare.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})

View File

@@ -0,0 +1,133 @@
# Copyright (c) 2012-2016 Seafile Ltd.
import os
import logging
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from seaserv import seafile_api
from seahub.api2.utils import api_error
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.authentication import TokenAuthentication
from seahub.base.templatetags.seahub_tags import email2nickname, \
email2contact_email
from seahub.share.models import UploadLinkShare
from seahub.utils import gen_shared_upload_link
from seahub.utils.repo import is_repo_admin
from seahub.utils.timeutils import datetime_to_isoformat_timestr
logger = logging.getLogger(__name__)
def get_upload_link_info(upload_link):
data = {}
token = upload_link.token
path = upload_link.path
if path:
obj_name = '/' if path == '/' else os.path.basename(path.rstrip('/'))
else:
obj_name = ''
if upload_link.ctime:
ctime = datetime_to_isoformat_timestr(upload_link.ctime)
else:
ctime = ''
if upload_link.expire_date:
expire_date = datetime_to_isoformat_timestr(upload_link.expire_date)
else:
expire_date = ''
creator_email = upload_link.username
data['creator_email'] = creator_email
data['creator_name'] = email2nickname(creator_email)
data['creator_contact_email'] = email2contact_email(creator_email)
data['path'] = path
data['obj_name'] = obj_name
data['token'] = token
data['link'] = gen_shared_upload_link(token)
data['ctime'] = ctime
data['expire_date'] = expire_date
return data
class RepoUploadLinks(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
def get(self, request, repo_id):
""" Get all upload links of a repo.
Permission checking:
1. repo owner or admin;
"""
# 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
username = request.user.username
if not is_repo_admin(username, repo_id):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
username = request.user.username
upload_links = UploadLinkShare.objects.filter(repo_id=repo_id)
result = []
for upload_link in upload_links:
link_info = get_upload_link_info(upload_link)
link_info['repo_id'] = repo_id
link_info['repo_name'] = repo.name
result.append(link_info)
return Response(result)
class RepoUploadLink(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
def delete(self, request, repo_id, token):
""" Delete upload link.
Permission checking:
1. repo owner or admin;
"""
# resource check
try:
upload_link = UploadLinkShare.objects.get(token=token)
except UploadLinkShare.DoesNotExist:
error_msg = 'Upload link %s not found.' % token
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
# permission check
username = request.user.username
if not is_repo_admin(username, upload_link.repo_id):
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
try:
upload_link.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})

View File

@@ -93,6 +93,9 @@ from seahub.api2.endpoints.via_repo_token import ViaRepoDirView, ViaRepoUploadLi
ViaRepoDownloadLinkView
from seahub.api2.endpoints.abuse_reports import AbuseReportsView
from seahub.api2.endpoints.repo_share_links import RepoShareLinks, RepoShareLink
from seahub.api2.endpoints.repo_upload_links import RepoUploadLinks, RepoUploadLink
# Admin
from seahub.api2.endpoints.admin.abuse_reports import AdminAbuseReportsView, AdminAbuseReportView
from seahub.api2.endpoints.admin.revision_tag import AdminTaggedItemsView
@@ -342,6 +345,11 @@ urlpatterns = [
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/file/participant/$', FileParticipantView.as_view(), name='api-v2.1-file-participant'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/related-users/$', RepoRelatedUsersView.as_view(), name='api-v2.1-related-user'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/share-links/$', RepoShareLinks.as_view(), name='api-v2.1-repo-share-links'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/share-links/(?P<token>[a-f0-9]+)/$', RepoShareLink.as_view(), name='api-v2.1-repo-share-link'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/upload-links/$', RepoUploadLinks.as_view(), name='api-v2.1-repo-upload-links'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/upload-links/(?P<token>[a-f0-9]+)/$', RepoUploadLink.as_view(), name='api-v2.1-repo-upload-link'),
## user:: repo-api-tokens
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/repo-api-tokens/$', RepoAPITokensView.as_view(), name='api-v2.1-repo-api-tokens'),
url(r'^api/v2.1/repos/(?P<repo_id>[-0-9a-f]{36})/repo-api-tokens/(?P<app_name>.*)/$', RepoAPITokenView.as_view(), name='api-v2.1-repo-api-token'),