Advertisement
Guest User

Untitled

a guest
Sep 20th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. class LoginUserAPIView(APIView):
  2. permission_classes = () # login should be accessed by anyone, no restrictions.
  3. def post(self, request, format=None):
  4. username = request.data['username']
  5. password = request.data['password']
  6.  
  7. user = authenticate(username=username, password=password)
  8.  
  9. if user is not None:
  10. login(request, user)
  11. user = UserSerializer(user)
  12. return Response({'success': 'Logged in', 'user': user.data})
  13. return Response({'wrong': 'username or password not correct, try again'}, status=status.HTTP_401_UNAUTHORIZED)
  14.  
  15. login() {
  16. this.isLoading = true;
  17. return axios({
  18. method: 'post',
  19. url: 'http://localhost:8000/api/login_user',
  20. data: {
  21. username: this.name,
  22. password: this.password
  23. },
  24. headers: {
  25. 'Content-Type': 'application/json'
  26. }
  27. })
  28. .then(response => {
  29. this.$store.commit('loginAuth', true); // setting isAuth to true in vuex store.
  30. this.$store.commit('setUser', response.data.user); // to access the user object since I don't use django templates
  31. this.$router.push({name: 'page'}); // redirect to random test page that requires authorization so I can see if everything went fine.
  32. })
  33. .catch(err => {
  34. console.error(err);
  35. if (err.response.status == 401) {
  36. alert(err.response.data.wrong);
  37. this.isLoading = false;
  38. }
  39. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement