Compare commits
3 Commits
feature/re
...
feature/bl
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3e1cfbf8d | ||
| 41da6d76f8 | |||
|
|
a36fd0e480 |
@@ -5,14 +5,15 @@
|
||||
// ***********************************************************************
|
||||
|
||||
using Asp.Versioning;
|
||||
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.Domain.Contexts.Onboarding.Request;
|
||||
using Core.Thalos.Provider.Contracts;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Graph;
|
||||
using ModuleRequest = Core.Thalos.Domain.Contexts.Onboarding.Request.ModuleRequest;
|
||||
|
||||
namespace LSA.Core.Kerberos.API.Controllers
|
||||
{
|
||||
@@ -24,7 +25,7 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[Produces(MimeTypes.ApplicationJson)]
|
||||
[Consumes(MimeTypes.ApplicationJson)]
|
||||
[ApiController]
|
||||
public class ModuleController(IModuleService service, ILogger<ModuleController> logger) : ControllerBase
|
||||
public class ModuleController(IModuleProvider service) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all the modules.
|
||||
@@ -39,19 +40,10 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(IEnumerable<ModuleAdapter>), StatusCodes.Status200OK)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("ModuleManagement.Read, RoleManagement.Read")]
|
||||
public async Task<IActionResult> GetAllModulesAsync()
|
||||
public async Task<IActionResult> GetAllModulesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.GetAllModulesService();
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error in GetAllModulesAsync");
|
||||
return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
|
||||
}
|
||||
var result = await service.GetAllModules(cancellationToken).ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -69,29 +61,15 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(IEnumerable<ModuleAdapter>), StatusCodes.Status200OK)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("ModuleManagement.Read")]
|
||||
public async Task<IActionResult> GetAllModulesByList([FromBody] string[] modules)
|
||||
public async Task<IActionResult> GetAllModulesByList([FromBody] string[] modules, CancellationToken cancellationToken)
|
||||
{
|
||||
if (modules == null || !modules.Any())
|
||||
{
|
||||
return BadRequest("Module identifiers are required.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var result = await service.GetAllModulesByListService(modules);
|
||||
|
||||
if (result == null || !result.Any())
|
||||
{
|
||||
return NotFound("No modules found for the given identifiers.");
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error in GetAllModulesByList");
|
||||
return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
|
||||
}
|
||||
var result = await service.GetAllModulesByList(modules, cancellationToken).ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
@@ -110,21 +88,16 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(ModuleAdapter), StatusCodes.Status200OK)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("ModuleManagement.Read")]
|
||||
public async Task<IActionResult> GetModuleByIdAsync([FromRoute] string id)
|
||||
public async Task<IActionResult> GetModuleByIdAsync([FromRoute] string _id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.GetModuleByIdService(id);
|
||||
var result = await service.GetModuleById(_id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (result is null) return NotFound($"module with id: '{id}' not found");
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
if (result == null)
|
||||
{
|
||||
logger.LogError(ex, "Error in GetModuleByIdAsync");
|
||||
return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
|
||||
return NotFound("Entity not found");
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -139,18 +112,10 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(ModuleAdapter), StatusCodes.Status201Created)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("ModuleManagement.Write")]
|
||||
public async Task<IActionResult> CreateModuleAsync([FromBody] ModuleRequest newModule)
|
||||
public async Task<IActionResult> CreateModuleAsync([FromBody] ModuleRequest newModule, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.CreateModuleService(newModule).ConfigureAwait(false);
|
||||
return Created("CreatedWithIdService", result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error in CreateModuleAsync");
|
||||
return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
|
||||
}
|
||||
var result = await service.CreateModule(newModule, cancellationToken).ConfigureAwait(false);
|
||||
return Created("CreatedWithIdAsync", result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -170,19 +135,16 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(ModuleAdapter), StatusCodes.Status200OK)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("ModuleManagement.Write")]
|
||||
public async Task<IActionResult> UpdateModuleAsync(ModuleAdapter entity, string id)
|
||||
public async Task<IActionResult> UpdateModuleAsync([FromRoute] string _id, ModuleAdapter entity, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
if (_id != entity._Id?.ToString())
|
||||
{
|
||||
var result = await service.UpdateModuleService(entity, id);
|
||||
return BadRequest("User ID mismatch");
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error in UpdateModuleAsync");
|
||||
return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
|
||||
}
|
||||
var result = await service.UpdateModule(entity, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -202,19 +164,10 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(ModuleAdapter), StatusCodes.Status200OK)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("ModuleManagement.Write")]
|
||||
public async Task<IActionResult> ChangeModuleStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus)
|
||||
public async Task<IActionResult> ChangeModuleStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.ChangeModuleStatusService(id, newStatus);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error in ChangeModuleStatus");
|
||||
return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
|
||||
}
|
||||
var result = await service.ChangeModuleStatus(id, newStatus, cancellationToken).ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,10 @@
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
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<UserController> logger) : ControllerBase
|
||||
public class UserController(IUserProvider service) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all the users.
|
||||
@@ -38,19 +37,10 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[ProducesResponseType(typeof(IEnumerable<UserAdapter>), StatusCodes.Status200OK)]
|
||||
[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
|
||||
[Permission("UserManagement.Read")]
|
||||
public async Task<IActionResult> GetAllUsersService()
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> GetUserByIdService([FromRoute] string id)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> GetUserByEmail([FromRoute] string email)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -124,24 +104,16 @@ namespace LSA.Core.Kerberos.API.Controllers
|
||||
[Route("{email}/ValidateExistence")]
|
||||
[ProducesResponseType(typeof(UserExistenceAdapter), StatusCodes.Status200OK)]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> ValidateUserExistence([FromRoute] string email)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> CreateUserAsync([FromBody] UserRequest newUser, [FromRoute] bool sendInvitation)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> UpdateUserAsync([FromBody] UserAdapter entity, [FromRoute] string id)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> LoginUserAsync([FromRoute] string email)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> LogOutUserSessionAsync([FromRoute] string email)
|
||||
public async Task<IActionResult> 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<IActionResult> ChangeUserStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> AddCompanyToUserAsync([FromRoute] string userId, [FromRoute] string companyId)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> RemoveCompanyFromUserAsync([FromRoute] string userId, [FromRoute] string companyId)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> AddProjectToUserAsync([FromRoute] string userId, [FromRoute] string projectId)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> RemoveProjectFromUserAsync([FromRoute] string userId, [FromRoute] string projectId)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<IActionResult> GetTokenAdapter([FromRoute] string email)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Thalos.Building.Blocks" Version="0.0.1" />
|
||||
<PackageReference Include="Thalos.Building.Blocks" Version="0.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
// AgileWebs
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
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 IModuleService
|
||||
public interface IModuleProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new Module.
|
||||
@@ -17,7 +17,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="entity">The Module to be created.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<ModuleAdapter> CreateModuleService(ModuleRequest newModule);
|
||||
ValueTask<ModuleAdapter> CreateModule(ModuleRequest newModule, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets an Module by identifier.
|
||||
@@ -25,14 +25,14 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="id">The Module identifier.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<ModuleAdapter> GetModuleByIdService(string id);
|
||||
ValueTask<ModuleAdapter> GetModuleById(string _id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the roles.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="{Task{IEnumerbale{ModuleAdapter}}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<IEnumerable<ModuleAdapter>> GetAllModulesService();
|
||||
ValueTask<IEnumerable<ModuleAdapter>> GetAllModules(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the permissions by permissions identifier list.
|
||||
@@ -40,7 +40,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="permissions">The list of permissions identifiers.</param>
|
||||
/// <returns>A <see cref="Task{IEnumerable{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<IEnumerable<ModuleAdapter>> GetAllModulesByListService(string[] permissions);
|
||||
ValueTask<IEnumerable<ModuleAdapter>> GetAllModulesByList(string[] modules, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status of the permission.
|
||||
@@ -50,7 +50,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <returns>The <see cref="ModuleAdapter"/> updated entity.</returns>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<ModuleAdapter> ChangeModuleStatusService(string id, StatusEnum newStatus);
|
||||
ValueTask<ModuleAdapter> ChangeModuleStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Updates a Module by id.
|
||||
@@ -59,6 +59,6 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="id">The Module identifier.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<ModuleAdapter> UpdateModuleService(ModuleAdapter entity, string id);
|
||||
ValueTask<ModuleAdapter> UpdateModule(ModuleAdapter entity, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,13 @@
|
||||
// AgileWebs
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new User.
|
||||
@@ -18,7 +17,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="entity">The User to be created.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> CreateUserService(UserRequest newUser);
|
||||
ValueTask<UserAdapter> CreateUser(UserRequest newUser, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets an User by identifier.
|
||||
@@ -26,7 +25,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> GetUserByIdService(string id);
|
||||
ValueTask<UserAdapter> GetUserById(string _id, CancellationToken cancellationToken);
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -34,7 +33,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="{Task{IEnumerable{UserAdapter}}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<IEnumerable<UserAdapter>> GetAllUsersService();
|
||||
ValueTask<IEnumerable<UserAdapter>> GetAllUsers(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets an User by email.
|
||||
@@ -42,7 +41,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> GetUserByEmailService(string? email);
|
||||
ValueTask<UserAdapter> GetUserByEmail(string? email, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Validates if a users exists by email.
|
||||
@@ -50,7 +49,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="eamil">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> ValidateUserExistenceService(string? email);
|
||||
ValueTask<UserAdapter> ValidateUserExistence(string? email, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status of the user.
|
||||
@@ -59,7 +58,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="newStatus">The new status of the user.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> ChangeUserStatusService(string id, StatusEnum newStatus);
|
||||
ValueTask<UserAdapter> ChangeUserStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Updates a User by id.
|
||||
@@ -68,7 +67,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> UpdateUserService(UserAdapter entity, string id);
|
||||
ValueTask<UserAdapter> UpdateUser(UserAdapter entity, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Logs in the user.
|
||||
@@ -76,7 +75,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="email">The User's email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter?> LogInUserService(string email);
|
||||
ValueTask<UserAdapter?> LogInUser(string email, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Logs out the user's session.
|
||||
@@ -84,7 +83,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="email">The User's email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
Task<UserAdapter> LogOutUserSessionService(string email);
|
||||
ValueTask<UserAdapter?> LogOutUserSession(string email, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a company to the user's list of companies.
|
||||
@@ -92,7 +91,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="userId">The identifier of the user to whom the company will be added.</param>
|
||||
/// <param name="companyId">The identifier of the company to add.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
Task<UserAdapter> AddCompanyToUserService(string userId, string companyId);
|
||||
ValueTask<UserAdapter> AddCompanyToUser(string userId, string companyId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a company from the user's list of companies.
|
||||
@@ -100,7 +99,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="userId">The identifier of the user from whom the company will be removed.</param>
|
||||
/// <param name="companyId">The identifier of the company to remove.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
Task<UserAdapter> RemoveCompanyFromUserService(string userId, string companyId);
|
||||
ValueTask<UserAdapter> RemoveCompanyFromUser(string userId, string companyId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a project to the user's list of projects.
|
||||
@@ -108,7 +107,7 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="userId">The identifier of the user to whom the project will be added.</param>
|
||||
/// <param name="projectId">The identifier of the project to add.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
Task<UserAdapter> AddProjectToUserService(string userId, string projectId);
|
||||
ValueTask<UserAdapter> AddProjectToUser(string userId, string projectId, CancellationToken cancellationToken);
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -117,13 +116,21 @@ namespace Core.Thalos.Provider.Contracts
|
||||
/// <param name="userId">The identifier of the user from whom the project will be removed.</param>
|
||||
/// <param name="projectId">The identifier of the project to remove.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
Task<UserAdapter> RemoveProjectFromUserService(string userId, string projectId);
|
||||
ValueTask<UserAdapter> RemoveProjectFromUser(string userId, string projectId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the token adapter for a user.
|
||||
/// </summary>
|
||||
/// <param name="email">The user's email.</param>
|
||||
/// <returns>A <see cref="{Task{TokenAdapter}}"/> representing the asynchronous execution of the service.</returns>
|
||||
Task<TokenAdapter?> GetTokenAdapter(string email);
|
||||
ValueTask<TokenAdapter?> GetToken(string email, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Delete an User by identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
ValueTask<UserAdapter> DeleteUser(string _id, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,10 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Core.Blueprint.Storage" Version="0.3.0-alpha0049" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="MongoDB.Driver" Version="3.0.0" />
|
||||
<PackageReference Include="Blueprint.Mongo" Version="0.0.3" />
|
||||
<PackageReference Include="Blueprint.Redis" Version="0.0.1" />
|
||||
<PackageReference Include="BuildingBlocks.Library" Version="0.0.1" />
|
||||
<PackageReference Include="Mapster" Version="7.4.2-pre02" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
153
Core.Thalos.Provider/Providers/Onboarding/ModuleProvider.cs
Normal file
153
Core.Thalos.Provider/Providers/Onboarding/ModuleProvider.cs
Normal file
@@ -0,0 +1,153 @@
|
||||
// ***********************************************************************
|
||||
// <copyright file="ModuleService.cs">
|
||||
// AgileWebs
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
using Core.Thalos.Adapters;
|
||||
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 Core.Thalos.Domain.Contexts.Onboarding.Request;
|
||||
|
||||
namespace Core.Thalos.Provider.Providers.Onboarding
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles all services and business rules related to <see cref="ModuleAdapter"/>.
|
||||
/// </summary>
|
||||
public class ModuleProvider : IModuleProvider
|
||||
{
|
||||
private readonly CollectionRepository<ModuleAdapter> repository;
|
||||
private readonly CacheSettings cacheSettings;
|
||||
private readonly IRedisCacheProvider cacheProvider;
|
||||
|
||||
public ModuleProvider(CollectionRepository<ModuleAdapter> repository,
|
||||
IRedisCacheProvider cacheProvider, IOptions<CacheSettings> cacheSettings)
|
||||
{
|
||||
this.repository = repository;
|
||||
this.repository.CollectionInitialization();
|
||||
this.cacheSettings = cacheSettings.Value;
|
||||
this.cacheProvider = cacheProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Module.
|
||||
/// </summary>
|
||||
/// <param name="entity">The Module to be created.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<ModuleAdapter> CreateModule(ModuleRequest newModule, CancellationToken cancellationToken)
|
||||
{
|
||||
var moduleCollection = newModule.Adapt<ModuleAdapter>();
|
||||
|
||||
await repository.InsertOneAsync(moduleCollection);
|
||||
|
||||
return moduleCollection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an Module by identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The Module identifier.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>0
|
||||
public async ValueTask<ModuleAdapter> GetModuleById(string _id, CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetModuleById", _id);
|
||||
var cachedData = await cacheProvider.GetAsync<ModuleAdapter>(cacheKey);
|
||||
|
||||
if (cachedData is not null) { return cachedData; }
|
||||
|
||||
var module = await repository.FindByIdAsync(_id);
|
||||
|
||||
await cacheProvider.SetAsync(cacheKey, module);
|
||||
|
||||
return module;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the modules.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="{Task{IEnumerbale{ModuleAdapter}}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<IEnumerable<ModuleAdapter>> GetAllModules(CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetModules");
|
||||
var cachedData = await cacheProvider.GetAsync<IEnumerable<ModuleAdapter>>(cacheKey) ?? [];
|
||||
|
||||
if (cachedData.Any()) return cachedData;
|
||||
|
||||
var modules = await repository.AsQueryable();
|
||||
|
||||
await cacheProvider.SetAsync(cacheKey, modules);
|
||||
|
||||
return modules;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the modules by modules identifier list.
|
||||
/// </summary>
|
||||
/// <param name="modules">The list of modules identifiers.</param>
|
||||
/// <returns>A <see cref="Task{IEnumerable{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<IEnumerable<ModuleAdapter>> GetAllModulesByList(string[] modules, CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesByList", modules);
|
||||
|
||||
var cachedData = await cacheProvider.GetAsync<IEnumerable<ModuleAdapter>>(cacheKey) ?? [];
|
||||
|
||||
if (cachedData.Any()) return cachedData;
|
||||
|
||||
var builder = Builders<ModuleAdapter>.Filter;
|
||||
var filters = new List<FilterDefinition<ModuleAdapter>>();
|
||||
|
||||
if (modules == null || !modules.Any())
|
||||
{
|
||||
filters.Add(builder.In(x => x.Id, modules));
|
||||
}
|
||||
|
||||
var finalFilter = filters.Any() ? builder.And(filters) : builder.Empty;
|
||||
|
||||
var modulesList = await repository.FilterByMongoFilterAsync(finalFilter);
|
||||
|
||||
await cacheProvider.SetAsync(cacheKey, modulesList);
|
||||
|
||||
return modulesList;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status of the module.
|
||||
/// </summary>
|
||||
/// <param name="id">The module identifier.</param>
|
||||
/// <param name="newStatus">The new status of the module.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<ModuleAdapter> ChangeModuleStatus(string id, Core.Blueprint.Mongo.StatusEnum newStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await repository.FindByIdAsync(id);
|
||||
entity.Status = newStatus;
|
||||
|
||||
await repository.ReplaceOneAsync(entity);
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a Module by id.
|
||||
/// </summary>
|
||||
/// <param name="entity">The Module to be updated.</param>
|
||||
/// <param name="id">The Module identifier.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<ModuleAdapter> UpdateModule(ModuleAdapter entity, CancellationToken cancellationToken)
|
||||
{
|
||||
await repository.ReplaceOneAsync(entity);
|
||||
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
// ***********************************************************************
|
||||
// <copyright file="ModuleService.cs">
|
||||
// AgileWebs
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
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.Driver;
|
||||
|
||||
namespace Core.Thalos.Provider.Providers.Onboarding
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles all services and business rules related to <see cref="ModuleAdapter"/>.
|
||||
/// </summary>
|
||||
public class ModuleService(ILogger<ModuleService> logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService,
|
||||
IOptions<CacheSettings> cacheSettings, IMongoDatabase database) : IModuleService
|
||||
{
|
||||
private readonly CacheSettings _cacheSettings = cacheSettings.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Module.
|
||||
/// </summary>
|
||||
/// <param name="entity">The Module to be created.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<ModuleAdapter> CreateModuleService(ModuleRequest newModule)
|
||||
{
|
||||
try
|
||||
{
|
||||
var entity = newModule.ToAdapter(httpContextAccessor);
|
||||
entity.Order = (entity.Order is not null) ? entity.Order : await GetLastOrderModule(newModule);
|
||||
await database.GetCollection<ModuleAdapter>(CollectionNames.Module).InsertOneAsync(entity);
|
||||
entity.Id = (entity as dynamic ?? "").Id.ToString();
|
||||
|
||||
return entity;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"CreateModuleService: Error in getting data - {ex.Message}");
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an Module by identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The Module identifier.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>0
|
||||
public async Task<ModuleAdapter> GetModuleByIdService(string id)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetModuleByIdService", id);
|
||||
var cachedData = await cacheService.GetAsync<ModuleAdapter>(cacheKey);
|
||||
|
||||
if (cachedData is not null) { return cachedData; }
|
||||
|
||||
try
|
||||
{
|
||||
var filter = Builders<ModuleAdapter>.Filter.And(
|
||||
Builders<ModuleAdapter>.Filter.Eq("_id", ObjectId.Parse(id)),
|
||||
Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString())
|
||||
);
|
||||
|
||||
var module = await database.GetCollection<ModuleAdapter>(CollectionNames.Module)
|
||||
.Find(filter)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
|
||||
|
||||
await cacheService.SetAsync(cacheKey, module, cacheDuration);
|
||||
|
||||
return module;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"GetModuleByIdService: Error in getting data - {ex.Message}");
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the modules.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="{Task{IEnumerbale{ModuleAdapter}}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<IEnumerable<ModuleAdapter>> GetAllModulesService()
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesService");
|
||||
var cachedData = await cacheService.GetAsync<IEnumerable<ModuleAdapter>>(cacheKey) ?? [];
|
||||
|
||||
if (cachedData.Any()) return cachedData;
|
||||
|
||||
try
|
||||
{
|
||||
var filter = Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString());
|
||||
|
||||
var roles = await database.GetCollection<ModuleAdapter>(CollectionNames.Module)
|
||||
.Find(filter)
|
||||
.SortBy(m => m.Application)
|
||||
.ThenBy(m => m.Order)
|
||||
.ToListAsync();
|
||||
|
||||
var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
|
||||
|
||||
await cacheService.SetAsync(cacheKey, roles, cacheDuration);
|
||||
|
||||
return roles;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"GetAllModulesService: Error in getting data - {ex.Message}");
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the modules by modules identifier list.
|
||||
/// </summary>
|
||||
/// <param name="modules">The list of modules identifiers.</param>
|
||||
/// <returns>A <see cref="Task{IEnumerable{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<IEnumerable<ModuleAdapter>> GetAllModulesByListService(string[] modules)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesByListService", modules);
|
||||
|
||||
var cachedData = await cacheService.GetAsync<IEnumerable<ModuleAdapter>>(cacheKey);
|
||||
|
||||
if (cachedData != null && cachedData.Any()) return cachedData;
|
||||
|
||||
try
|
||||
{
|
||||
var objectIds = modules.Select(id => ObjectId.Parse(id)).ToArray();
|
||||
|
||||
var filter = Builders<ModuleAdapter>.Filter.In("_id", objectIds)
|
||||
& Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString());
|
||||
|
||||
var roles = await database.GetCollection<ModuleAdapter>(CollectionNames.Module)
|
||||
.Find(filter)
|
||||
.SortBy(m => m.Application)
|
||||
.ThenBy(m => m.Order)
|
||||
.ToListAsync();
|
||||
|
||||
var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
|
||||
|
||||
await cacheService.SetAsync(cacheKey, roles, cacheDuration);
|
||||
|
||||
return roles;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"GetAllModulesByListService: Error in getting data - {ex.Message}");
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status of the module.
|
||||
/// </summary>
|
||||
/// <param name="id">The module identifier.</param>
|
||||
/// <param name="newStatus">The new status of the module.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<ModuleAdapter> ChangeModuleStatusService(string id, StatusEnum newStatus)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<ModuleAdapter>.Filter
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<ModuleAdapter>.Update
|
||||
.Set(v => v.Status, newStatus)
|
||||
.Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
|
||||
.Set(v => v.UpdatedAt, DateTime.UtcNow);
|
||||
|
||||
await database.GetCollection<ModuleAdapter>(CollectionNames.Module).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedModule = await database.GetCollection<ModuleAdapter>(CollectionNames.Module)
|
||||
.Find(filter)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
return updatedModule;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"ChangeModuleStatusService: Error in getting data - {ex.Message}");
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a Module by id.
|
||||
/// </summary>
|
||||
/// <param name="entity">The Module to be updated.</param>
|
||||
/// <param name="id">The Module identifier.</param>
|
||||
/// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<ModuleAdapter> UpdateModuleService(ModuleAdapter entity, string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<ModuleAdapter>.Filter
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<ModuleAdapter>.Update
|
||||
.Set(v => v.Name, entity.Name)
|
||||
.Set(v => v.Description, entity.Description)
|
||||
.Set(v => v.Icon, entity.Icon)
|
||||
.Set(v => v.Route, entity.Route)
|
||||
.Set(v => v.Order, entity.Order)
|
||||
.Set(v => v.Application, entity.Application)
|
||||
.Set(v => v.Status, entity.Status)
|
||||
.Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
|
||||
.Set(v => v.UpdatedAt, DateTime.UtcNow);
|
||||
|
||||
await database.GetCollection<ModuleAdapter>(CollectionNames.Module).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedModule = await database.GetCollection<ModuleAdapter>(CollectionNames.Module)
|
||||
.Find(filter)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
return updatedModule;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"UpdateModuleService: Error in getting data - {ex.Message}");
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int?> GetLastOrderModule(ModuleRequest newModule)
|
||||
{
|
||||
var filter = Builders<ModuleAdapter>.Filter.And(
|
||||
Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()),
|
||||
Builders<ModuleAdapter>.Filter.Eq("application", newModule.Application.ToString()));
|
||||
|
||||
var maxOrderModule = await database.GetCollection<ModuleAdapter>(CollectionNames.Module)
|
||||
.Find(filter)
|
||||
.SortByDescending(m => m.Order)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
return (maxOrderModule is not null && maxOrderModule.Order is not null) ? maxOrderModule.Order : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,7 +175,7 @@ namespace Core.Thalos.Provider.Providers.Onboarding
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<PermissionAdapter>.Update
|
||||
.Set(v => v.Status, newStatus)
|
||||
//.Set(v => v.Status, newStatus)
|
||||
.Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
|
||||
.Set(v => v.UpdatedAt, DateTime.UtcNow);
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ namespace Core.Thalos.Provider.Providers.Onboarding
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<RoleAdapter>.Update
|
||||
.Set(v => v.Status, newStatus)
|
||||
//.Set(v => v.Status, newStatus)
|
||||
.Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
|
||||
.Set(v => v.UpdatedAt, DateTime.UtcNow);
|
||||
|
||||
|
||||
471
Core.Thalos.Provider/Providers/Onboarding/UserProvider.cs
Normal file
471
Core.Thalos.Provider/Providers/Onboarding/UserProvider.cs
Normal file
@@ -0,0 +1,471 @@
|
||||
// ***********************************************************************
|
||||
// <copyright file="UserService.cs">
|
||||
// AgileWebs
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles all services and business rules related to <see cref="UserAdapter"/>.
|
||||
/// </summary>
|
||||
public class UserProvider : IUserProvider
|
||||
{
|
||||
private readonly CollectionRepository<UserAdapter> repository;
|
||||
private readonly CacheSettings cacheSettings;
|
||||
private readonly IRedisCacheProvider cacheProvider;
|
||||
|
||||
public UserProvider(CollectionRepository<UserAdapter> repository,
|
||||
IRedisCacheProvider cacheProvider, IOptions<CacheSettings> cacheSettings)
|
||||
{
|
||||
this.repository = repository;
|
||||
this.repository.CollectionInitialization();
|
||||
this.cacheSettings = cacheSettings.Value;
|
||||
this.cacheProvider = cacheProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new User.
|
||||
/// </summary>
|
||||
/// <param name="newUser">The User to be created.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> CreateUser(Core.Thalos.Domain.Contexts.Onboarding.Request.UserRequest newUser, CancellationToken cancellationToken)
|
||||
{
|
||||
var userCollection = newUser.Adapt<UserAdapter>();
|
||||
|
||||
await repository.InsertOneAsync(userCollection);
|
||||
|
||||
return userCollection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an User by identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> GetUserById(string _id, CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserById", _id);
|
||||
var cachedData = await cacheProvider.GetAsync<UserAdapter>(cacheKey);
|
||||
|
||||
if (cachedData is not null) { return cachedData; }
|
||||
|
||||
var user = await repository.FindByIdAsync(_id);
|
||||
|
||||
await cacheProvider.SetAsync(cacheKey, user);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the users.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="{Task{IEnumerable{UserAdapter}}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<IEnumerable<UserAdapter>> GetAllUsers(CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllUsers");
|
||||
var cachedData = await cacheProvider.GetAsync<IEnumerable<UserAdapter>>(cacheKey) ?? [];
|
||||
|
||||
if (cachedData.Any()) return cachedData;
|
||||
|
||||
var users = await repository.AsQueryable();
|
||||
|
||||
await cacheProvider.SetAsync(cacheKey, users);
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an User by email.
|
||||
/// </summary>
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> GetUserByEmail(string? email, CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByEmail", email);
|
||||
var cachedData = await cacheProvider.GetAsync<UserAdapter>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates if a users exists by email..
|
||||
/// </summary>
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> ValidateUserExistence(string? email, CancellationToken cancellationToken)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByEmail", email);
|
||||
var cachedData = await cacheProvider.GetAsync<UserAdapter>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status of the user.
|
||||
/// </summary>
|
||||
/// <param name="id">The user identifier.</param>
|
||||
/// <param name="newStatus">The new status of the user.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a User by id.
|
||||
/// </summary>
|
||||
/// <param name="entity">The User to be updated.</param>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> UpdateUser(UserAdapter entity, CancellationToken cancellationToken)
|
||||
{
|
||||
await repository.ReplaceOneAsync(entity);
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs in the user.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter?> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs out the user's session.
|
||||
/// </summary>
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter?> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a company to the user's list of companies.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user to whom the company will be added.</param>
|
||||
/// <param name="companyId">The identifier of the company to add.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async ValueTask<UserAdapter> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a company from the user's list of companies.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user from whom the company will be removed.</param>
|
||||
/// <param name="companyId">The identifier of the company to remove.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async ValueTask<UserAdapter> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a project to the user's list of projects.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user to whom the project will be added.</param>
|
||||
/// <param name="projectId">The identifier of the project to add.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async ValueTask<UserAdapter> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a project from the user's list of projects.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user from whom the project will be removed.</param>
|
||||
/// <param name="projectId">The identifier of the project to remove.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async ValueTask<UserAdapter> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the token adapter for a user.
|
||||
/// </summary>
|
||||
/// <param name="email">The user's email.</param>
|
||||
/// <returns>A <see cref="{Task{TokenAdapter}}"/> representing the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<TokenAdapter?> 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<BsonDocument>(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<PermissionAdapter>(permission.AsBsonDocument))
|
||||
.Where(permission => permission.Status == Core.Blueprint.Mongo.StatusEnum.Active)
|
||||
.ToList()
|
||||
};
|
||||
|
||||
return tokenAdapter;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes an User by id.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async ValueTask<UserAdapter> DeleteUser(string _id, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await repository.DeleteOneAsync(doc => doc.Id == _id);
|
||||
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
// ***********************************************************************
|
||||
// <copyright file="UserService.cs">
|
||||
// AgileWebs
|
||||
// </copyright>
|
||||
// ***********************************************************************
|
||||
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles all services and business rules related to <see cref="UserAdapter"/>.
|
||||
/// </summary>
|
||||
public class UserService(ILogger<UserService> logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService,
|
||||
IOptions<CacheSettings> cacheSettings, IMongoDatabase database, IBlobStorageProvider blobStorageProvider) : IUserService
|
||||
{
|
||||
private readonly CacheSettings _cacheSettings = cacheSettings.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new User.
|
||||
/// </summary>
|
||||
/// <param name="newUser">The User to be created.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> CreateUserService(UserRequest newUser)
|
||||
{
|
||||
try
|
||||
{
|
||||
var entity = newUser.ToAdapter(httpContextAccessor);
|
||||
await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an User by identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> GetUserByIdService(string id)
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByIdService", id);
|
||||
var cachedData = await cacheService.GetAsync<UserAdapter>(cacheKey);
|
||||
|
||||
if (cachedData is not null) return cachedData;
|
||||
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.And(
|
||||
Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(id)),
|
||||
Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString())
|
||||
);
|
||||
|
||||
var user = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the users.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="{Task{IEnumerable{UserAdapter}}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<IEnumerable<UserAdapter>> GetAllUsersService()
|
||||
{
|
||||
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllUsersService");
|
||||
var cachedData = await cacheService.GetAsync<IEnumerable<UserAdapter>>(cacheKey) ?? [];
|
||||
|
||||
if (cachedData.Any()) return cachedData;
|
||||
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString());
|
||||
|
||||
var users = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an User by email.
|
||||
/// </summary>
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> GetUserByEmailService(string? email)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.And(
|
||||
Builders<UserAdapter>.Filter.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")),
|
||||
Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString())
|
||||
);
|
||||
|
||||
var user = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates if a users exists by email..
|
||||
/// </summary>
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> ValidateUserExistenceService(string? email)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.And(
|
||||
Builders<UserAdapter>.Filter.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")),
|
||||
Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString())
|
||||
);
|
||||
|
||||
var user = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes an User by id.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> DeleteUserService(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<UserAdapter>.Update
|
||||
.Set(v => v.Status, StatusEnum.Inactive);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var deletedUser = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status of the user.
|
||||
/// </summary>
|
||||
/// <param name="id">The user identifier.</param>
|
||||
/// <param name="newStatus">The new status of the user.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> ChangeUserStatusService(string id, StatusEnum newStatus)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<UserAdapter>.Update
|
||||
.Set(v => v.Status, newStatus)
|
||||
.Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
|
||||
.Set(v => v.UpdatedAt, DateTime.UtcNow);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedUser = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a User by id.
|
||||
/// </summary>
|
||||
/// <param name="entity">The User to be updated.</param>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> UpdateUserService(UserAdapter entity, string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter
|
||||
.Eq("_id", ObjectId.Parse(id));
|
||||
|
||||
var update = Builders<UserAdapter>.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<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs in the user.
|
||||
/// </summary>
|
||||
/// <param name="id">The User identifier.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter?> LogInUserService(string email)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter
|
||||
.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i"));
|
||||
|
||||
var update = Builders<UserAdapter>.Update
|
||||
.Set(v => v.LastLogIn, DateTime.UtcNow);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var user = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs out the user's session.
|
||||
/// </summary>
|
||||
/// <param name="email">The User email.</param>
|
||||
/// <returns>A <see cref="{Task{UserAdapter}}"/> representing
|
||||
/// the asynchronous execution of the service.</returns>
|
||||
public async Task<UserAdapter> LogOutUserSessionService(string email)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter
|
||||
.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i"));
|
||||
|
||||
|
||||
var update = Builders<UserAdapter>.Update
|
||||
.Set(v => v.LastLogOut, DateTime.UtcNow);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var user = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a company to the user's list of companies.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user to whom the company will be added.</param>
|
||||
/// <param name="companyId">The identifier of the company to add.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async Task<UserAdapter> AddCompanyToUserService(string userId, string companyId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId));
|
||||
var update = Builders<UserAdapter>.Update.AddToSet(v => v.Companies, companyId);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedUser = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a company from the user's list of companies.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user from whom the company will be removed.</param>
|
||||
/// <param name="companyId">The identifier of the company to remove.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async Task<UserAdapter> RemoveCompanyFromUserService(string userId, string companyId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId));
|
||||
var update = Builders<UserAdapter>.Update.Pull(v => v.Companies, companyId);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedUser = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a project to the user's list of projects.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user to whom the project will be added.</param>
|
||||
/// <param name="projectId">The identifier of the project to add.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async Task<UserAdapter> AddProjectToUserService(string userId, string projectId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId));
|
||||
var update = Builders<UserAdapter>.Update.AddToSet(v => v.Projects, projectId);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedUser = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a project from the user's list of projects.
|
||||
/// </summary>
|
||||
/// <param name="userId">The identifier of the user from whom the project will be removed.</param>
|
||||
/// <param name="projectId">The identifier of the project to remove.</param>
|
||||
/// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns>
|
||||
public async Task<UserAdapter> RemoveProjectFromUserService(string userId, string projectId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId));
|
||||
var update = Builders<UserAdapter>.Update.Pull(v => v.Projects, projectId);
|
||||
|
||||
await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update);
|
||||
|
||||
var updatedUser = await database.GetCollection<UserAdapter>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the token adapter for a user.
|
||||
/// </summary>
|
||||
/// <param name="email">The user's email.</param>
|
||||
/// <returns>A <see cref="{Task{TokenAdapter}}"/> representing the asynchronous execution of the service.</returns>
|
||||
public async Task<TokenAdapter?> 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<BsonDocument>(CollectionNames.User)
|
||||
.Aggregate<BsonDocument>(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<PermissionAdapter>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,11 +63,11 @@ namespace Core.Thalos.Provider
|
||||
{
|
||||
services.AddHttpContextAccessor();
|
||||
|
||||
services.AddScoped<IUserService, UserService>();
|
||||
services.AddScoped<IUserProvider, UserProvider>();
|
||||
services.AddScoped<IRoleService, RoleService>();
|
||||
services.AddScoped<IPermissionService, PermissionService>();
|
||||
services.AddScoped<IPermissionService, PermissionService>();
|
||||
services.AddScoped<IModuleService, ModuleService>();
|
||||
services.AddScoped<IModuleProvider, ModuleProvider>();
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user