In our previous blog post, 

we walked through the process of creating a user registration API using Rust and Actix-Web. Now, we'll continue by implementing the login API to authenticate users. This is a natural next step after allowing users to register, as it enables them to securely access their accounts.

In this post, we'll build on the existing codebase, adding a new LoginRequest model, implementing the login logic, and integrating the login endpoint into our application. Let’s dive in!

Recap: What We Built Earlier

In the first part, we created a user registration API that:

Now, we’ll allow users to log in by verifying their credentials against the stored data.

Step 1: Define the LoginRequest Model

To handle login requests, we need a new model that captures the user's input. This model will include:

Here’s the code to add to src/models.rs:

This model will be used to parse the JSON payload sent by the client during the login process.

Step 2: Implement the Login Function

Next, we’ll implement the login_user function in the authentication module. This function will:

Here’s the implementation:

Explanation of the Code:

Step 3: Add the Login Route to the Application

Finally, we need to expose the login functionality via an API endpoint. We’ll add a new route to the main.rs file:

Key Points:

Testing the Login API

To test the login functionality, you can use tools like Postman or cURL. Here’s an example request:

Request:

Responses:

User Not Found (404 Not Found):

Server Error (500 Internal Server Error):

Conclusion

In this post, we extended our Rust Actix-Web application by adding a login API. This allows users to authenticate using their username or email and password. By leveraging bcrypt for password verification and sqlx for database interactions, we’ve built a secure and efficient authentication system.