diff --git a/Core.Thalos.DAL.API/Controllers/UserController.cs b/Core.Thalos.DAL.API/Controllers/UserController.cs index fd87282..7f8bb83 100644 --- a/Core.Thalos.DAL.API/Controllers/UserController.cs +++ b/Core.Thalos.DAL.API/Controllers/UserController.cs @@ -4,11 +4,10 @@ // // *********************************************************************** using Asp.Versioning; -using Core.Blueprint.Storage.Adapters; +using Core.Blueprint.Mongo; using Core.Thalos.Adapters; using Core.Thalos.Adapters.Attributes; using Core.Thalos.Adapters.Common.Constants; -using Core.Thalos.Adapters.Common.Enums; using Core.Thalos.Provider.Contracts; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -25,7 +24,7 @@ namespace LSA.Core.Kerberos.API.Controllers [Produces(MimeTypes.ApplicationJson)] [Consumes(MimeTypes.ApplicationJson)] [ApiController] - public class UserController(IUserService service, ILogger logger) : ControllerBase + public class UserController(IUserProvider service) : ControllerBase { /// /// Gets all the users. @@ -38,19 +37,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Read")] - public async Task GetAllUsersService() + public async Task GetAllUsers(CancellationToken cancellationToken) { - try - { - var result = await service.GetAllUsersService(); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in GetAllUsersService"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.GetAllUsers(cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -66,21 +56,16 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Read")] - public async Task GetUserByIdService([FromRoute] string id) + public async Task GetUserById([FromRoute] string _id, CancellationToken cancellationToken) { - try - { - var result = await service.GetUserByIdService(id); + var result = await service.GetUserById(_id, cancellationToken).ConfigureAwait(false); - if (result is null) return NotFound($"user with id: '{id}' not found"); - - return Ok(result); - } - catch (Exception ex) + if (result == null) { - logger.LogError(ex, "Error in GetUserByIdService"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); + return NotFound("Entity not found"); } + + return Ok(result); } /// @@ -95,21 +80,16 @@ namespace LSA.Core.Kerberos.API.Controllers [Route(Routes.Email)] [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.AzureScheme}")] - public async Task GetUserByEmail([FromRoute] string email) + public async Task GetUserByEmail([FromRoute] string email, CancellationToken cancellationToken) { - try - { - var result = await service.GetUserByEmailService(email); + var result = await service.GetUserByEmail(email, cancellationToken).ConfigureAwait(false); - if (result is null) return NotFound($"user with email: '{email}' not found"); - - return Ok(result); - } - catch (Exception ex) + if (result == null) { - logger.LogError(ex, "Error in GetUserByIdEmail"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); + return NotFound("User not found"); } + + return Ok(result); } /// @@ -124,24 +104,16 @@ namespace LSA.Core.Kerberos.API.Controllers [Route("{email}/ValidateExistence")] [ProducesResponseType(typeof(UserExistenceAdapter), StatusCodes.Status200OK)] [AllowAnonymous] - public async Task ValidateUserExistence([FromRoute] string email) + public async Task ValidateUserExistence([FromRoute] string email, CancellationToken cancellationToken) { - try - { - var result = await service.ValidateUserExistenceService(email); + var result = await service.ValidateUserExistence(email, cancellationToken).ConfigureAwait(false); - var existence = new UserExistenceAdapter - { - Existence = (result is not null) ? true : false - }; - - return Ok(existence); - } - catch (Exception ex) + if (result == null) { - logger.LogError(ex, "Error in ValidateUserExistance"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); + return NotFound("User not found"); } + + return Ok(result); } /// @@ -157,24 +129,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status201Created)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task CreateUserAsync([FromBody] UserRequest newUser, [FromRoute] bool sendInvitation) + public async Task CreateUserAsync([FromBody] UserRequest newUser, CancellationToken cancellationToken) { - try - { - var user = await service.GetUserByEmailService(newUser.Email).ConfigureAwait(false); - - if (user is not null) - return UnprocessableEntity("There is a user with the same email registered in the database"); - - var result = await service.CreateUserService(newUser).ConfigureAwait(false); - - return Created("CreatedWithIdService", result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in CreateUserAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.CreateUser(newUser, cancellationToken).ConfigureAwait(false); + return Created("CreatedWithIdAsync", result); } /// @@ -192,19 +150,16 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task UpdateUserAsync([FromBody] UserAdapter entity, [FromRoute] string id) + public async Task UpdateUserAsync([FromRoute] string _id, [FromBody] UserAdapter entity, CancellationToken cancellationToken) { - try + if (_id != entity._Id?.ToString()) { - var result = await service.UpdateUserService(entity, id); + return BadRequest("User ID mismatch"); + } - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in UpdateUserAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.UpdateUser(entity, cancellationToken).ConfigureAwait(false); + + return Ok(result); } /// @@ -219,22 +174,14 @@ namespace LSA.Core.Kerberos.API.Controllers [HttpPatch(Routes.LogIn)] [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.AzureScheme}")] - public async Task LoginUserAsync([FromRoute] string email) + public async Task LoginUserAsync([FromRoute] string email, CancellationToken cancellationToken) { - try - { - var result = await service.LogInUserService(email).ConfigureAwait(false); + var result = await service.LogInUser(email, cancellationToken).ConfigureAwait(false); - if (result is null) - return new NotFoundObjectResult($"The user with email: '{email}' was not found"); + if (result is null) + return new NotFoundObjectResult($"The user with email: '{email}' was not found"); - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in LogInUserService"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + return Ok(result); } /// @@ -248,19 +195,11 @@ namespace LSA.Core.Kerberos.API.Controllers [HttpPatch(Routes.LogOut)] [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.AzureScheme}")] - public async Task LogOutUserSessionAsync([FromRoute] string email) + public async Task LogOutUserSessionAsync([FromRoute] string email, CancellationToken cancellationToken) { - try - { - var result = await service.LogOutUserSessionService(email).ConfigureAwait(false); + var result = await service.LogOutUserSession(email, cancellationToken).ConfigureAwait(false); - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in LogOutUserSessionService"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + return Ok(result); } @@ -279,19 +218,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task ChangeUserStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus) + public async Task ChangeUserStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus, CancellationToken cancellationToken) { - try - { - var result = await service.ChangeUserStatusService(id, newStatus); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in ChangeUserStatus"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.ChangeUserStatus(id, newStatus, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -308,19 +238,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task AddCompanyToUserAsync([FromRoute] string userId, [FromRoute] string companyId) + public async Task AddCompanyToUserAsync([FromRoute] string userId, [FromRoute] string companyId, CancellationToken cancellationToken) { - try - { - var result = await service.AddCompanyToUserService(userId, companyId); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in AddCompanyToUserAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.AddCompanyToUser(userId, companyId, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -337,19 +258,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task RemoveCompanyFromUserAsync([FromRoute] string userId, [FromRoute] string companyId) + public async Task RemoveCompanyFromUserAsync([FromRoute] string userId, [FromRoute] string companyId, CancellationToken cancellationToken) { - try - { - var result = await service.RemoveCompanyFromUserService(userId, companyId); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in RemoveCompanyFromUserAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.RemoveCompanyFromUser(userId, companyId, cancellationToken).ConfigureAwait(false); ; + return Ok(result); } /// @@ -366,19 +278,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task AddProjectToUserAsync([FromRoute] string userId, [FromRoute] string projectId) + public async Task AddProjectToUserAsync([FromRoute] string userId, [FromRoute] string projectId, CancellationToken cancellationToken) { - try - { - var result = await service.AddProjectToUserService(userId, projectId); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in AddProjectToUserAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.AddProjectToUser(userId, projectId, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -395,19 +298,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("UserManagement.Write")] - public async Task RemoveProjectFromUserAsync([FromRoute] string userId, [FromRoute] string projectId) + public async Task RemoveProjectFromUserAsync([FromRoute] string userId, [FromRoute] string projectId, CancellationToken cancellationToken) { - try - { - var result = await service.RemoveProjectFromUserService(userId, projectId); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in RemoveProjectFromUserAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.RemoveCompanyFromUser(userId, projectId, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -422,21 +316,13 @@ namespace LSA.Core.Kerberos.API.Controllers [Route("{email}/GetTokenAdapter")] [ProducesResponseType(typeof(TokenAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.AzureScheme}")] - public async Task GetTokenAdapter([FromRoute] string email) + public async Task GetTokenAdapter([FromRoute] string email, CancellationToken cancellationToken) { - try - { - var tokenAdapter = await service.GetTokenAdapter(email); + var tokenAdapter = await service.GetToken(email, cancellationToken).ConfigureAwait(false); - if (tokenAdapter == null) return NotFound($"User with email: {email} not found"); + if (tokenAdapter == null) return NotFound($"User with email: {email} not found"); - return Ok(tokenAdapter); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in GetTokenAdapter"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + return Ok(tokenAdapter); } } } diff --git a/Core.Thalos.Domain/Core.Thalos.Domain.csproj b/Core.Thalos.Domain/Core.Thalos.Domain.csproj index 941cef1..05d9012 100644 --- a/Core.Thalos.Domain/Core.Thalos.Domain.csproj +++ b/Core.Thalos.Domain/Core.Thalos.Domain.csproj @@ -7,7 +7,7 @@ - + diff --git a/Core.Thalos.Provider/Contracts/IUserService.cs b/Core.Thalos.Provider/Contracts/IUserProvider.cs similarity index 72% rename from Core.Thalos.Provider/Contracts/IUserService.cs rename to Core.Thalos.Provider/Contracts/IUserProvider.cs index 8c1d004..7fe150a 100644 --- a/Core.Thalos.Provider/Contracts/IUserService.cs +++ b/Core.Thalos.Provider/Contracts/IUserProvider.cs @@ -3,14 +3,13 @@ // AgileWebs // // *********************************************************************** -using Core.Blueprint.Storage.Adapters; +using Core.Blueprint.Mongo; using Core.Thalos.Adapters; -using Core.Thalos.Adapters.Common.Enums; using Core.Thalos.Domain.Contexts.Onboarding.Request; namespace Core.Thalos.Provider.Contracts { - public interface IUserService + public interface IUserProvider { /// /// Creates a new User. @@ -18,7 +17,7 @@ namespace Core.Thalos.Provider.Contracts /// The User to be created. /// A representing /// the asynchronous execution of the service. - Task CreateUserService(UserRequest newUser); + ValueTask CreateUser(UserRequest newUser, CancellationToken cancellationToken); /// /// Gets an User by identifier. @@ -26,7 +25,7 @@ namespace Core.Thalos.Provider.Contracts /// The User identifier. /// A representing /// the asynchronous execution of the service. - Task GetUserByIdService(string id); + ValueTask GetUserById(string _id, CancellationToken cancellationToken); /// @@ -34,7 +33,7 @@ namespace Core.Thalos.Provider.Contracts /// /// A representing /// the asynchronous execution of the service. - Task> GetAllUsersService(); + ValueTask> GetAllUsers(CancellationToken cancellationToken); /// /// Gets an User by email. @@ -42,7 +41,7 @@ namespace Core.Thalos.Provider.Contracts /// The User email. /// A representing /// the asynchronous execution of the service. - Task GetUserByEmailService(string? email); + ValueTask GetUserByEmail(string? email, CancellationToken cancellationToken); /// /// Validates if a users exists by email. @@ -50,7 +49,7 @@ namespace Core.Thalos.Provider.Contracts /// The User email. /// A representing /// the asynchronous execution of the service. - Task ValidateUserExistenceService(string? email); + ValueTask ValidateUserExistence(string? email, CancellationToken cancellationToken); /// /// Changes the status of the user. @@ -59,7 +58,7 @@ namespace Core.Thalos.Provider.Contracts /// The new status of the user. /// A representing /// the asynchronous execution of the service. - Task ChangeUserStatusService(string id, StatusEnum newStatus); + ValueTask ChangeUserStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken); /// /// Updates a User by id. @@ -68,7 +67,7 @@ namespace Core.Thalos.Provider.Contracts /// The User identifier. /// A representing /// the asynchronous execution of the service. - Task UpdateUserService(UserAdapter entity, string id); + ValueTask UpdateUser(UserAdapter entity, CancellationToken cancellationToken); /// /// Logs in the user. @@ -76,7 +75,7 @@ namespace Core.Thalos.Provider.Contracts /// The User's email. /// A representing /// the asynchronous execution of the service. - Task LogInUserService(string email); + ValueTask LogInUser(string email, CancellationToken cancellationToken); /// /// Logs out the user's session. @@ -84,7 +83,7 @@ namespace Core.Thalos.Provider.Contracts /// The User's email. /// A representing /// the asynchronous execution of the service. - Task LogOutUserSessionService(string email); + ValueTask LogOutUserSession(string email, CancellationToken cancellationToken); /// /// Adds a company to the user's list of companies. @@ -92,7 +91,7 @@ namespace Core.Thalos.Provider.Contracts /// The identifier of the user to whom the company will be added. /// The identifier of the company to add. /// A representing the asynchronous operation, with the updated user object. - Task AddCompanyToUserService(string userId, string companyId); + ValueTask AddCompanyToUser(string userId, string companyId, CancellationToken cancellationToken); /// /// Removes a company from the user's list of companies. @@ -100,7 +99,7 @@ namespace Core.Thalos.Provider.Contracts /// The identifier of the user from whom the company will be removed. /// The identifier of the company to remove. /// A representing the asynchronous operation, with the updated user object. - Task RemoveCompanyFromUserService(string userId, string companyId); + ValueTask RemoveCompanyFromUser(string userId, string companyId, CancellationToken cancellationToken); /// /// Adds a project to the user's list of projects. @@ -108,7 +107,7 @@ namespace Core.Thalos.Provider.Contracts /// The identifier of the user to whom the project will be added. /// The identifier of the project to add. /// A representing the asynchronous operation, with the updated user object. - Task AddProjectToUserService(string userId, string projectId); + ValueTask AddProjectToUser(string userId, string projectId, CancellationToken cancellationToken); /// @@ -117,13 +116,21 @@ namespace Core.Thalos.Provider.Contracts /// The identifier of the user from whom the project will be removed. /// The identifier of the project to remove. /// A representing the asynchronous operation, with the updated user object. - Task RemoveProjectFromUserService(string userId, string projectId); + ValueTask RemoveProjectFromUser(string userId, string projectId, CancellationToken cancellationToken); /// /// Gets the token adapter for a user. /// /// The user's email. /// A representing the asynchronous execution of the service. - Task GetTokenAdapter(string email); + ValueTask GetToken(string email, CancellationToken cancellationToken); + + /// + /// Delete an User by identifier. + /// + /// The User identifier. + /// A representing + /// the asynchronous execution of the service. + ValueTask DeleteUser(string _id, CancellationToken cancellationToken); } } diff --git a/Core.Thalos.Provider/Core.Thalos.Provider.csproj b/Core.Thalos.Provider/Core.Thalos.Provider.csproj index 1929c0d..2023c09 100644 --- a/Core.Thalos.Provider/Core.Thalos.Provider.csproj +++ b/Core.Thalos.Provider/Core.Thalos.Provider.csproj @@ -11,9 +11,10 @@ - - - + + + + diff --git a/Core.Thalos.Provider/Providers/Onboarding/ModuleService.cs b/Core.Thalos.Provider/Providers/Onboarding/ModuleService.cs index e12d7a6..99561bf 100644 --- a/Core.Thalos.Provider/Providers/Onboarding/ModuleService.cs +++ b/Core.Thalos.Provider/Providers/Onboarding/ModuleService.cs @@ -180,7 +180,7 @@ namespace Core.Thalos.Provider.Providers.Onboarding .Eq("_id", ObjectId.Parse(id)); var update = Builders.Update - .Set(v => v.Status, newStatus) + //.Set(v => v.Status, newStatus) .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) .Set(v => v.UpdatedAt, DateTime.UtcNow); diff --git a/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs b/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs index c5e9c95..e2abf74 100644 --- a/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs +++ b/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs @@ -175,7 +175,7 @@ namespace Core.Thalos.Provider.Providers.Onboarding .Eq("_id", ObjectId.Parse(id)); var update = Builders.Update - .Set(v => v.Status, newStatus) + //.Set(v => v.Status, newStatus) .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) .Set(v => v.UpdatedAt, DateTime.UtcNow); diff --git a/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs b/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs index 601f60f..bd4e0ed 100644 --- a/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs +++ b/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs @@ -134,7 +134,7 @@ namespace Core.Thalos.Provider.Providers.Onboarding .Eq("_id", ObjectId.Parse(id)); var update = Builders.Update - .Set(v => v.Status, newStatus) + //.Set(v => v.Status, newStatus) .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) .Set(v => v.UpdatedAt, DateTime.UtcNow); diff --git a/Core.Thalos.Provider/Providers/Onboarding/UserProvider.cs b/Core.Thalos.Provider/Providers/Onboarding/UserProvider.cs new file mode 100644 index 0000000..bed3c21 --- /dev/null +++ b/Core.Thalos.Provider/Providers/Onboarding/UserProvider.cs @@ -0,0 +1,471 @@ +// *********************************************************************** +// +// AgileWebs +// +// *********************************************************************** + +using Core.Thalos.Adapters; +using Core.Thalos.Adapters.Common.Enums; +using Core.Blueprint.Mongo; +using Core.Blueprint.Redis; +using Core.Blueprint.Redis.Helpers; +using Mapster; +using Microsoft.Extensions.Options; +using MongoDB.Driver; +using Core.Thalos.Provider.Contracts; +using MongoDB.Bson; +using System.Text.RegularExpressions; +using MongoDB.Bson.Serialization; + +namespace Core.Thalos.Provider.Providers.Onboarding +{ + /// + /// Handles all services and business rules related to . + /// + public class UserProvider : IUserProvider + { + private readonly CollectionRepository repository; + private readonly CacheSettings cacheSettings; + private readonly IRedisCacheProvider cacheProvider; + + public UserProvider(CollectionRepository repository, + IRedisCacheProvider cacheProvider, IOptions cacheSettings) + { + this.repository = repository; + this.repository.CollectionInitialization(); + this.cacheSettings = cacheSettings.Value; + this.cacheProvider = cacheProvider; + } + + /// + /// Creates a new User. + /// + /// The User to be created. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask CreateUser(Core.Thalos.Domain.Contexts.Onboarding.Request.UserRequest newUser, CancellationToken cancellationToken) + { + var userCollection = newUser.Adapt(); + + await repository.InsertOneAsync(userCollection); + + return userCollection; + } + + /// + /// Gets an User by identifier. + /// + /// The User identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask GetUserById(string _id, CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserById", _id); + var cachedData = await cacheProvider.GetAsync(cacheKey); + + if (cachedData is not null) { return cachedData; } + + var user = await repository.FindByIdAsync(_id); + + await cacheProvider.SetAsync(cacheKey, user); + + return user; + } + + /// + /// Gets all the users. + /// + /// A representing + /// the asynchronous execution of the service. + public async ValueTask> GetAllUsers(CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllUsers"); + var cachedData = await cacheProvider.GetAsync>(cacheKey) ?? []; + + if (cachedData.Any()) return cachedData; + + var users = await repository.AsQueryable(); + + await cacheProvider.SetAsync(cacheKey, users); + + return users; + } + + /// + /// Gets an User by email. + /// + /// The User email. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask GetUserByEmail(string? email, CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByEmail", email); + var cachedData = await cacheProvider.GetAsync(cacheKey); + + if (cachedData is not null) { return cachedData; } + + var user = await repository.FindOneAsync( + u => u.Email == email && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + await cacheProvider.SetAsync(cacheKey, user); + + return user; + } + + /// + /// Validates if a users exists by email.. + /// + /// The User email. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask ValidateUserExistence(string? email, CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByEmail", email); + var cachedData = await cacheProvider.GetAsync(cacheKey); + + if (cachedData is not null) { return cachedData; } + + var user = await repository.FindOneAsync( + u => u.Email == email && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + await cacheProvider.SetAsync(cacheKey, user); + + return user; + } + + /// + /// Changes the status of the user. + /// + /// The user identifier. + /// The new status of the user. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask ChangeUserStatus(string id, Core.Blueprint.Mongo.StatusEnum newStatus, CancellationToken cancellationToken) + { + var entity = await repository.FindByIdAsync(id); + entity.Status = newStatus; + + await repository.ReplaceOneAsync(entity); + + return entity; + } + + /// + /// Updates a User by id. + /// + /// The User to be updated. + /// The User identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask UpdateUser(UserAdapter entity, CancellationToken cancellationToken) + { + await repository.ReplaceOneAsync(entity); + + return entity; + } + + /// + /// Logs in the user. + /// + /// The User identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask LogInUser(string email, CancellationToken cancellationToken) + { + var user = await repository.FindOneAsync( + u => u.Email == email && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + user.LastLogIn = DateTime.UtcNow; + + await repository.ReplaceOneAsync(user); + + return user; + } + + /// + /// Logs out the user's session. + /// + /// The User email. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask LogOutUserSession(string email, CancellationToken cancellationToken) + { + var user = await repository.FindOneAsync( + u => u.Email == email && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + user.LastLogOut = DateTime.UtcNow; + + await repository.ReplaceOneAsync(user); + + return user; + } + + /// + /// Adds a company to the user's list of companies. + /// + /// The identifier of the user to whom the company will be added. + /// The identifier of the company to add. + /// A representing the asynchronous operation, with the updated user object. + public async ValueTask AddCompanyToUser(string userId, string companyId, CancellationToken cancellationToken) + { + var user = await repository.FindOneAsync( + u => u.Id == userId && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + var updatedCompanies = user.Companies.Append(companyId).Distinct().ToArray(); + user.Companies = updatedCompanies; + + await repository.ReplaceOneAsync(user); + + return user; + } + + /// + /// Removes a company from the user's list of companies. + /// + /// The identifier of the user from whom the company will be removed. + /// The identifier of the company to remove. + /// A representing the asynchronous operation, with the updated user object. + public async ValueTask RemoveCompanyFromUser(string userId, string companyId, CancellationToken cancellationToken) + { + var user = await repository.FindOneAsync( + u => u.Id == userId && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + var updatedCompanies = user.Companies + ?.Where(c => c != companyId) + .ToArray(); + + user.Companies = updatedCompanies; + + await repository.ReplaceOneAsync(user); + + return user; + } + + /// + /// Adds a project to the user's list of projects. + /// + /// The identifier of the user to whom the project will be added. + /// The identifier of the project to add. + /// A representing the asynchronous operation, with the updated user object. + public async ValueTask AddProjectToUser(string userId, string projectId, CancellationToken cancellationToken) + { + var user = await repository.FindOneAsync( + u => u.Id == userId && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + var updatedProjects = user.Projects.Append(projectId).Distinct().ToArray(); + user.Companies = updatedProjects; + + await repository.ReplaceOneAsync(user); + + return user; + } + + /// + /// Removes a project from the user's list of projects. + /// + /// The identifier of the user from whom the project will be removed. + /// The identifier of the project to remove. + /// A representing the asynchronous operation, with the updated user object. + public async ValueTask RemoveProjectFromUser(string userId, string projectId, CancellationToken cancellationToken) + { + var user = await repository.FindOneAsync( + u => u.Id == userId && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + var updatedProjects = user.Projects + ?.Where(c => c != projectId) + .ToArray(); + + user.Companies = updatedProjects; + + await repository.ReplaceOneAsync(user); + + return user; + } + + /// + /// Gets the token adapter for a user. + /// + /// The user's email. + /// A representing the asynchronous execution of the service. + public async ValueTask GetToken(string email, CancellationToken cancellationToken) + { + try + { + var pipeline = new[] + { + new BsonDocument("$match", new BsonDocument + { + { "email", new BsonDocument + { + { "$regex", $"^{Regex.Escape(email)}$" }, + { "$options", "i" } + } + }, + { "status", Core.Blueprint.Mongo.StatusEnum.Active.ToString() } + }), + + new BsonDocument("$lookup", new BsonDocument + { + { "from", "Roles" }, + { "localField", "roleId" }, + { "foreignField", "_id" }, + { "as", "role" } + }), + + new BsonDocument("$unwind", "$role"), + new BsonDocument("$match", new BsonDocument("role.status", Core.Blueprint.Mongo.StatusEnum.Active.ToString())), + + new BsonDocument("$addFields", new BsonDocument + { + { "role.permissions", new BsonDocument("$map", new BsonDocument + { + { "input", "$role.permissions" }, + { "as", "perm" }, + { "in", new BsonDocument("$toObjectId", "$$perm") } + }) + }, + { "role.modules", new BsonDocument("$map", new BsonDocument + { + { "input", "$role.modules" }, + { "as", "mod" }, + { "in", new BsonDocument("$toObjectId", "$$mod") } + }) + } + }), + + new BsonDocument("$lookup", new BsonDocument + { + { "from", "Permissions" }, + { "localField", "role.permissions" }, + { "foreignField", "_id" }, + { "as", "permissions" } + }), + new BsonDocument("$lookup", new BsonDocument + { + { "from", "Modules" }, + { "localField", "role.modules" }, + { "foreignField", "_id" }, + { "as", "modules" } + }), + new BsonDocument("$project", new BsonDocument + { + { "_id", 1 }, + { "guid", 1 }, + { "email", 1 }, + { "name", 1 }, + { "middleName", 1 }, + { "lastName", 1 }, + { "displayName", 1 }, + { "roleId", 1 }, + { "companies", 1 }, + { "projects", 1 }, + { "lastLogIn", 1 }, + { "lastLogOut", 1 }, + { "createdBy", 1 }, + { "updatedBy", 1 }, + { "status", 1 }, + { "createdAt", 1 }, + { "updatedAt", 1 }, + { "role._id", 1 }, + { "role.name", 1 }, + { "role.description", 1 }, + { "role.applications", 1 }, + { "role.permissions", 1 }, + { "role.modules", 1 }, + { "role.status", 1 }, + { "role.createdAt", 1 }, + { "role.updatedAt", 1 }, + { "role.createdBy", 1 }, + { "role.updatedBy", 1 }, + { "permissions", 1 }, + { "modules", 1 } + }) + }; + + var result = await repository.FindOnePipelineAsync(pipeline); + + if (result is null) return null; + + var tokenAdapter = new TokenAdapter + { + User = new UserAdapter + { + Id = result["_id"]?.ToString() ?? "", + Guid = result["guid"].AsString, + Email = result["email"].AsString, + Name = result["name"].AsString, + MiddleName = result["middleName"].AsString, + LastName = result["lastName"].AsString, + DisplayName = result["displayName"].AsString, + RoleId = result["roleId"]?.ToString() ?? "", + Companies = result["companies"].AsBsonArray + .Select(c => c.AsString) + .ToArray(), + Projects = result["projects"].AsBsonArray + .Select(c => c.AsString) + .ToArray(), + LastLogIn = result["lastLogIn"].ToUniversalTime(), + LastLogOut = result["lastLogOut"].ToUniversalTime(), + CreatedAt = result["createdAt"].ToUniversalTime(), + CreatedBy = result["createdBy"].AsString, + UpdatedAt = result["updatedAt"].ToUniversalTime(), + UpdatedBy = result["updatedBy"].AsString, + Status = (Core.Blueprint.Mongo.StatusEnum)Enum.Parse(typeof(Core.Blueprint.Mongo.StatusEnum), result["status"].AsString), + }, + Role = new RoleAdapter + { + Id = result["role"]["_id"]?.ToString() ?? "", + Name = result["role"]["name"].AsString, + Description = result["role"]["description"].AsString, + Applications = result["role"]["applications"].AsBsonArray + .Select(c => (ApplicationsEnum)c.AsInt32) + .ToArray(), + Modules = result["role"]["modules"].AsBsonArray + .Select(c => c.ToString() ?? "") + .ToArray(), + Permissions = result["role"]["permissions"].AsBsonArray + .Select(c => c.ToString() ?? "") + .ToArray(), + Status = (Core.Blueprint.Mongo.StatusEnum)Enum.Parse(typeof(Core.Blueprint.Mongo.StatusEnum), result["role"]["status"].AsString), + CreatedAt = result["role"]["createdAt"].ToUniversalTime(), + UpdatedAt = result["role"]["updatedAt"].ToUniversalTime(), + CreatedBy = result["role"]["createdBy"].AsString, + UpdatedBy = result["role"]["updatedBy"].AsString + }, + Permissions = result["permissions"].AsBsonArray + .Select(permission => BsonSerializer.Deserialize(permission.AsBsonDocument)) + .Where(permission => permission.Status == Core.Blueprint.Mongo.StatusEnum.Active) + .ToList() + }; + + return tokenAdapter; + + } + catch (Exception ex) + { + throw new Exception(ex.Message, ex); + } + } + + /// + /// Deletes an User by id. + /// + /// The User identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask DeleteUser(string _id, CancellationToken cancellationToken) + { + var entity = await repository.DeleteOneAsync(doc => doc.Id == _id); + + return entity; + } + } +} diff --git a/Core.Thalos.Provider/Providers/Onboarding/UserService.cs b/Core.Thalos.Provider/Providers/Onboarding/UserService.cs deleted file mode 100644 index 334c3bd..0000000 --- a/Core.Thalos.Provider/Providers/Onboarding/UserService.cs +++ /dev/null @@ -1,627 +0,0 @@ -// *********************************************************************** -// -// AgileWebs -// -// *********************************************************************** - -using Core.Thalos.Adapters; -using Core.Thalos.Adapters.Common.Constants; -using Core.Thalos.Adapters.Common.Enums; -using Core.Thalos.Domain.Contexts.Onboarding.Mappers; -using Core.Thalos.Domain.Contexts.Onboarding.Request; -using Core.Thalos.Infraestructure.Caching.Configs; -using Core.Thalos.Infraestructure.Caching.Contracts; -using Core.Thalos.Provider.Contracts; -using LSA.Core.Dapper.Service.Caching; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using MongoDB.Bson; -using MongoDB.Bson.Serialization; -using MongoDB.Driver; -using System.Text.RegularExpressions; -using Core.Blueprint.Storage.Contracts; -using Core.Blueprint.Storage.Adapters; - -namespace Core.Thalos.Provider.Providers.Onboarding -{ - /// - /// Handles all services and business rules related to . - /// - public class UserService(ILogger logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService, - IOptions cacheSettings, IMongoDatabase database, IBlobStorageProvider blobStorageProvider) : IUserService - { - private readonly CacheSettings _cacheSettings = cacheSettings.Value; - - /// - /// Creates a new User. - /// - /// The User to be created. - /// A representing - /// the asynchronous execution of the service. - public async Task CreateUserService(UserRequest newUser) - { - try - { - var entity = newUser.ToAdapter(httpContextAccessor); - await database.GetCollection(CollectionNames.User).InsertOneAsync(entity); - entity.Id = (entity as dynamic ?? "").Id.ToString(); - - return entity; - } - catch (Exception ex) - { - logger.LogError(ex, $"CreateUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets an User by identifier. - /// - /// The User identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task GetUserByIdService(string id) - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByIdService", id); - var cachedData = await cacheService.GetAsync(cacheKey); - - if (cachedData is not null) return cachedData; - - try - { - var filter = Builders.Filter.And( - Builders.Filter.Eq("_id", ObjectId.Parse(id)), - Builders.Filter.Eq("status", StatusEnum.Active.ToString()) - ); - - var user = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - - await cacheService.SetAsync(cacheKey, user, cacheDuration); - - return user; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetUserByIdService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets all the users. - /// - /// A representing - /// the asynchronous execution of the service. - public async Task> GetAllUsersService() - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllUsersService"); - var cachedData = await cacheService.GetAsync>(cacheKey) ?? []; - - if (cachedData.Any()) return cachedData; - - try - { - var filter = Builders.Filter.Eq("status", StatusEnum.Active.ToString()); - - var users = await database.GetCollection(CollectionNames.User) - .Find(filter) - .ToListAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - await cacheService.SetAsync(cacheKey, users, cacheDuration); - - return users; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetAllUsersService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets an User by email. - /// - /// The User email. - /// A representing - /// the asynchronous execution of the service. - public async Task GetUserByEmailService(string? email) - { - try - { - var filter = Builders.Filter.And( - Builders.Filter.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")), - Builders.Filter.Eq("status", StatusEnum.Active.ToString()) - ); - - var user = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - - return user; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetUserByEmailService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Validates if a users exists by email.. - /// - /// The User email. - /// A representing - /// the asynchronous execution of the service. - public async Task ValidateUserExistenceService(string? email) - { - try - { - var filter = Builders.Filter.And( - Builders.Filter.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")), - Builders.Filter.Eq("status", StatusEnum.Active.ToString()) - ); - - var user = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - - return user; - } - catch (Exception ex) - { - logger.LogError(ex, $"ValidateUserExistenceService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Deletes an User by id. - /// - /// The User identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task DeleteUserService(string id) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - .Set(v => v.Status, StatusEnum.Inactive); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var deletedUser = await database.GetCollection(CollectionNames.User).Find(filter).FirstAsync(); - - return deletedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"DeleteUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Changes the status of the user. - /// - /// The user identifier. - /// The new status of the user. - /// A representing - /// the asynchronous execution of the service. - public async Task ChangeUserStatusService(string id, StatusEnum newStatus) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - .Set(v => v.Status, newStatus) - .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) - .Set(v => v.UpdatedAt, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var updatedUser = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - - return updatedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"ChangeUserStatusService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Updates a User by id. - /// - /// The User to be updated. - /// The User identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task UpdateUserService(UserAdapter entity, string id) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - .Set(v => v.Email, entity.Email) - .Set(v => v.Name, entity.Name) - .Set(v => v.MiddleName, entity.MiddleName) - .Set(v => v.LastName, entity.LastName) - .Set(v => v.DisplayName, $"{entity.Name} {entity.MiddleName} {entity.LastName}") - .Set(v => v.RoleId, entity.RoleId) - .Set(v => v.Companies, entity.Companies) - .Set(v => v.Projects, entity.Projects) - .Set(v => v.Status, entity.Status) - .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) - .Set(v => v.UpdatedAt, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var updatedUser = await GetUserByIdService(id); - - return updatedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"UpdateUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Logs in the user. - /// - /// The User identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task LogInUserService(string email) - { - try - { - var filter = Builders.Filter - .Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")); - - var update = Builders.Update - .Set(v => v.LastLogIn, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var user = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstAsync(); - - return user; - } - catch (Exception ex) - { - logger.LogError(ex, $"LogInUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Logs out the user's session. - /// - /// The User email. - /// A representing - /// the asynchronous execution of the service. - public async Task LogOutUserSessionService(string email) - { - try - { - var filter = Builders.Filter - .Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")); - - - var update = Builders.Update - .Set(v => v.LastLogOut, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var user = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstAsync(); - - return user; - } - catch (Exception ex) - { - logger.LogError(ex, $"LogOutUserSessionService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Adds a company to the user's list of companies. - /// - /// The identifier of the user to whom the company will be added. - /// The identifier of the company to add. - /// A representing the asynchronous operation, with the updated user object. - public async Task AddCompanyToUserService(string userId, string companyId) - { - try - { - var filter = Builders.Filter.Eq("_id", ObjectId.Parse(userId)); - var update = Builders.Update.AddToSet(v => v.Companies, companyId); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var updatedUser = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - return updatedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"AddCompanyToUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Removes a company from the user's list of companies. - /// - /// The identifier of the user from whom the company will be removed. - /// The identifier of the company to remove. - /// A representing the asynchronous operation, with the updated user object. - public async Task RemoveCompanyFromUserService(string userId, string companyId) - { - try - { - var filter = Builders.Filter.Eq("_id", ObjectId.Parse(userId)); - var update = Builders.Update.Pull(v => v.Companies, companyId); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var updatedUser = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - return updatedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"RemoveCompanyFromUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Adds a project to the user's list of projects. - /// - /// The identifier of the user to whom the project will be added. - /// The identifier of the project to add. - /// A representing the asynchronous operation, with the updated user object. - public async Task AddProjectToUserService(string userId, string projectId) - { - try - { - var filter = Builders.Filter.Eq("_id", ObjectId.Parse(userId)); - var update = Builders.Update.AddToSet(v => v.Projects, projectId); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var updatedUser = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - return updatedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"AddProjectToUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Removes a project from the user's list of projects. - /// - /// The identifier of the user from whom the project will be removed. - /// The identifier of the project to remove. - /// A representing the asynchronous operation, with the updated user object. - public async Task RemoveProjectFromUserService(string userId, string projectId) - { - try - { - var filter = Builders.Filter.Eq("_id", ObjectId.Parse(userId)); - var update = Builders.Update.Pull(v => v.Projects, projectId); - - await database.GetCollection(CollectionNames.User).UpdateOneAsync(filter, update); - - var updatedUser = await database.GetCollection(CollectionNames.User) - .Find(filter) - .FirstOrDefaultAsync(); - return updatedUser; - } - catch (Exception ex) - { - logger.LogError(ex, $"RemoveProjectFromUserService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets the token adapter for a user. - /// - /// The user's email. - /// A representing the asynchronous execution of the service. - public async Task GetTokenAdapter(string email) - { - try - { - var pipeline = new[] - { - new BsonDocument("$match", new BsonDocument - { - { "email", new BsonDocument - { - { "$regex", $"^{Regex.Escape(email)}$" }, - { "$options", "i" } - } - }, - { "status", StatusEnum.Active.ToString() } - }), - - new BsonDocument("$lookup", new BsonDocument - { - { "from", "Roles" }, - { "localField", "roleId" }, - { "foreignField", "_id" }, - { "as", "role" } - }), - - new BsonDocument("$unwind", "$role"), - new BsonDocument("$match", new BsonDocument("role.status", StatusEnum.Active.ToString())), - - new BsonDocument("$addFields", new BsonDocument - { - { "role.permissions", new BsonDocument("$map", new BsonDocument - { - { "input", "$role.permissions" }, - { "as", "perm" }, - { "in", new BsonDocument("$toObjectId", "$$perm") } - }) - }, - { "role.modules", new BsonDocument("$map", new BsonDocument - { - { "input", "$role.modules" }, - { "as", "mod" }, - { "in", new BsonDocument("$toObjectId", "$$mod") } - }) - } - }), - - new BsonDocument("$lookup", new BsonDocument - { - { "from", "Permissions" }, - { "localField", "role.permissions" }, - { "foreignField", "_id" }, - { "as", "permissions" } - }), - new BsonDocument("$lookup", new BsonDocument - { - { "from", "Modules" }, - { "localField", "role.modules" }, - { "foreignField", "_id" }, - { "as", "modules" } - }), - new BsonDocument("$project", new BsonDocument - { - { "_id", 1 }, - { "guid", 1 }, - { "email", 1 }, - { "name", 1 }, - { "middleName", 1 }, - { "lastName", 1 }, - { "displayName", 1 }, - { "roleId", 1 }, - { "companies", 1 }, - { "projects", 1 }, - { "lastLogIn", 1 }, - { "lastLogOut", 1 }, - { "createdBy", 1 }, - { "updatedBy", 1 }, - { "status", 1 }, - { "createdAt", 1 }, - { "updatedAt", 1 }, - { "role._id", 1 }, - { "role.name", 1 }, - { "role.description", 1 }, - { "role.applications", 1 }, - { "role.permissions", 1 }, - { "role.modules", 1 }, - { "role.status", 1 }, - { "role.createdAt", 1 }, - { "role.updatedAt", 1 }, - { "role.createdBy", 1 }, - { "role.updatedBy", 1 }, - { "permissions", 1 }, - { "modules", 1 } - }) - }; - - - var result = await database.GetCollection(CollectionNames.User) - .Aggregate(pipeline) - .FirstOrDefaultAsync(); - - if (result is null) return null; - - var tokenAdapter = new TokenAdapter - { - User = new UserAdapter - { - Id = result["_id"]?.ToString() ?? "", - Guid = result["guid"].AsString, - Email = result["email"].AsString, - Name = result["name"].AsString, - MiddleName = result["middleName"].AsString, - LastName = result["lastName"].AsString, - DisplayName = result["displayName"].AsString, - RoleId = result["roleId"]?.ToString() ?? "", - Companies = result["companies"].AsBsonArray - .Select(c => c.AsString) - .ToArray(), - Projects = result["projects"].AsBsonArray - .Select(c => c.AsString) - .ToArray(), - LastLogIn = result["lastLogIn"].ToUniversalTime(), - LastLogOut = result["lastLogOut"].ToUniversalTime(), - CreatedAt = result["createdAt"].ToUniversalTime(), - CreatedBy = result["createdBy"].AsString, - UpdatedAt = result["updatedAt"].ToUniversalTime(), - UpdatedBy = result["updatedBy"].AsString, - Status = (StatusEnum)Enum.Parse(typeof(StatusEnum), result["status"].AsString), - }, - Role = new RoleAdapter - { - Id = result["role"]["_id"]?.ToString() ?? "", - Name = result["role"]["name"].AsString, - Description = result["role"]["description"].AsString, - Applications = result["role"]["applications"].AsBsonArray - .Select(c => (ApplicationsEnum)c.AsInt32) - .ToArray(), - Modules = result["role"]["modules"].AsBsonArray - .Select(c => c.ToString() ?? "") - .ToArray(), - Permissions = result["role"]["permissions"].AsBsonArray - .Select(c => c.ToString() ?? "") - .ToArray(), - Status = (StatusEnum)Enum.Parse(typeof(StatusEnum), result["role"]["status"].AsString), - CreatedAt = result["role"]["createdAt"].ToUniversalTime(), - UpdatedAt = result["role"]["updatedAt"].ToUniversalTime(), - CreatedBy = result["role"]["createdBy"].AsString, - UpdatedBy = result["role"]["updatedBy"].AsString - }, - Permissions = result["permissions"].AsBsonArray - .Select(permission => BsonSerializer.Deserialize(permission.AsBsonDocument)) - .Where(permission => permission.Status == StatusEnum.Active) - .ToList() - }; - - return tokenAdapter; - - } - catch (Exception ex) - { - logger.LogError(ex, $"GetTokenAdapter: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - } -} diff --git a/Core.Thalos.Provider/ServiceCollectionExtensions.cs b/Core.Thalos.Provider/ServiceCollectionExtensions.cs index e31984c..741b094 100644 --- a/Core.Thalos.Provider/ServiceCollectionExtensions.cs +++ b/Core.Thalos.Provider/ServiceCollectionExtensions.cs @@ -1,5 +1,4 @@ -using Core.Blueprint.Storage.Configuration; -using Core.Thalos.Infraestructure.Caching.Contracts; +using Core.Thalos.Infraestructure.Caching.Contracts; using Core.Thalos.Infraestructure.Contexts.Mongo; using Core.Thalos.Provider.Contracts; using Core.Thalos.Provider.Providers; @@ -55,7 +54,6 @@ namespace Core.Thalos.Provider services.AddDALConfigurationLayer(); services.AddLogs(); services.AddRedisCacheService(configuration); - services.AddBlobStorage(configuration); return services; } @@ -65,7 +63,7 @@ namespace Core.Thalos.Provider { services.AddHttpContextAccessor(); - services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped();