Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

90 righe
2.6 KiB

  1. import json
  2. from django.conf import settings
  3. from django.contrib import messages
  4. from django.contrib.auth import authenticate, login, logout
  5. from django.contrib.auth.decorators import login_required
  6. from django.core.urlresolvers import reverse
  7. from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponse
  8. from django.utils.functional import lazy
  9. from rest_framework import mixins, routers
  10. from rest_framework.permissions import BasePermission
  11. from rest_framework.renderers import JSONRenderer
  12. from rest_framework.viewsets import GenericViewSet
  13. from core.serializers import UserSerializer
  14. from users.models import User
  15. def reverse_lazy(name=None, *args):
  16. return lazy(reverse, str)(name, args=args)
  17. class UserViewSet(
  18. mixins.RetrieveModelMixin,
  19. mixins.ListModelMixin,
  20. mixins.CreateModelMixin,
  21. GenericViewSet,
  22. ):
  23. class Permission(BasePermission):
  24. def has_permission(self, request, view):
  25. if not request.method == "POST":
  26. return True
  27. return settings.ALLOW_NEW_REGISTRATIONS
  28. def has_object_permission(self, request, view, obj):
  29. return request.user == obj
  30. permission_classes = [Permission, ]
  31. serializer_class = UserSerializer
  32. pagination_class = None
  33. def get_queryset(self):
  34. if self.request.user.is_anonymous:
  35. return User.objects.none()
  36. return User.objects.filter(id=self.request.user.id)
  37. def login_user(request):
  38. try:
  39. data = json.loads(request.body)
  40. except json.JSONDecodeError:
  41. return HttpResponseBadRequest()
  42. if 'username' not in data:
  43. return HttpResponseBadRequest(
  44. json.dumps({"username": "this field is required"})
  45. )
  46. if 'password' not in data:
  47. return HttpResponseBadRequest(
  48. json.dumps({"password": "this field is required"})
  49. )
  50. user = authenticate(
  51. request,
  52. username=data['username'],
  53. password=data['password']
  54. )
  55. if not user:
  56. return HttpResponseBadRequest(
  57. json.dumps({"password": "username and password doesn't match"})
  58. )
  59. login(request, user)
  60. data = UserSerializer(
  61. user,
  62. context={'request': request},
  63. ).data
  64. return HttpResponse(
  65. JSONRenderer().render(data),
  66. content_type="application/json"
  67. )
  68. @login_required
  69. def logout_user(request):
  70. logout(request)
  71. messages.success(request, 'You have successfully logged out.')
  72. return HttpResponseRedirect('/')
  73. drf_router = routers.DefaultRouter()
  74. drf_router.register(r'users', UserViewSet, base_name="user")