Projet

Général

Profil

0001-general-add-API-to-push-documents-7080.patch

Frédéric Péters, 12 février 2016 15:59

Télécharger (6,87 ko)

Voir les différences:

Subject: [PATCH] general: add API to push documents (#7080)

 fargo/fargo/api_views.py | 107 +++++++++++++++++++++++++++++++++++++++++++++++
 fargo/settings.py        |  18 ++++++++
 fargo/urls.py            |   3 ++
 setup.py                 |   1 +
 4 files changed, 129 insertions(+)
 create mode 100644 fargo/fargo/api_views.py
fargo/fargo/api_views.py
1
# fargo - document box
2
# Copyright (C) 2015-2016  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
import base64
18

  
19
from django.conf import settings
20
from django.core.files.base import ContentFile
21
from django.contrib.auth.models import User
22
from django.utils.text import slugify
23

  
24
from rest_framework import serializers, authentication
25
from rest_framework.decorators import permission_classes
26
from rest_framework.generics import GenericAPIView
27
from rest_framework.permissions import IsAdminUser
28
from rest_framework.response import Response
29
from rest_framework import permissions, status
30

  
31
from .models import Origin, Document, UserDocument, Validation
32

  
33
try:
34
    from mellon.models import UserSAMLIdentifier
35
except ImportError:
36
    UserSAMLIdentifier = None
37

  
38

  
39
class PushDocumentSerializer(serializers.Serializer):
40
    origin = serializers.CharField(required=True)
41
    file_b64_content = serializers.CharField(required=True)
42
    file_name = serializers.CharField(required=False)
43
    document_type = serializers.ChoiceField(required=True,
44
            choices=[x.get('name') for x in settings.FARGO_DOCUMENT_TYPES])
45
    user_email = serializers.CharField(required=False)
46
    user_nameid = serializers.CharField(required=False)
47

  
48
    def validate(self, data):
49
        if not (data.get('user_email') or data.get('user_nameid')):
50
            raise serializers.ValidationError('user must be specified')
51
        return data
52

  
53
    def validate_user_email(self, value):
54
        try:
55
            user = User.objects.get(email=value)
56
        except User.DoesNotExist:
57
            raise serializers.ValidationError('unknown user')
58
        return value
59

  
60
    def validate_user_nameid(self, value):
61
        if UserSAMLIdentifier is None:
62
            raise serializers.ValidationError('nameid lookups require django-mellon')
63
        try:
64
            UserSAMLIdentifier.objects.get(name_id=value)
65
        except UserSAMLIdentifier.DoesNotExist:
66
            raise serializers.ValidationError('unknown user')
67
        return value
68

  
69

  
70
class PushDocument(GenericAPIView):
71
    serializer_class = PushDocumentSerializer
72
    permission_classes = (IsAdminUser,)
73

  
74
    def post(self, request, format=None):
75
        serializer = self.get_serializer(data=request.data)
76
        if not serializer.is_valid():
77
            response = {'result': 0, 'errors': serializer.errors}
78
            return Response(response, status.HTTP_400_BAD_REQUEST)
79

  
80
        data = serializer.validated_data
81
        if data.get('user_email'):
82
            user = User.objects.get(email=data.get('user_email'))
83
        elif data.get('user_nameid'):
84
            user = UserSAMLIdentifier.objects.get(name_id=data.get('user_nameid')).user
85

  
86
        origin, created = Origin.objects.get_or_create(
87
                slug=slugify(data.get('origin')),
88
                defaults={'label': data.get('origin')})
89

  
90
        document_file = ContentFile(base64.decodestring(data.get('file_b64_content')))
91
        if data.get('file_name'):
92
            document_file.name = data.get('file_name')
93
        document = Document(content=document_file)
94
        document.save()
95

  
96
        user_document = UserDocument(
97
                user=user,
98
                filename=data.get('file_name'),
99
                document=document,
100
                origin=origin)
101
        user_document.save()
102

  
103
        response = {'hello': 'world'}
104
        response_status = status.HTTP_200_OK
105
        return Response(response, response_status)
106

  
107
push_document = PushDocument.as_view()
fargo/settings.py
41 41
    'django_tables2',
42 42
    'gadjo',
43 43
    'fargo.fargo',
44
    'rest_framework',
44 45
)
45 46

  
46 47
MIDDLEWARE_CLASSES = (
......
148 149

  
149 150
LOGIN_REDIRECT_URL = 'home'
150 151

  
152
REST_FRAMEWORK = {
153
    'NON_FIELD_ERRORS_KEY': '__all__',
154
    'DEFAULT_AUTHENTICATION_CLASSES': (
155
        'rest_framework.authentication.BasicAuthentication',
156
        'rest_framework.authentication.SessionAuthentication',
157
    ),
158
    'DEFAULT_PERMISSION_CLASSES': (
159
        'rest_framework.permissions.IsAuthenticated',
160
    ),
161
    'DEFAULT_FILTER_BACKENDS': (
162
        'rest_framework.filters.DjangoFilterBackend',
163
        'rest_framework.filters.OrderingFilter',
164
    ),
165
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
166
    'PAGE_SIZE': 10,
167
}
168

  
151 169
local_settings_file = os.environ.get('FARGO_SETTINGS_FILE',
152 170
        os.path.join(os.path.dirname(__file__), 'local_settings.py'))
153 171

  
fargo/urls.py
5 5
from .fargo.views import (home, jsonp, json, document, download, pick, delete,
6 6
                          upload, remote_download, login, logout, pick_list,
7 7
                          metadata, validation, document_types)
8
from .fargo.api_views import (push_document, )
8 9

  
9 10
urlpatterns = patterns(
10 11
    '',
......
28 29
    url(r'^login/$', login, name='auth_login'),
29 30
    url(r'^logout/$', logout, name='auth_logout'),
30 31
    url(r'^document-types/$', document_types, name='document_types'),
32

  
33
    url(r'^api/push-document', push_document, name='api-push-document'),
31 34
)
32 35

  
33 36

  
setup.py
98 98
        'gadjo',
99 99
        'django-tables2',
100 100
        'django-jsonfield >= 0.9.3',
101
        'djangorestframework>=3.1',
101 102
        ],
102 103
    zip_safe=False,
103 104
    cmdclass={
104
-