assignUserToResource

The assignUserToResource() method in the UserRoleAssignService is designed to assign a specific role to a user for a given resource. It is responsible for ensuring that a user is granted appropriate access permissions by establishing a relationship between the user, their role, and the resource they are interacting with.

Arguments

The method accepts a single args object that contains the following properties:
  • userID: A string that uniquely identifies the user.
  • userRole: An enum value of RoleAlias indicating the alias of the role to be assigned.
  • resource: A string that uniquely identifies the resource.
  • userType: An enum value of UserType representing the type of the user.
  • validUntil (optional): A Date object representing the expiry date of the role assignment. If not provided, it defaults to a distant future date, effectively making the assignment indefinitely valid.

Behavior

  1. Role Retrieval: The method starts by retrieving the role using the findOne() method from a RoleService based on the provided userRole alias.
  2. Assignment Check: Before proceeding with the assignment, it checks whether the user is already assigned to the resource with the given role to avoid duplicate assignments.
  3. Role Assignment: If the user is not already assigned, it proceeds to create a new UserRoleAssign document, which includes the user’s ID, role ID, resource ID, and the type of user, along with the validity period of the assignment.
  4. Type-specific Logic: Additionally, it includes logic to handle type-specific conditions to tailor the role assignment according to the user’s type.
  5. Creation: Finally, it uses the create() method to persist the new role assignment in the database.

Returns

The method returns a promise which, upon successful assignment, resolves to the newly created UserRoleAssign document. If the role does not exist or the user is already assigned to the resource, the promise may resolve to null or throw an error, depending on the implementation.

Example

Service Usage
await this.userRoleAssignService.assignUserToResource({
  userID: "some-user-id",
  userRole: RoleAlias.APP_USER,
  userType: UserType.USER,
  resource: "some-resource-id",
  validUntil: new Date("2023-12-31"), // optional
});
In this example, assignUserToResource() is invoked to assign a user with the APP_USER role to a resource identified by some-resource-id. The user type is specified as USER, and an optional validity date is provided.