Current User Endpoint
In this lesson, we're going to create an endpoint for current user
Current User endpoint#
We have added one more property to the User model which is the courses that they've purchased. We can return the courses with the userDto which we are returning when the user is logged in. We can create another endpoint, currentUser, which will return the same UserDto, but we will make this request authorized so that only users who have logged in can make this request.
Let's go to the UsersController and create a new HttpGet request with name, currentUser. Let's also use Authorize on top of it. This will return UserDto as well so we can write public async task of action result of user dto. Let's call this GetCurrentUser and inside, we need a user for which we will use usermanager dot findByNameAsync method and pass user dot identity dot name. We also need basket for which we can copy the logic from signin method. Now, we need to get courses which were added to the User's account. If you remember, we have created a UserCourses table which is working as a join between User and Course table. Let's write a new variable, courses, and make this equal to context dot UserCourses dot AsQueryable. We need to make this Queryable because we want to use the Where condition on this. Now that we are inside UserDto, let's add Courses which will be List of course.
Coming back to the Users Controller, let's add courses property which will be equal to courses.Where, x dot UserId is equal to user.Id, and now we want to select the course which we will return, so we can use u.Course and use ToList to return it as a list. Let's return the same from a login function. We can copy this and paste this. Now, whenever the user logs in, they will receive the basket and all the courses they've purchased.