- Purpose: Handles user authentication and token generation for subsequent API requests.
-
Serializer Class:
serializer_class = CustomUserSerializer
This specifies the serializer to use for validating user data, although it is not explicitly used in this method.
-
Retrieving Credentials:
username = request.data.get("username") password = request.data.get("password")
The
POST
request contains the username and password provided by the user. -
User Lookup:
user = CustomUser.objects.filter(username=username).first()
- Searches for a user with the given username.
- Uses
filter
to ensure the query doesn't raise an exception if no user is found. - Retrieves the first matching user or
None
if no match exists.
-
Password Verification:
if user and user.check_password(password):
- Verifies the password using Django's
check_password
method, which compares the hashed password stored in the database with the input.
- Verifies the password using Django's
-
Login and Token Creation:
login(request, user) token = Token.objects.create(user=user)
- Logs in the user by attaching their session to the
request
. - Creates a unique authentication token for the user using Django's
Token
model.
- Logs in the user by attaching their session to the
-
Response:
return Response({'message': 'user logged in', 'token': token.key}, status=status.HTTP_200_OK)
- Returns a success message along with the generated token.
- This token will be used for authenticating subsequent API requests.
-
Invalid Credentials:
return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST)
- If authentication fails, an error response is returned.
- Purpose: Handles token deletion and user logout.
-
Permission Check:
permission_classes = [IsAuthenticated]
- Ensures that only authenticated users can access this view.
-
Token Deletion:
request.user.auth_token.delete()
- Deletes the token associated with the currently authenticated user.
- This effectively invalidates the user's authentication for future requests.
-
User Logout:
logout(request)
- Logs the user out by clearing their session.
-
Response:
return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK)
- Returns a success message confirming the logout.
- The user provides valid credentials (username and password).
- A unique token is generated for the user:
- Stored in the
Token
model with a one-to-one relationship to the user. - The token is sent to the client in the response.
- Stored in the
- The client stores the token (e.g., in local storage or memory) and sends it with every API request in the header:
Authorization: Token <token_value>
- The user sends a logout request with their token.
- The server identifies the user using the provided token and deletes it from the database:
- The token becomes invalid, and the user can no longer authenticate using it.
- The user's session is cleared, ensuring a clean logout.
- LoginView:
- Authenticates the user.
- Issues a token for API authentication.
- LogoutView:
- Deletes the token, revoking API access.
- Logs the user out by clearing their session.
This mechanism ensures stateless, secure authentication where the token is the key to accessing protected resources.
To make a request for login using the LoginView
, the client (such as a frontend application, Postman, or a cURL command) sends a POST request with the user's credentials in the request body.
The login endpoint URL is defined in urls.py
:
path('login/', LoginView.as_view(), name='user-login'),
The URL to send the login request might look like:
http://127.0.0.1:8000/api/v1/login/
The method for login is POST, as defined in the post
method of the LoginView
class.
Headers typically include:
- Content-Type:
application/json
(if sending JSON data). - No token is required since this is a public endpoint for unauthenticated users.
Example headers:
Content-Type: application/json
The request body contains the user's credentials:
{
"username": "user123",
"password": "securepassword"
}
curl -X POST http://127.0.0.1:8000/login/ \
-H "Content-Type: application/json" \
-d '{"username": "user123", "password": "securepassword"}'
- Set the method to POST.
- Enter the URL
http://127.0.0.1:8000/login/
. - Go to the Body tab:
- Choose
raw
. - Set the body type to JSON.
- Enter:
{ "username": "user123", "password": "securepassword" }
- Choose
- Send the request.
axios.post('http://127.0.0.1:8000/login/', {
username: 'user123',
password: 'securepassword'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error.response.data);
});
If the credentials are correct, the server responds with a 200 OK status and a token in the body:
{
"message": "user logged in",
"token": "8951a608c193c5e6bb1b600c77520538aa477bba"
}
If the credentials are invalid, the server responds with a 400 Bad Request status and an error message:
{
"error": "Invalid credentials"
}
- The server receives the request and extracts the
username
andpassword
. - It looks up the user in the database using:
user = CustomUser.objects.filter(username=username).first()
- If the user exists, it checks the password using:
user.check_password(password)
- If authentication is successful:
- The user is logged in with
login(request, user)
. - A token is generated using:
token = Token.objects.create(user=user)
- The token is returned in the response.
- The user is logged in with
- If authentication fails, an error message is returned.
This process securely validates the user's credentials and provides them with a token for future API access.