Part 2 of How to Implement Activity Logs API
Let's continue from where we left,
Step 3: Add the API View
ActivityLogViewSet to include a custom method for handling user login activity. In this method, you can retrieve the user's IP address and create an activity log based on the login status. Here's an example:
In this code, we retrieve the user's IP address from the request's
META data. Then, we authenticate the user using the provided username and password. Depending on the authentication result, we set the login status to either "SUCCESS" or "FAILED". Finally, we create an
ActivityLog instance with the relevant information and save it to the database.
Step 4: Add the URLs
To make the login activity endpoint accessible, we need to update the URLs configuration. In your Django app's URLs file (
urls.py), include the new login activity endpoint:
Implementing user login activity logs with IP addresses is essential for monitoring and auditing user actions. By following the steps outlined in this blog post, you can easily add this functionality to your Django application. Remember to customize the code to fit your specific requirements and authentication system.
By keeping a record of user login activity, you can enhance the security of your Django app and gain valuable insights into user behavior.