Creating Users Controller
In this lesson, we're going to create Users controller
Creating Users controller#
Now let's create a users controller so that our frontend can create and get users. Inside controllers, we can create a new class, UsersController. Like always, let's derive it from the BaseController, let's create a new constructor where we'll inject the UserManager with User type and name, userManager. Let's import it, along with the User from entity and initialize field from parameter. We will interact with the database with the help of the userManager. It will help us in verifying the password or checking if the user exists or creating a new user. Also, we don't have to use the savechanges async method with the usermanager. It handles it automatically behind the scenes.
So let's start implementing the API now. Let's start with the login endpoint. It will be a post request so let's call it http post with name login. Below this, we will write public async task which will return an action result of type user; let's call it login. Let's import ActionResult from system threading tasks. Also, let's import Http post from AspNetCore.Mvc. Rather than hardcoding the required parameters, let's create a login class inside the Dto folder; we can call it LoginDto. We just need the Email of type string and a password of type string. Coming back to the UsersController, let's mention the LoginDto here, and let's import it. Since we're going to pass the user information inside body, we don't have to explicitly mention body here, like we would do if we were expecting the data from the query.
First of all, we will check if the user already exists. Let's write var user, and await userManager.FindByEmailAsync. This method takes the email as a parameter, so let's pass loginDto dot email. If the user exists, it will give us the user. If not, it will return null. Now we can check if the user is null or the password is incorrect, for which, we can use userManager dot check password async method. It takes the user as the first parameter and the password as the second. If it is false, we can return Unauthorized with new ApiResponse 401. Finally, if everything is correct, we can return the user.