# Class UserService

Namespace
  adas_core.Authentication

Assembly
  adas-core.Authentication.dll

Provides the concrete implementation of user-related service operations defined by the IUserService contract.

    public class UserService : IUserService

Inheritance
  object
  UserService

Implements
  IUserService

Inherited Members
  object.Equals(object)
  object.Equals(object, object)
  object.GetHashCode()
  object.GetType()
  object.MemberwiseClone()
  object.ReferenceEquals(object, object)
  object.ToString()

Extension Methods
  NumberUtils.IsNumber(object)
  NumberUtils.ToDouble(object)
  ObjectUtils.ToStr(object?)

## Remarks

This class is the default service component responsible for handling user domain logic and delegating persistence or infrastructure concerns as required by the interface.

## Constructors

### UserService(IEnumerable<ILoginService>, IOptions<AuthSettings>, IOptions<ValidGroupsConfig>, IOptions<AuthSettings>, IOptions<AuthSettings>, IHttpContextAccessor, IUserRepository, IAuthorityService, ILocalAuditService, Lazy<IDisplayService>, ILogger<UserService>, ISubscribersService, IClientMessageService, Lazy<IPermissionService>)

    public UserService(IEnumerable<ILoginService> loginServices, IOptions<AuthSettings> configuration, IOptions<ValidGroupsConfig> validGroups, IOptions<AuthSettings> usersWhiteList, IOptions<AuthSettings> jwt, IHttpContextAccessor httpContextAccessor, IUserRepository userRepository, IAuthorityService authorityService, ILocalAuditService auditService, Lazy<IDisplayService> displayService, ILogger<UserService> logger, ISubscribersService subscribersService, IClientMessageService clientMessageService, Lazy<IPermissionService> permissionService)

#### Parameters

`loginServices` IEnumerable<ILoginService>
`configuration` IOptions<AuthSettings>
`validGroups` IOptions<ValidGroupsConfig>
`usersWhiteList` IOptions<AuthSettings>
`jwt` IOptions<AuthSettings>
`httpContextAccessor` IHttpContextAccessor
`userRepository` IUserRepository
`authorityService` IAuthorityService
`auditService` ILocalAuditService
`displayService` Lazy<IDisplayService>
`logger` ILogger<UserService>
`subscribersService` ISubscribersService
`clientMessageService` IClientMessageService
`permissionService` Lazy<IPermissionService>

## Methods

### ClaimsFromAuthorities(List<Authorization>)

Asynchronously resolves a list of Claim objects from the provided Authorization entries. When an authorization has a `UnitId`, the associated display is looked up and its identifier is assigned to the authorization before the claim is added; otherwise, the claim is added directly.

    public Task<List<Claim>> ClaimsFromAuthorities(List<Authorization> authorities)

#### Parameters

`authorities` List<Authorization>

  The list of authorizations to convert into claims.

#### Returns

Task<List<Claim>>

  A task that represents the asynchronous operation, containing the list of claims built from the supplied authorities.

### CreateNewAuthority(Authorization)

Creates a new user authority based on the provided authorization. If the underlying authority service returns a null result, indicating that the creation failed, a conflict exception is raised.

    public Task<Authorization> CreateNewAuthority(Authorization auth)

#### Parameters

`auth` Authorization

  The authorization used to create the new user authority.

#### Returns

Task<Authorization>

  The newly created Authorization instance.

#### Exceptions

ConflictException

  Thrown when the authority service fails to create the user authority (returns null).

### CreateNewUserByRequest(User)

Creates a new user after validating email and username uniqueness; for local accounts, it enforces password strength and hashes the password before persistence.

    public Task<User?> CreateNewUserByRequest(User user)

#### Parameters

`user` User

  The user to create, including email, username, password, and account type.

#### Returns

Task<User>

  The created user retrieved by username after insertion.

#### Exceptions

UnprocessableEntityException

  Thrown when a local user's password is not considered strong.

NotFoundException

  Thrown when the user cannot be retrieved by username after insertion.

### CreateNewUserWithAuthorities(CreateUserWithAuthDto)

Creates a new user along with the specified authorizations, associating each authorization with the newly created user. Throws an exception if the user cannot be created.

    public Task<User?> CreateNewUserWithAuthorities(CreateUserWithAuthDto createUserWithAuthDto)

#### Parameters

`createUserWithAuthDto` CreateUserWithAuthDto

  The data transfer object containing the user details and the list of authorizations to associate with the new user.

#### Returns

Task<User>

  The newly created user, or `null` if creation fails (in which case an exception is thrown instead).

#### Exceptions

NotFoundException

  Thrown when the user cannot be created by the underlying request, indicating a missing resource.

### CreateUser(User)

Creates a new user from LDAP data after validating that the username and email are not already in use, persists the entry, and records the creation in the audit log.

    public Task<User?> CreateUser(User userEntryLdap)

#### Parameters

`userEntryLdap` User

  The user information sourced from LDAP to be created in the system.

#### Returns

Task<User>

  The created user retrieved by username, or null if the user cannot be found after insertion.

### DeleteAuthority(string)

Deletes a user authority identified by the specified string identifier. Validates the identifier format and throws if the deletion cannot be completed.

    public Task<bool> DeleteAuthority(string id)

#### Parameters

`id` string

  The string representation of the authority's ObjectId to delete.

#### Returns

Task<bool>

  A task that resolves to `true` when the authority is successfully deleted.

#### Exceptions

BadRequestException

  Thrown when the provided `id` is not a valid ObjectId format.

ConflictException

  Thrown when the underlying delete operation fails.

### DeleteUser(ObjectId)

Deletes a user by its identifier, records an audit log entry for the deletion, and returns the operation result. Returns `false` if an error occurs during deletion, in which case the exception is logged.

    public Task<bool> DeleteUser(ObjectId id)

#### Parameters

`id` ObjectId

  The identifier of the user to delete.

#### Returns

Task<bool>

  A task that resolves to `true` when the user is successfully deleted; otherwise, `false` if an error is encountered.

### GenerateJwt(User)

Generates a JSON Web Token (JWT) pair (access and refresh) for the specified user, including claims derived from the user's authorization data when available.

    public Task<TokenResult> GenerateJwt(User user)

#### Parameters

`user` User

  The user whose identity, email, IP address, and authorization claims will be embedded in the generated tokens.

#### Returns

Task<TokenResult>

  A TokenResult containing the serialized access and refresh tokens, their respective expiration times, and the associated user.

### GetAll()

Retrieves the list of all users by attempting each valid login method in order, selecting the first service that supports password authentication. If a service throws a BusinessException it is remembered and the next service is tried; other exceptions are logged and wrapped in a LoginServicesException. Throws the captured exception from the last attempt, or LoginServicesNotFoundException when no suitable login service is found.

    public Task<List<User>> GetAll()

#### Returns

Task<List<User>>

  A task that resolves to the list of User objects returned by the first successful login service.

#### Exceptions

LoginServicesException

  Thrown when a non-business exception occurs while retrieving users from a service.

LoginServicesNotFoundException

  Thrown when no login service matches the valid login methods or all attempts fail without a captured business exception.

### GetPaginatedUsers(PaginationFilter)

Retrieves a paginated list of users based on the provided filter, including the total document count for pagination metadata.

    public Task<PaginationResponse<User>> GetPaginatedUsers(PaginationFilter filter)

#### Parameters

`filter` PaginationFilter

  The pagination filter containing the page number and page size used to skip, limit, and shape the result set.

#### Returns

Task<PaginationResponse<User>>

  A task that represents the asynchronous operation. The task result contains a PaginationResponse<T> with the requested page of users and pagination details.

### GetUser(string, string)

Authenticates a user by iterating through the configured valid login methods, attempting each available password-enabled service until one succeeds. If every login attempt fails, a LoginServicesNotFoundException is thrown.

    public Task<User> GetUser(string username, string password)

#### Parameters

`username` string

  The username to authenticate.

`password` string

  The password to authenticate against.

#### Returns

Task<User>

  The authenticated User returned by the first successful login service.

#### Exceptions

LoginServicesNotFoundException

  Thrown when no configured login service successfully authenticates the user.

### GetUserByCasTicket(string, string)

Authenticates a user using a CAS (Central Authentication Service) ticket and returns the associated user if authorization succeeds.

    public Task<User?> GetUserByCasTicket(string serviceUrl, string ticket)

#### Parameters

`serviceUrl` string

  The URL of the service requesting CAS authentication.

`ticket` string

  The CAS ticket issued by the CAS server to validate.

#### Returns

Task<User>

  The authenticated User if the ticket is valid and the user passes whitelist and group checks; otherwise, an exception is thrown.

#### Exceptions

LoginServicesException

  Thrown when the CAS login method is not available, or when an unexpected error occurs during authentication.

UnauthorizedAccessException

  Thrown when the authenticated user is not in the users whitelist and does not belong to any valid group.

BusinessException

  Rethrown when a business-level error occurs during the login process.

### GetUserById(ObjectId)

Retrieves a user by their unique identifier, including the user's assigned authorities when the user is found. Returns `null` if the user does not exist or if an error occurs while loading the user or its authorities.

    public Task<User?> GetUserById(ObjectId id)

#### Parameters

`id` ObjectId

  The unique identifier of the user to retrieve.

#### Returns

Task<User>

  A Task<TResult> containing the user with its authorization populated, or `null` if the user cannot be found or an exception is thrown during retrieval.

### GetUserByName(string)

Retrieves a user by their name, including the user's authorization information if the user is found. Returns `null` if the user does not exist or if an error occurs while retrieving the data.

    public Task<User?> GetUserByName(string name)

#### Parameters

`name` string

  The name of the user to look up.

#### Returns

Task<User>

  A User instance with its `Authorization` populated when found; otherwise, `null`.

### GetUserByToken(JwtSecurityToken?)

Retrieves the user associated with the provided JWT security token. Returns `null` if the token is `null` or if no matching user is found.

    public Task<User?> GetUserByToken(JwtSecurityToken? jwtToken)

#### Parameters

`jwtToken` JwtSecurityToken

  The JWT security token used to identify the user. May be `null`.

#### Returns

Task<User>

  A task that resolves to the User associated with the token, or `null` if the token is invalid or no user matches.

### GetUserByUserName(string)

Retrieves a user by their username, including their assigned authorities. Returns null if no user with the specified name exists.

    public Task<User?> GetUserByUserName(string name)

#### Parameters

`name` string

  The username to look up.

#### Returns

Task<User>

  The matching User with its `Authorization` property populated from the authority service, or `null` if no user is found.

### Login(string, string)

Authenticates a user with the provided credentials and generates a JWT token upon successful authentication. Performs validations for user existence, account status (enabled and not locked), and authorization via whitelist or group membership. Updates the user's last login timestamp and clears the lock expiration if it has expired before issuing the token.

    public Task<TokenResult> Login(string username, string password)

#### Parameters

`username` string

  The username used to look up the user account.

`password` string

  The password used to verify the user's credentials.

#### Returns

Task<TokenResult>

  A Task<TResult> containing the generated TokenResult for the authenticated user.

#### Exceptions

UnauthorizedException

  Thrown when no user matches the provided credentials, or when the user is not in the whitelist or valid groups.

ForbbidenException

  Thrown when the user account is disabled or currently locked.

### LoginWithAccessToken(string)

Authenticates a user using a previously issued access token and issues a new JWT. Validates the provided token, retrieves the associated user, and loads user authorities on demand before generating the authentication response.

    public Task<TokenResult> LoginWithAccessToken(string token)

#### Parameters

`token` string

  The access token used to identify and authenticate the user.

#### Returns

Task<TokenResult>

  A Task<TResult> containing the generated JWT for the authenticated user.

#### Exceptions

NotFoundException

  Thrown when no user is found that matches the validated access token.

### LoginWithGivenAccessToken(string)

Authenticates a user using a provided access token and returns a new token pair. Validates the token, retrieves the associated user, and either generates a fresh JWT if the original is expired, or issues new access and refresh tokens preserving the remaining lifetime of the supplied token.

    public Task<TokenResult> LoginWithGivenAccessToken(string token)

#### Parameters

`token` string

  The access token to validate and use for user authentication.

#### Returns

Task<TokenResult>

  A TokenResult containing the new access token, refresh token, their expiry times, and the authenticated user.

#### Exceptions

NotFoundException

  Thrown when no user can be resolved from the provided token.

### RefreshToken(string)

Refreshes a JWT token using the provided refresh token. Validates the refresh token, retrieves the associated user, and generates a new JWT; if the user is not found, returns an empty TokenResult.

    public Task<TokenResult> RefreshToken(string refreshToken)

#### Parameters

`refreshToken` string

  The refresh token used to generate a new JWT.

#### Returns

Task<TokenResult>

  A TokenResult containing the new JWT, or an empty result if the user associated with the token is not found.

### UpdateAuthority(Authorization)

Updates the authority for the specified authorization entry. If the underlying authority service returns a null result, a conflict is raised to signal that the update could not be applied.

    public Task<bool> UpdateAuthority(Authorization authorization)

#### Parameters

`authorization` Authorization

  The authorization details used to update the user's authority.

#### Returns

Task<bool>

  A task that resolves to `true` when the authority is successfully updated.

#### Exceptions

ConflictException

  Thrown when the authority service returns a null response, indicating the update failed.

### UpdateUserPassword(ObjectId, string, string)

Updates the password of an existing user after validating the current password and the strength of the new one, logging the change and recording an audit entry on success.

    public Task<bool> UpdateUserPassword(ObjectId id, string oldPassword, string newPassword)

#### Parameters

`id` ObjectId

  The unique identifier of the user whose password will be updated.

`oldPassword` string

  The user's current password, used to verify the request before applying the change.

`newPassword` string

  The new password to set; must differ from the current password and meet the strength policy.

#### Returns

Task<bool>

  A task that resolves to `true` when the password is successfully updated, or `false` if the repository update returns no result.

#### Exceptions

BadRequestException

  Thrown when `newPassword` is equal to `oldPassword`.

NotFoundException

  Thrown when no user exists for the supplied `id`.

UnprocessableEntityException

  Thrown when `oldPassword` does not match the user's current password, or when `newPassword` does not satisfy the strength policy.

### UpdateUserWithAuthorities(UpdateUserWithAuthDto, bool)

Updates an existing user together with the associated authorities (roles/permissions), validating that the email and user name remain unique. Deletes, updates, and creates authorities according to the provided DTO, and broadcasts the new permission set whenever at least one authority change has been applied.

    public Task<User?> UpdateUserWithAuthorities(UpdateUserWithAuthDto updateUserWithAuthDto, bool updatePass)

#### Parameters

`updateUserWithAuthDto` UpdateUserWithAuthDto

  DTO containing the user to update along with the lists of authorities to delete, update, and add.

`updatePass` bool

  Flag indicating whether the user's password should be updated as part of the operation.

#### Returns

Task<User>

  The updated User.

#### Exceptions

ConflictException

  Thrown when the underlying user update returns no result.

### UpdateUsersByRequest(User, bool)

Updates a user, optionally updating their password, and broadcasts relevant notifications when the password changes, the user is disabled, or the account becomes locked.

    public Task<User?> UpdateUsersByRequest(User user, bool updatePass)

#### Parameters

`user` User

  The user with the updated information to be persisted.

`updatePass` bool

  Indicates whether the user's password should be updated and re-hashed.

#### Returns

Task<User>

  The updated user returned by the repository, or `null` if the user could not be found or updated.

#### Exceptions

UnprocessableEntityException

  Thrown when `updatePass` is `true` and the provided password does not meet the strong password policy.

### ValidateToken(string, string, out SecurityToken)

Validates a JWT token using the configured audience, issuer, and symmetric signing key, and returns the validated security token. The token must be a JWT signed with the HmacSha256 algorithm; otherwise, validation fails and a TokenException is thrown.

    public void ValidateToken(string token, string tokenType, out SecurityToken validatedToken)

#### Parameters

`token` string

  The JWT token string to validate.

`tokenType` string

  The type of the token being validated.

`validatedToken` SecurityToken

  When the method returns, contains the validated SecurityToken if validation succeeds.

#### Exceptions

TokenException

  Thrown when the token is invalid, is not signed with the HmacSha256 algorithm, or any other validation error occurs.