2015-02-12 22:42:54 +01:00
|
|
|
from django.contrib.auth import login as auth_login
|
|
|
|
from django.contrib.auth import logout as auth_logout
|
2015-06-16 10:37:23 +02:00
|
|
|
from django.contrib.auth.forms import AuthenticationForm
|
2015-06-18 22:39:58 +02:00
|
|
|
from django.utils.translation import ugettext as _
|
2015-06-16 10:37:23 +02:00
|
|
|
from django.utils.translation import ugettext_lazy
|
2014-10-11 14:34:49 +02:00
|
|
|
|
2015-09-16 00:55:27 +02:00
|
|
|
from ..core.config import config
|
2015-11-06 15:44:27 +01:00
|
|
|
from ..utils.rest_api import (
|
|
|
|
ModelViewSet,
|
|
|
|
Response,
|
|
|
|
ValidationError,
|
|
|
|
detail_route,
|
|
|
|
status,
|
|
|
|
)
|
2015-09-16 00:55:27 +02:00
|
|
|
from ..utils.views import APIView, PDFView
|
2014-10-11 14:34:49 +02:00
|
|
|
from .models import Group, User
|
2015-02-12 22:42:54 +01:00
|
|
|
from .pdf import users_passwords_to_pdf, users_to_pdf
|
|
|
|
from .serializers import (
|
|
|
|
GroupSerializer,
|
|
|
|
UserFullSerializer,
|
2015-02-27 09:20:49 +01:00
|
|
|
UserShortSerializer,
|
2015-02-12 22:42:54 +01:00
|
|
|
)
|
2011-07-31 10:46:29 +02:00
|
|
|
|
2012-07-07 15:26:00 +02:00
|
|
|
|
2015-07-01 23:18:48 +02:00
|
|
|
# Viewsets for the REST API
|
2012-08-10 19:49:46 +02:00
|
|
|
|
2015-02-12 18:48:14 +01:00
|
|
|
class UserViewSet(ModelViewSet):
|
2015-01-06 00:11:22 +01:00
|
|
|
"""
|
2015-07-01 23:18:48 +02:00
|
|
|
API endpoint for users.
|
|
|
|
|
2015-08-31 14:07:24 +02:00
|
|
|
There are the following views: metadata, list, retrieve, create,
|
|
|
|
partial_update, update, destroy and reset_password.
|
2015-01-06 00:11:22 +01:00
|
|
|
"""
|
|
|
|
queryset = User.objects.all()
|
|
|
|
|
2015-07-01 23:18:48 +02:00
|
|
|
def check_view_permissions(self):
|
2015-01-06 00:11:22 +01:00
|
|
|
"""
|
2015-07-01 23:18:48 +02:00
|
|
|
Returns True if the user has required permissions.
|
2015-01-06 00:11:22 +01:00
|
|
|
"""
|
2016-01-10 10:52:44 +01:00
|
|
|
if self.action in ('metadata', 'list', 'retrieve', 'update', 'partial_update'):
|
2015-07-01 23:18:48 +02:00
|
|
|
result = self.request.user.has_perm('users.can_see_name')
|
2016-01-10 10:52:44 +01:00
|
|
|
elif self.action in ('create', 'destroy', 'reset_password'):
|
2015-07-01 23:18:48 +02:00
|
|
|
result = (self.request.user.has_perm('users.can_see_name') and
|
|
|
|
self.request.user.has_perm('users.can_see_extra_data') and
|
|
|
|
self.request.user.has_perm('users.can_manage'))
|
|
|
|
else:
|
|
|
|
result = False
|
|
|
|
return result
|
2015-01-06 00:11:22 +01:00
|
|
|
|
2015-01-17 14:25:05 +01:00
|
|
|
def get_serializer_class(self):
|
|
|
|
"""
|
2015-02-12 20:57:05 +01:00
|
|
|
Returns different serializer classes with respect to action and user's
|
|
|
|
permissions.
|
2015-01-17 14:25:05 +01:00
|
|
|
"""
|
2015-07-01 23:18:48 +02:00
|
|
|
if (self.action in ('create', 'partial_update', 'update') or
|
2015-05-05 10:42:31 +02:00
|
|
|
self.request.user.has_perm('users.can_see_extra_data')):
|
2015-07-01 23:18:48 +02:00
|
|
|
# Return the UserFullSerializer for edit requests or for
|
|
|
|
# list/retrieve requests of users with more permissions.
|
2015-01-17 14:25:05 +01:00
|
|
|
serializer_class = UserFullSerializer
|
|
|
|
else:
|
|
|
|
serializer_class = UserShortSerializer
|
|
|
|
return serializer_class
|
|
|
|
|
2015-09-06 10:29:23 +02:00
|
|
|
def list(self, request, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Customized view endpoint to list all user.
|
|
|
|
|
2015-09-06 11:38:17 +02:00
|
|
|
Hides the default_password for non admins.
|
2015-09-06 10:29:23 +02:00
|
|
|
"""
|
|
|
|
response = super().list(request, *args, **kwargs)
|
|
|
|
self.extract_default_password(response)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def retrieve(self, request, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Customized view endpoint to retrieve a user.
|
|
|
|
|
2015-09-06 11:38:17 +02:00
|
|
|
Hides the default_password for non admins.
|
2015-09-06 10:29:23 +02:00
|
|
|
"""
|
|
|
|
response = super().retrieve(request, *args, **kwargs)
|
|
|
|
self.extract_default_password(response)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def extract_default_password(self, response):
|
|
|
|
"""
|
|
|
|
Checks if a user is not a manager. If yes, the default password is
|
|
|
|
extracted from the response.
|
|
|
|
"""
|
|
|
|
if not self.request.user.has_perm('users.can_manage'):
|
|
|
|
if isinstance(response.data, dict):
|
|
|
|
del response.data['default_password']
|
|
|
|
elif isinstance(response.data, list):
|
|
|
|
for user in response.data:
|
|
|
|
del user['default_password']
|
|
|
|
|
|
|
|
def update(self, request, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Customized view endpoint to update an user.
|
|
|
|
|
|
|
|
Checks also whether the requesting user can update the user. He
|
|
|
|
needs at least the permissions 'users.can_see_name' (see
|
|
|
|
self.check_view_permissions()). Also it is evaluated whether he
|
|
|
|
wants to update himself or is manager.
|
|
|
|
"""
|
|
|
|
# Check manager perms
|
|
|
|
if (request.user.has_perm('users.can_see_extra_data') and
|
|
|
|
request.user.has_perm('users.can_manage')):
|
2016-01-09 11:59:34 +01:00
|
|
|
if request.data.get('is_active') is False and self.get_object() == request.user:
|
|
|
|
# A user can not deactivate himself.
|
|
|
|
raise ValidationError({'detail': _('You can not deactivate yourself.')})
|
2015-09-06 10:29:23 +02:00
|
|
|
response = super().update(request, *args, **kwargs)
|
|
|
|
else:
|
|
|
|
# Get user.
|
|
|
|
user = self.get_object()
|
|
|
|
# Check permissions only to update yourself.
|
|
|
|
if request.user != user:
|
|
|
|
self.permission_denied(request)
|
|
|
|
# Check permission to send only some data.
|
|
|
|
whitelist = (
|
|
|
|
'username',
|
|
|
|
'title',
|
|
|
|
'first_name',
|
|
|
|
'last_name',
|
2016-01-10 10:52:44 +01:00
|
|
|
'structure_level',
|
2015-09-06 10:29:23 +02:00
|
|
|
'about_me',)
|
2016-01-10 10:52:44 +01:00
|
|
|
keys = list(request.data.keys())
|
|
|
|
for key in keys:
|
|
|
|
if key not in whitelist:
|
|
|
|
# Non-staff users are allowed to send only some data. Ignore other data.
|
|
|
|
del request.data[key]
|
2015-09-06 10:29:23 +02:00
|
|
|
# Validate data and update user.
|
|
|
|
serializer = self.get_serializer(
|
|
|
|
user,
|
|
|
|
data=request.data,
|
|
|
|
partial=kwargs.get('partial', False))
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
serializer.save()
|
|
|
|
response = Response(serializer.data)
|
|
|
|
return response
|
|
|
|
|
2016-01-09 11:59:34 +01:00
|
|
|
def destroy(self, request, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Customized view endpoint to delete an user.
|
|
|
|
|
|
|
|
Ensures that no one can delete himself.
|
|
|
|
"""
|
|
|
|
instance = self.get_object()
|
|
|
|
if instance == self.request.user:
|
|
|
|
raise ValidationError({'detail': _('You can not delete yourself.')})
|
|
|
|
self.perform_destroy(instance)
|
|
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
|
|
|
|
2015-06-18 22:39:58 +02:00
|
|
|
@detail_route(methods=['post'])
|
|
|
|
def reset_password(self, request, pk=None):
|
|
|
|
"""
|
|
|
|
View to reset the password (using the default password).
|
|
|
|
"""
|
|
|
|
user = self.get_object()
|
|
|
|
user.set_password(user.default_password)
|
|
|
|
user.save()
|
|
|
|
return Response({'detail': _('Password successfully reset.')})
|
|
|
|
|
2015-01-06 00:11:22 +01:00
|
|
|
|
2015-02-12 18:48:14 +01:00
|
|
|
class GroupViewSet(ModelViewSet):
|
2015-02-04 00:08:38 +01:00
|
|
|
"""
|
2015-07-01 23:18:48 +02:00
|
|
|
API endpoint for groups.
|
|
|
|
|
2015-08-31 14:07:24 +02:00
|
|
|
There are the following views: metadata, list, retrieve, create,
|
|
|
|
partial_update, update and destroy.
|
2015-02-04 00:08:38 +01:00
|
|
|
"""
|
|
|
|
queryset = Group.objects.all()
|
|
|
|
serializer_class = GroupSerializer
|
|
|
|
|
2015-07-01 23:18:48 +02:00
|
|
|
def check_view_permissions(self):
|
2015-02-04 00:08:38 +01:00
|
|
|
"""
|
2015-07-01 23:18:48 +02:00
|
|
|
Returns True if the user has required permissions.
|
2015-02-04 00:08:38 +01:00
|
|
|
"""
|
2015-08-31 14:07:24 +02:00
|
|
|
if self.action in ('metadata', 'list', 'retrieve'):
|
|
|
|
# Every authenticated user can see the metadata and list or
|
|
|
|
# retrieve groups. Anonymous users can do so if they are enabled.
|
2015-07-01 23:18:48 +02:00
|
|
|
result = self.request.user.is_authenticated() or config['general_system_enable_anonymous']
|
|
|
|
elif self.action in ('create', 'partial_update', 'update', 'destroy'):
|
|
|
|
# Users with all app permissions can edit groups.
|
|
|
|
result = (self.request.user.has_perm('users.can_see_name') and
|
|
|
|
self.request.user.has_perm('users.can_see_extra_data') and
|
|
|
|
self.request.user.has_perm('users.can_manage'))
|
|
|
|
else:
|
|
|
|
# Deny request in any other case.
|
|
|
|
result = False
|
|
|
|
return result
|
2015-02-04 00:08:38 +01:00
|
|
|
|
2015-02-17 00:45:53 +01:00
|
|
|
def destroy(self, request, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Protects builtin groups 'Anonymous' (pk=1) and 'Registered' (pk=2)
|
|
|
|
from being deleted.
|
|
|
|
"""
|
|
|
|
instance = self.get_object()
|
2015-07-01 23:18:48 +02:00
|
|
|
if instance.pk in (1, 2):
|
2015-02-17 00:45:53 +01:00
|
|
|
self.permission_denied(request)
|
2015-07-01 23:18:48 +02:00
|
|
|
self.perform_destroy(instance)
|
|
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
2015-02-17 00:45:53 +01:00
|
|
|
|
2015-02-04 00:08:38 +01:00
|
|
|
|
2015-07-01 23:18:48 +02:00
|
|
|
# Special API views
|
2015-02-12 22:42:54 +01:00
|
|
|
|
|
|
|
class UserLoginView(APIView):
|
|
|
|
"""
|
2015-09-16 00:55:27 +02:00
|
|
|
Login the user.
|
2015-02-12 22:42:54 +01:00
|
|
|
"""
|
2016-01-09 01:10:37 +01:00
|
|
|
http_method_names = ['get', 'post']
|
2015-02-12 22:42:54 +01:00
|
|
|
|
|
|
|
def post(self, *args, **kwargs):
|
|
|
|
form = AuthenticationForm(self.request, data=self.request.data)
|
2015-12-11 16:28:56 +01:00
|
|
|
if not form.is_valid():
|
|
|
|
raise ValidationError({'detail': _('Username or password is not correct.')})
|
|
|
|
self.user = form.get_user()
|
|
|
|
auth_login(self.request, self.user)
|
2015-02-12 22:42:54 +01:00
|
|
|
return super().post(*args, **kwargs)
|
|
|
|
|
|
|
|
def get_context_data(self, **context):
|
2016-01-09 01:10:37 +01:00
|
|
|
"""
|
|
|
|
Adds some context.
|
|
|
|
|
|
|
|
For GET requests adds login info text to context. This info text is
|
|
|
|
taken from the config. If this value is empty, a special text is used
|
|
|
|
if the admin user has the password 'admin'.
|
|
|
|
|
|
|
|
For POST requests adds the id of the current user to the context.
|
|
|
|
"""
|
|
|
|
if self.request.method == 'GET':
|
|
|
|
if config['general_login_info_text']:
|
|
|
|
context['info_text'] = config['general_login_info_text']
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
user = User.objects.get(username='admin')
|
|
|
|
except User.DoesNotExist:
|
|
|
|
context['info_text'] = ''
|
|
|
|
else:
|
|
|
|
if user.check_password('admin'):
|
|
|
|
context['info_text'] = _(
|
|
|
|
'Installation was successfully. Use {username} and '
|
|
|
|
'{password} for first login. Important: Please change '
|
|
|
|
'your password!'.format(
|
|
|
|
username='<strong>admin</strong>',
|
|
|
|
password='<strong>admin</strong>'))
|
|
|
|
else:
|
|
|
|
context['info_text'] = ''
|
|
|
|
else:
|
|
|
|
# self.request.method == 'POST'
|
|
|
|
context['user_id'] = self.user.pk
|
2015-02-12 22:42:54 +01:00
|
|
|
return super().get_context_data(**context)
|
|
|
|
|
|
|
|
|
|
|
|
class UserLogoutView(APIView):
|
|
|
|
"""
|
2015-09-16 00:55:27 +02:00
|
|
|
Logout the user.
|
2015-02-12 22:42:54 +01:00
|
|
|
"""
|
|
|
|
http_method_names = ['post']
|
|
|
|
|
|
|
|
def post(self, *args, **kwargs):
|
2015-12-11 16:28:56 +01:00
|
|
|
if not self.request.user.is_authenticated():
|
|
|
|
raise ValidationError({'detail': _('You are not authenticated.')})
|
2015-02-12 22:42:54 +01:00
|
|
|
auth_logout(self.request)
|
|
|
|
return super().post(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class WhoAmIView(APIView):
|
|
|
|
"""
|
2015-07-01 23:18:48 +02:00
|
|
|
Returns the id of the requesting user.
|
2015-02-12 22:42:54 +01:00
|
|
|
"""
|
|
|
|
http_method_names = ['get']
|
|
|
|
|
|
|
|
def get_context_data(self, **context):
|
|
|
|
"""
|
2015-12-10 00:02:16 +01:00
|
|
|
Appends the user id to the context. Uses None for the anonymous
|
|
|
|
user. Appends also a flag if guest users are enabled in the config.
|
2015-02-12 22:42:54 +01:00
|
|
|
"""
|
|
|
|
return super().get_context_data(
|
|
|
|
user_id=self.request.user.pk,
|
2015-12-10 00:02:16 +01:00
|
|
|
guest_enabled=config['general_system_enable_anonymous'],
|
2015-02-12 22:42:54 +01:00
|
|
|
**context)
|
2015-07-01 23:18:48 +02:00
|
|
|
|
|
|
|
|
2015-11-06 15:44:27 +01:00
|
|
|
class SetPasswordView(APIView):
|
|
|
|
"""
|
|
|
|
Users can set a new password for themselves.
|
|
|
|
"""
|
|
|
|
http_method_names = ['post']
|
|
|
|
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
user = request.user
|
|
|
|
if user.check_password(request.data['old_password']):
|
|
|
|
user.set_password(request.data['new_password'])
|
|
|
|
user.save()
|
|
|
|
else:
|
2015-12-11 16:28:56 +01:00
|
|
|
raise ValidationError({'detail': _('Old password does not match.')})
|
2015-11-06 15:44:27 +01:00
|
|
|
return super().post(request, *args, **kwargs)
|
|
|
|
|
|
|
|
|
2015-07-01 23:18:48 +02:00
|
|
|
# Views to generate PDFs
|
|
|
|
|
|
|
|
class UsersListPDF(PDFView):
|
|
|
|
"""
|
2015-09-16 00:55:27 +02:00
|
|
|
Generate a list of all users as PDF.
|
2015-07-01 23:18:48 +02:00
|
|
|
"""
|
|
|
|
required_permission = 'users.can_see_extra_data'
|
2015-09-16 00:55:27 +02:00
|
|
|
filename = ugettext_lazy('user-list')
|
|
|
|
document_title = ugettext_lazy('List of users')
|
2015-07-01 23:18:48 +02:00
|
|
|
|
|
|
|
def append_to_pdf(self, pdf):
|
|
|
|
"""
|
|
|
|
Append PDF objects.
|
|
|
|
"""
|
|
|
|
users_to_pdf(pdf)
|
|
|
|
|
|
|
|
|
|
|
|
class UsersPasswordsPDF(PDFView):
|
|
|
|
"""
|
|
|
|
Generate the access data welcome paper for all users as PDF.
|
|
|
|
"""
|
|
|
|
required_permission = 'users.can_manage'
|
2015-09-16 00:55:27 +02:00
|
|
|
filename = ugettext_lazy('user-access-data')
|
2015-07-01 23:18:48 +02:00
|
|
|
top_space = 0
|
|
|
|
|
|
|
|
def build_document(self, pdf_document, story):
|
|
|
|
pdf_document.build(story)
|
|
|
|
|
|
|
|
def append_to_pdf(self, pdf):
|
|
|
|
"""
|
|
|
|
Append PDF objects.
|
|
|
|
"""
|
|
|
|
users_passwords_to_pdf(pdf)
|