Advertisement
Guest User

Untitled

a guest
Feb 15th, 2016
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. @api_view(['POST'])
  2. def user_login(request):
  3. """
  4. **User Login**
  5. Login an existing user.
  6. Used for authenticating the user.
  7.  
  8. > POST
  9.  
  10. * Requires following fields of users in JSON format:
  11.  
  12. 1. `email` - String
  13. 2. `password` - String
  14.  
  15. * Returns user profile data on successful login.
  16. * Also returns Authentication token to be used by frontend for further
  17. communication with backend.
  18. * On failure it returns appropriate HTTP status and message in JSON
  19. response.
  20.  
  21. * Possible HTTP status codes and JSON response:
  22.  
  23. * `HTTP_200_OK` on successful login.
  24.  
  25. {
  26. "message": Login successful,
  27. "email": String,
  28. "token": String,
  29. "id": Integer
  30. }
  31.  
  32. * `HTTP_401_UNAUTHORIZED` for failed login attempt.
  33.  
  34. {
  35. "message": "Invalid username or password"
  36. }
  37.  
  38. * `HTTP_500_INTERNAL_SERVER_ERROR` - Internal server error.
  39.  
  40. * `HTTP_404_NOT_FOUND` - When user is not found.
  41.  
  42. {
  43. "message": "User with specified email does not exist."
  44. }
  45.  
  46. * Status code can be used from HTTP header. A separate status field in json
  47. data is not provided.
  48. :param request:
  49.  
  50. """
  51. try:
  52. email = request.data['email']
  53. password = request.data['password']
  54.  
  55. except KeyError:
  56. return Response(
  57. "Email and Password required",
  58. status=status.HTTP_400_BAD_REQUEST
  59. )
  60.  
  61. response = utils.check_user_exists_for_login(email)
  62. if response is True:
  63. return authenticate_user(
  64. email, password, request=request)
  65. else:
  66. return response
  67.  
  68.  
  69. def check_user_exists_for_login(email):
  70. try:
  71. User.objects.get(email=email)
  72. return True
  73. except User.DoesNotExist: #'User' is User table in database
  74. return Response(
  75. "User with specified email does not exist.",
  76. status=status.HTTP_404_NOT_FOUND)
  77.  
  78.  
  79.  
  80. def authenticate_user(email, password, request=None):
  81. user = authenticate(email=email, password=password)
  82. if user:
  83. serializer_dict["message"] = "Login successful"
  84.  
  85. return Response(serializer_dict, status=status.HTTP_200_OK)
  86. else:
  87. return Response("Invalid email or password", status=status.HTTP_401_UNAUTHORIZED)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement