Storing role in request user

The user in the request will now, in addition to storing his id, also store his role, in order to show his permission rank.

We'll now see something quite interesting: our interface in action. Going back to the RequestUser interface, let's indicate that it should also have the user's role.

readonly role: Role;

Immediately, we can see the AuthService showing errors. This is because the variables that implement this interface are no longer fulfilling its contract. And this is exactly what was intended to happen, in order to be sure that everything is correctly adjusted due to the type safety. So, in both places that an error appeared, let's also return the user's role.

const requestUser: RequestUser = { id: user.id, role: user.role };

However, you may have noticed that we are repeating the same step in both validation methods. So, let's encapsulate this logic in an aux method.

private createRequestUser(user: User) {
  const { id, role } = user;
  const requestUser: RequestUser = { id, role };
  return requestUser;
}

And now, have as return of the two validation methods, the call to this aux method.

return this.createRequestUser(user);

Excellent! We're already storing the user's role in the user field of the request. We can now focus on protecting the routes according to the users' permissions.

Commit - Storing role in request user

Last updated