Skip to content

[ENG-7716] Allow for reinstatement of previous preprint versions (with date uploaded) via the admin app #11097

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions admin/preprints/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
re_path(r'^(?P<guid>\w+)/change_provider/$', views.PreprintProviderChangeView.as_view(), name='preprint-provider'),
re_path(r'^(?P<guid>\w+)/machine_state/$', views.PreprintMachineStateView.as_view(), name='preprint-machine-state'),
re_path(r'^(?P<guid>\w+)/reindex_share_preprint/$', views.PreprintReindexShare.as_view(), name='reindex-share-preprint'),
re_path(r'^(?P<guid>\w+)/reversion_preprint/$', views.PreprintReVersion.as_view(), name='re-version-preprint'),
re_path(r'^(?P<guid>\w+)/remove_user/(?P<user_id>[a-z0-9]+)/$', views.PreprintRemoveContributorView.as_view(), name='remove-user'),
re_path(r'^(?P<guid>\w+)/make_private/$', views.PreprintMakePrivate.as_view(), name='make-private'),
re_path(r'^(?P<guid>\w+)/fix_editing/$', views.PreprintFixEditing.as_view(), name='fix-editing'),
Expand Down
50 changes: 46 additions & 4 deletions admin/preprints/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.db import transaction
from django.db.models import F
from django.core.exceptions import PermissionDenied
from django.urls import NoReverseMatch
from django.http import HttpResponse, JsonResponse
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.shortcuts import redirect
Expand All @@ -10,7 +11,7 @@
FormView,
)
from django.utils import timezone
from django.urls import reverse_lazy
from django.urls import NoReverseMatch, reverse_lazy

from admin.base.views import GuidView
from admin.base.forms import GuidForm
Expand All @@ -19,6 +20,7 @@

from api.share.utils import update_share
from api.providers.workflows import Workflows
from api.preprints.serializers import PreprintSerializer

from osf.exceptions import PreprintStateError

Expand All @@ -45,6 +47,7 @@
)
from osf.utils.workflows import DefaultStates
from website import search
from website.files.utils import copy_files
from website.preprints.tasks import on_preprint_updated


Expand All @@ -56,8 +59,8 @@ def get_object(self):
preprint.guid = preprint._id
return preprint

def get_success_url(self):
return reverse_lazy('preprints:preprint', kwargs={'guid': self.kwargs['guid']})
def get_success_url(self, guid=None):
return reverse_lazy('preprints:preprint', kwargs={'guid': guid or self.kwargs['guid']})


class PreprintView(PreprintMixin, GuidView):
Expand Down Expand Up @@ -183,6 +186,45 @@ def post(self, request, *args, **kwargs):
return redirect(self.get_success_url())


class PreprintReVersion(PreprintMixin, View):
"""Allows an authorized user to create new version 1 of a preprint based on earlier
primary file version(s). All operations are executed within an atomic transaction.
If any step fails, the entire transaction will be rolled back and no version will be changed.
"""
permission_required = 'osf.change_node'

@transaction.atomic
def post(self, request, *args, **kwargs):
preprint = self.get_object()

file_versions = request.POST.getlist('file_versions')
if not file_versions:
return HttpResponse('At least one file version should be attached.', status=400)

versions = preprint.get_preprint_versions()
for version in versions:
version.upgrade_version()

new_preprint, data_to_update = Preprint.create_version(
create_from_guid=preprint._id,
assign_version_number=1,
auth=request,
ignore_permission=True,
)
primary_file = copy_files(preprint.primary_file, target_node=new_preprint, identifier__in=file_versions)
data_to_update['primary_file'] = primary_file

# FIXME: currently it's not possible to ignore permission when update subjects
# via serializer, remove this logic if deprecated
subjects = data_to_update.pop('subjects', None)
if subjects:
new_preprint.set_subjects([subjects], auth=request, ignore_permission=True)

PreprintSerializer(new_preprint, context={'request': request, 'ignore_permission': True}).update(new_preprint, data_to_update)

return JsonResponse({'redirect': self.get_success_url(new_preprint._id)})


class PreprintReindexElastic(PreprintMixin, View):
""" Allows an authorized user to reindex a node in ElasticSearch.
"""
Expand Down
18 changes: 18 additions & 0 deletions admin/static/js/preprints/preprints.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
$(document).ready(function() {

$("#confirmReversion").on("submit", function (event) {
event.preventDefault();

$.ajax({
url: window.templateVars.reVersionPreprint,
type: "post",
data: $("#re-version-preprint-form").serialize(),
}).success(function (response) {
if (response.redirect) {
window.location.href = response.redirect;
}
}).fail(function (jqXHR, textStatus, error) {
$("#version-validation").text(jqXHR.responseText);
});
});
});
32 changes: 32 additions & 0 deletions admin/templates/preprints/assign_new_version.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{% load node_extras %}
<a data-toggle="modal" data-target="#confirmReversion" class="btn btn-default">
Create new version 1
</a>
<div class="modal" id="confirmReversion">
<div class="modal-dialog">
<div class="modal-content">
<form id="re-version-preprint-form", class="well">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3>Are you sure you want to create new version 1 for <a href="{{ preprint | reverse_preprint }}">({{ preprint.title }})</a> preprint</h3>
</div>
<p>Select file versions to attach:</p>
{% for version in preprint.primary_file.versions.all %}
<label>
<input type="checkbox" name="file_versions" value="{{ version.identifier }}"> Version: {{ version.identifier }} | {{ version.created|date:"Y-m-d H:i" }}
</label>
<br/>
{% endfor %}
<p id="version-validation"></p>
{% csrf_token %}
<div class="modal-footer">
<input class="btn btn-danger" type="submit" value="Confirm" />
<button type="button" class="btn btn-default" data-dismiss="modal">
Cancel
</button>
</div>
</form>
</div>
</div>
</div>

9 changes: 9 additions & 0 deletions admin/templates/preprints/preprint.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
{% include "preprints/make_public.html" with preprint=preprint %}
{% include "preprints/make_published.html" with preprint=preprint %}
{% include "preprints/fix_editing.html" with preprint=preprint %}
{% include "preprints/assign_new_version.html" with preprint=preprint %}
</div>
</div>
</div>
Expand Down Expand Up @@ -123,3 +124,11 @@ <h2>Preprint: <b>{{ preprint.title }}</b> <a href="{{ preprint.absolute_url }}">
</div>
</div>
{% endblock content %}
{% block bottom_js %}
<script src="/static/js/preprints/preprints.js"></script>
<script>
window.templateVars = {
'reVersionPreprint': '{% url 'preprints:re-version-preprint' guid=preprint.guid %}',
}
</script>
{% endblock %}
30 changes: 30 additions & 0 deletions admin_tests/preprints/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -797,3 +797,33 @@ def test_admin_user_can_publish_preprint(self, user, preprint, plain_view):
preprint.reload()

assert preprint.is_published


@pytest.mark.urls('admin.base.urls')
class TestPreprintReVersionView:

@pytest.fixture()
def plain_view(self):
return views.PreprintReVersion

def test_admin_user_can_add_new_version_one(self, user, preprint, plain_view):
# user isn't admin contributor in the preprint
assert preprint.contributors.filter(id=user.id).exists() is False
assert preprint.has_permission(user, ADMIN) is False
assert len(preprint.get_preprint_versions()) == 1

request = RequestFactory().post(
reverse('preprints:re-version-preprint',
kwargs={'guid': preprint._id}),
data={'file_versions': ['1']}
)
request.user = user

admin_group = Group.objects.get(name='osf_admin')
admin_group.permissions.add(Permission.objects.get(codename='change_node'))
user.groups.add(admin_group)

plain_view.as_view()(request, guid=preprint._id)
preprint.refresh_from_db()

assert len(preprint.get_preprint_versions()) == 2
4 changes: 3 additions & 1 deletion api/base/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ def get_user_auth(request):
authenticated user attached to it.
"""
user = request.user
private_key = request.query_params.get('view_only', None)
private_key = None
if hasattr(request, 'query_params'): # allows django WSGIRequest to be used as well
private_key = request.query_params.get('view_only', None)
if user.is_anonymous:
auth = Auth(None, private_key=private_key)
else:
Expand Down
104 changes: 37 additions & 67 deletions api/preprints/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,8 @@ def update(self, preprint, validated_data):
assert isinstance(preprint, Preprint), 'You must specify a valid preprint to be updated'

auth = get_user_auth(self.context['request'])
if not preprint.has_permission(auth.user, osf_permissions.WRITE):
ignore_permission = self.context.get('ignore_permission', False)
if not ignore_permission and not preprint.has_permission(auth.user, osf_permissions.WRITE):
raise exceptions.PermissionDenied(detail='User must have admin or write permissions to update a preprint.')

for field in ['conflict_of_interest_statement', 'why_no_data', 'why_no_prereg']:
Expand Down Expand Up @@ -344,76 +345,45 @@ def update(self, preprint, validated_data):
detail='You cannot edit this field while your prereg links availability is set to false or is unanswered.',
)

def require_admin_permission():
if not preprint.has_permission(auth.user, osf_permissions.ADMIN):
raise exceptions.PermissionDenied(detail='Must have admin permissions to update author assertion fields.')
try:
if 'has_coi' in validated_data:
preprint.update_has_coi(auth, validated_data['has_coi'], ignore_permission=ignore_permission)

if 'has_coi' in validated_data:
require_admin_permission()
try:
preprint.update_has_coi(auth, validated_data['has_coi'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
if 'conflict_of_interest_statement' in validated_data:
preprint.update_conflict_of_interest_statement(auth, validated_data['conflict_of_interest_statement'], ignore_permission=ignore_permission)

if 'conflict_of_interest_statement' in validated_data:
require_admin_permission()
try:
preprint.update_conflict_of_interest_statement(auth, validated_data['conflict_of_interest_statement'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
if 'has_data_links' in validated_data:
preprint.update_has_data_links(auth, validated_data['has_data_links'], ignore_permission=ignore_permission)

if 'has_data_links' in validated_data:
require_admin_permission()
try:
preprint.update_has_data_links(auth, validated_data['has_data_links'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
if 'why_no_data' in validated_data:
preprint.update_why_no_data(auth, validated_data['why_no_data'], ignore_permission=ignore_permission)

if 'why_no_data' in validated_data:
require_admin_permission()
try:
preprint.update_why_no_data(auth, validated_data['why_no_data'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
if 'has_prereg_links' in validated_data:
preprint.update_has_prereg_links(auth, validated_data['has_prereg_links'], ignore_permission=ignore_permission)

if 'data_links' in validated_data:
require_admin_permission()
try:
preprint.update_data_links(auth, validated_data['data_links'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
else:
if updated_has_data_links == 'no' and preprint.data_links:
preprint.update_data_links(auth, [])

if 'has_prereg_links' in validated_data:
require_admin_permission()
if 'why_no_prereg' in validated_data:
preprint.update_why_no_prereg(auth, validated_data['why_no_prereg'], ignore_permission=ignore_permission)

try:
preprint.update_has_prereg_links(auth, validated_data['has_prereg_links'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))

if 'why_no_prereg' in validated_data:
require_admin_permission()
try:
preprint.update_why_no_prereg(auth, validated_data['why_no_prereg'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
if 'prereg_links' in validated_data:
preprint.update_prereg_links(auth, validated_data['prereg_links'], ignore_permission=ignore_permission)

if 'prereg_links' in validated_data:
require_admin_permission()
try:
preprint.update_prereg_links(auth, validated_data['prereg_links'])
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
if 'prereg_link_info' in validated_data:
preprint.update_prereg_link_info(auth, validated_data['prereg_link_info'], ignore_permission=ignore_permission)
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
except PermissionsError:
raise exceptions.PermissionDenied(detail='Must have admin permissions to update author assertion fields.')

if 'prereg_link_info' in validated_data:
require_admin_permission()
if 'data_links' in validated_data:
try:
preprint.update_prereg_link_info(auth, validated_data['prereg_link_info'])
preprint.update_data_links(auth, validated_data['data_links'], ignore_permission=ignore_permission)
except PreprintStateError as e:
raise exceptions.ValidationError(detail=str(e))
except PermissionsError:
raise exceptions.PermissionDenied(detail='Must have admin permissions to update author assertion fields.')
else:
if updated_has_data_links == 'no' and preprint.data_links:
preprint.update_data_links(auth, [], ignore_permission=ignore_permission)

published = validated_data.pop('is_published', None)
if published and preprint.provider.is_reviewed:
Expand All @@ -434,7 +404,7 @@ def require_admin_permission():

primary_file = validated_data.pop('primary_file', None)
if primary_file:
self.set_field(preprint.set_primary_file, primary_file, auth)
self.set_field(preprint.set_primary_file, primary_file, auth, ignore_permission=ignore_permission)

old_tags = set(preprint.tags.values_list('name', flat=True))
if 'tags' in validated_data:
Expand All @@ -451,19 +421,19 @@ def require_admin_permission():

if 'node' in validated_data:
node = validated_data.pop('node', None)
self.set_field(preprint.set_supplemental_node, node, auth)
self.set_field(preprint.set_supplemental_node, node, auth, ignore_permission=ignore_permission)

if 'subjects' in validated_data:
subjects = validated_data.pop('subjects', None)
self.update_subjects(preprint, subjects, auth)

if 'title' in validated_data:
title = validated_data['title']
self.set_field(preprint.set_title, title, auth)
self.set_field(preprint.set_title, title, auth, ignore_permission=ignore_permission)

if 'description' in validated_data:
description = validated_data['description']
self.set_field(preprint.set_description, description, auth)
self.set_field(preprint.set_description, description, auth, ignore_permission=ignore_permission)

if 'article_doi' in validated_data:
preprint.article_doi = validated_data['article_doi']
Expand All @@ -483,7 +453,7 @@ def require_admin_permission():
raise exceptions.ValidationError(
detail='A valid primary_file must be set before publishing a preprint.',
)
self.set_field(preprint.set_published, published, auth)
self.set_field(preprint.set_published, published, auth, ignore_permission=ignore_permission)
recently_published = published
preprint.set_privacy('public', log=False, save=True)

Expand All @@ -506,9 +476,9 @@ def require_admin_permission():

return preprint

def set_field(self, func, val, auth, save=False):
def set_field(self, func, val, auth, **kwargs):
try:
func(val, auth)
func(val, auth, **kwargs)
except PermissionsError as e:
raise exceptions.PermissionDenied(detail=str(e))
except (ValueError, ValidationError, NodeStateError) as e:
Expand Down
Loading
Loading