Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @api_view(['POST'])
- def user_login(request):
- """
- **User Login**
- Login an existing user.
- Used for authenticating the user.
- > POST
- * Requires following fields of users in JSON format:
- 1. `email` - String
- 2. `password` - String
- * Returns user profile data on successful login.
- * Also returns Authentication token to be used by frontend for further
- communication with backend.
- * On failure it returns appropriate HTTP status and message in JSON
- response.
- * Possible HTTP status codes and JSON response:
- * `HTTP_200_OK` on successful login.
- {
- "message": Login successful,
- "email": String,
- "token": String,
- "id": Integer
- }
- * `HTTP_401_UNAUTHORIZED` for failed login attempt.
- {
- "message": "Invalid username or password"
- }
- * `HTTP_500_INTERNAL_SERVER_ERROR` - Internal server error.
- * `HTTP_404_NOT_FOUND` - When user is not found.
- {
- "message": "User with specified email does not exist."
- }
- * Status code can be used from HTTP header. A separate status field in json
- data is not provided.
- :param request:
- """
- try:
- email = request.data['email']
- password = request.data['password']
- except KeyError:
- return Response(
- "Email and Password required",
- status=status.HTTP_400_BAD_REQUEST
- )
- response = utils.check_user_exists_for_login(email)
- if response is True:
- return authenticate_user(
- email, password, request=request)
- else:
- return response
- def check_user_exists_for_login(email):
- try:
- User.objects.get(email=email)
- return True
- except User.DoesNotExist: #'User' is User table in database
- return Response(
- "User with specified email does not exist.",
- status=status.HTTP_404_NOT_FOUND)
- def authenticate_user(email, password, request=None):
- user = authenticate(email=email, password=password)
- if user:
- serializer_dict["message"] = "Login successful"
- return Response(serializer_dict, status=status.HTTP_200_OK)
- else:
- return Response("Invalid email or password", status=status.HTTP_401_UNAUTHORIZED)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement