Commit 08559ed68aa9c84c0a711f2c0ec6b110018ec812
1 parent
4401f6495c
Exists in
master
User login auth added api.py
Showing 2 changed files with 27 additions and 2 deletions Side-by-side Diff
flashcards/api.py
View file @
08559ed
1 | 1 | from django.core.mail import send_mail |
2 | +from django.contrib.auth import authenticate, login | |
2 | 3 | from rest_framework.views import APIView |
3 | 4 | from rest_framework.response import Response |
4 | 5 | from rest_framework import status |
... | ... | @@ -56,4 +57,28 @@ |
56 | 57 | [user.email]) |
57 | 58 | |
58 | 59 | return Response(UserSerializer(User).data) |
60 | + | |
61 | +class UserLogin(APIView): | |
62 | + """ | |
63 | + Authenticates user and returns user data if valid. Handles invalid | |
64 | + users. | |
65 | + """ | |
66 | + def post(self, request, format=None): | |
67 | + if 'email' not in request.data: | |
68 | + raise ValidationError('Email is required') | |
69 | + if 'password' not in request.data: | |
70 | + raise ValidationError('Password is required') | |
71 | + | |
72 | + email = request.data['email'] | |
73 | + password = request.data['password'] | |
74 | + user = authenticate(username=email, password=password) | |
75 | + | |
76 | + if user is not None: | |
77 | + if user.is_active: | |
78 | + login(request, user) | |
79 | + return Response(UserSerializer(User).data) | |
80 | + else: | |
81 | + raise ValidationError('Account is disabled') | |
82 | + else: | |
83 | + raise ValidationError('Invalid email or password') |
flashy/urls.py
View file @
08559ed
... | ... | @@ -9,7 +9,8 @@ |
9 | 9 | router.register(r'lectureperiods', LecturePeriodViewSet) |
10 | 10 | |
11 | 11 | urlpatterns = [ |
12 | - url(r'^api/user/me$', UserDetail.as_view()), | |
12 | + url(r'^api/users/me$', UserDetail.as_view()), | |
13 | + url(r'^api/login$', UserLogin.as_view()), | |
13 | 14 | url(r'^api/', include(router.urls)), |
14 | 15 | url(r'^admin/doc/', include('django.contrib.admindocs.urls')), |
15 | 16 | url(r'^admin/', include(admin.site.urls)), |