Compare commits
	
		
			1 Commits
		
	
	
		
			6a055bc3db
			...
			feature/go
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | e7a3ee2389 | 
| @@ -1,10 +1,18 @@ | ||||
| using Asp.Versioning; | ||||
| using Core.Thalos.Adapters; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
| using Core.Thalos.Adapters.Contracts; | ||||
| using Core.Thalos.Application.UseCases.Users.Input; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.BFF.Api.Services; | ||||
| using Core.Thalos.External.Clients.Thalos.Requests.Users; | ||||
| using Google.Apis.Auth.OAuth2; | ||||
| using LSA.Dashboard.External.Clients.Dashboard; | ||||
| using Microsoft.AspNetCore.Authorization; | ||||
| using Microsoft.AspNetCore.Mvc; | ||||
| using Microsoft.Graph; | ||||
| using Newtonsoft.Json.Linq; | ||||
| using System.Reflection; | ||||
| using System.Text.Json; | ||||
|  | ||||
| namespace Core.Thalos.BFF.Api.Controllers | ||||
| { | ||||
| @@ -17,10 +25,10 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|     [Consumes(MimeTypes.ApplicationJson)] | ||||
|     [ApiController] | ||||
|     public class AuthenticationController( | ||||
|     IThalosServiceClient thalosServiceClient, | ||||
|     ILogger<AuthenticationController> logger, | ||||
|     ITokenService tokenService, | ||||
|     IGoogleAuthorization googleAuthorization) : BaseController(logger) | ||||
|         IThalosServiceClient thalosServiceClient,  | ||||
|         ILogger<AuthenticationController> logger,  | ||||
|         ITokenService tokenService, | ||||
|         IGoogleAuthorization googleAuthorization) : BaseController(logger) | ||||
|     { | ||||
|         [HttpGet] | ||||
|         public IActionResult Authorize() => Ok(googleAuthorization.GetAuthorizationUrl()); | ||||
| @@ -30,8 +38,9 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         { | ||||
|             var userCredential = await googleAuthorization.ExchangeCodeForToken(code); | ||||
|  | ||||
|             return Ok(new { Token = userCredential!.Token.IdToken }); | ||||
|             return Ok(new Token(userCredential!.Token.IdToken)); | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Get token for user. | ||||
|         /// </summary> | ||||
| @@ -42,7 +51,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [HttpGet] | ||||
|         [Route(Routes.GenerateToken)] | ||||
|         [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.GoogleScheme)] | ||||
|         [Authorize] | ||||
|         public async Task<IActionResult> GenerateTokenService(CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|   | ||||
| @@ -1,5 +1,8 @@ | ||||
| using Asp.Versioning; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters; | ||||
| using Core.Thalos.Adapters.Attributes; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
| using Core.Thalos.BFF.Api.Services; | ||||
| using Core.Thalos.External.Clients.Thalos.Requests.Permissions; | ||||
| using Lib.Architecture.BuildingBlocks; | ||||
| using LSA.Dashboard.External.Clients.Dashboard; | ||||
| @@ -17,7 +20,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|     [Consumes("application/json")] | ||||
|     [Produces("application/json")] | ||||
|     [ApiController] | ||||
|     [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|     //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|     public class ModuleController(IThalosServiceClient thalosServiceClient, ILogger<ModuleController> logger) : BaseController(logger) | ||||
|     { | ||||
|         /// <summary> | ||||
| @@ -30,7 +33,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("ModuleManagement.Read, RoleManagement.Read")] | ||||
|         [Authorize(AuthenticationSchemes = Constant.Scheme)] | ||||
|         //[Permission("ModuleManagement.Read, RoleManagement.Read")] | ||||
|         public async Task<IActionResult> GetAllModulesService(CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -63,7 +67,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||||
|         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("ModuleManagement.Read")] | ||||
|         [AllowAnonymous] | ||||
|         //[Permission("ModuleManagement.Read")] | ||||
|         public async Task<IActionResult> GetAllModulesByListAsync([FromBody] GetAllModulesByListRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -96,7 +101,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("ModuleManagement.Write")] | ||||
|         [AllowAnonymous] | ||||
|         //[Permission("ModuleManagement.Write")] | ||||
|         public async Task<IActionResult> CreateModuleService(CreateModuleRequest newModule, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -130,7 +136,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("ModuleManagement.Read")] | ||||
|         //[Permission("ModuleManagement.Read")] | ||||
|         public async Task<IActionResult> GetModuleByIdService(GetModuleRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -158,7 +164,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("ModuleManagement.Write")] | ||||
|         //[Permission("ModuleManagement.Write")] | ||||
|         public async Task<IActionResult> UpdateModuleService(UpdateModuleRequest newModule, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -194,7 +200,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("ModuleManagement.Write")] | ||||
|         //[Permission("ModuleManagement.Write")] | ||||
|         public async Task<IActionResult> ChangeModuleStatusService([FromBody] ChangeModuleStatusRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|   | ||||
| @@ -1,5 +1,7 @@ | ||||
| using Asp.Versioning; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters; | ||||
| using Core.Thalos.Adapters.Attributes; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
| using Core.Thalos.External.Clients.Thalos.Requests.Permissions; | ||||
| using Lib.Architecture.BuildingBlocks; | ||||
| using LSA.Dashboard.External.Clients.Dashboard; | ||||
| @@ -18,7 +20,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|     [Consumes("application/json")] | ||||
|     [Produces("application/json")] | ||||
|     [ApiController] | ||||
|     [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|     //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|     public class PermissionController(IThalosServiceClient thalosServiceClient, ILogger<PermissionController> logger) : BaseController(logger) | ||||
|     { | ||||
|         /// <summary> | ||||
| @@ -31,7 +33,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("PermissionManagement.Read, RoleManagement.Read")] | ||||
|         ////[Permission("PermissionManagement.Read, RoleManagement.Read")] | ||||
|         public async Task<IActionResult> GetAllPermissionsService(CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -64,7 +66,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||||
|         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("PermissionManagement.Read")] | ||||
|         //[Permission("PermissionManagement.Read")] | ||||
|         public async Task<IActionResult> GetAllPermissionsByListAsync([FromBody] GetAllPermissionsByListRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -97,7 +99,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("PermissionManagement.Write")] | ||||
|         //[Permission("PermissionManagement.Write")] | ||||
|         public async Task<IActionResult> CreatePermissionService(CreatePermissionRequest newPermission, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -129,7 +131,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("PermissionManagement.Read")] | ||||
|         //[Permission("PermissionManagement.Read")] | ||||
|         public async Task<IActionResult> GetPermissionByIdService(GetPermissionRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -157,7 +159,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("PermissionManagement.Write")] | ||||
|         //[Permission("PermissionManagement.Write")] | ||||
|         public async Task<IActionResult> UpdatePermissionService(UpdatePermissionRequest newPermission, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -191,7 +193,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Permission("PermissionManagement.Write")] | ||||
|         //[Permission("PermissionManagement.Write")] | ||||
|         public async Task<IActionResult> ChangePermissionStatusService([FromBody] ChangePermissionStatusRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|   | ||||
| @@ -1,6 +1,7 @@ | ||||
| using Asp.Versioning; | ||||
| using Core.Thalos.Adapters.Attributes; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
| using Core.Thalos.Application.UseCases.Roles.Input; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Lib.Architecture.BuildingBlocks; | ||||
| using LSA.Dashboard.External.Clients.Dashboard; | ||||
| using Microsoft.AspNetCore.Authorization; | ||||
| @@ -17,7 +18,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|     [Consumes("application/json")] | ||||
|     [Produces("application/json")] | ||||
|     [ApiController] | ||||
|     [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|     //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|     public class RoleController(IThalosServiceClient thalosServiceClient, ILogger<RoleController> logger) : BaseController(logger) | ||||
|     { | ||||
|         /// <summary> | ||||
|   | ||||
| @@ -1,6 +1,7 @@ | ||||
| using Asp.Versioning; | ||||
| using Core.Thalos.Adapters.Attributes; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
| using Core.Thalos.Application.UseCases.Users.Input; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.External.Clients.Thalos.Requests.Users; | ||||
| using Lib.Architecture.BuildingBlocks; | ||||
| using LSA.Dashboard.External.Clients.Dashboard; | ||||
| @@ -30,8 +31,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         [Permission("UserManagement.Read")] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Read")] | ||||
|         public async Task<IActionResult> GetAllUsersService(CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -57,8 +58,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         [Permission("UserManagement.Write")] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|         public async Task<IActionResult> CreateUserService(CreateUserRequest newUser, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -75,6 +76,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|  | ||||
|                 if (string.IsNullOrEmpty(newUser.RoleId)) return BadRequest("Invalid role id"); | ||||
|  | ||||
|                 if (!newUser.Companies.Any()) return BadRequest("The user must contain at least one company"); | ||||
|  | ||||
|                 return await Handle(() => thalosServiceClient.CreateUserService(newUser, cancellationToken)).ConfigureAwait(false); | ||||
|             } | ||||
|             catch (Exception ex) | ||||
| @@ -94,8 +97,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         [Permission("UserManagement.Read")] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Read")] | ||||
|         public async Task<IActionResult> GetUserByIdService(GetUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -123,8 +126,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         [Permission("UserManagement.Read")] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Read")] | ||||
|         public async Task<IActionResult> GetUserByEmailService(GetUserByEmailRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -152,8 +155,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         [Permission("UserManagement.Write")] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|         public async Task<IActionResult> UpdateUserService(UpdateUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -191,7 +194,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = $"{Schemes.GoogleScheme}, {Schemes.DefaultScheme}")] | ||||
|         //[Authorize(AuthenticationSchemes = $"{Schemes.AzureScheme}, {Schemes.DefaultScheme}")] | ||||
|         public async Task<IActionResult> LoginUserService([FromBody] LoginUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -219,7 +222,7 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = $"{Schemes.GoogleScheme}, {Schemes.DefaultScheme}")] | ||||
|         //[Authorize(AuthenticationSchemes = $"{Schemes.AzureScheme}, {Schemes.DefaultScheme}")] | ||||
|         public async Task<IActionResult> LogoutUserService([FromBody] LogoutUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -249,8 +252,8 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         [Permission("UserManagement.Write")] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|         public async Task<IActionResult> ChangeUserStatusService([FromBody] ChangeUserStatusRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
| @@ -268,6 +271,135 @@ namespace Core.Thalos.BFF.Api.Controllers | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Adds a company to the user's list of companies. | ||||
|         /// </summary> | ||||
|         [HttpPost] | ||||
|         [Route("AddCompany")] | ||||
|         [ProducesResponseType(StatusCodes.Status200OK)] | ||||
|         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||||
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||||
|         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|         public async Task<IActionResult> AddCompanyToUserService([FromBody] AddCompanyToUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 logger.LogInformation($"{nameof(AddCompanyToUserService)} - Request received - Payload: {JsonSerializer.Serialize(request)}"); | ||||
|  | ||||
|                 if (string.IsNullOrEmpty(request.UserId)) { return BadRequest("Invalid user identifier"); } | ||||
|                 if (string.IsNullOrEmpty(request.CompanyId)) { return BadRequest("Invalid company identifier"); } | ||||
|  | ||||
|                 return await Handle(() => thalosServiceClient.AddCompanyToUserService(request, cancellationToken)).ConfigureAwait(false); | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError($"{nameof(AddCompanyToUserService)} - An Error Occurred- {ex.Message} - {ex.InnerException} - {ex.StackTrace} - with payload {JsonSerializer.Serialize(request)}"); | ||||
|                 throw; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Removes a company from the user's list of companies. | ||||
|         /// </summary> | ||||
|         [HttpDelete] | ||||
|         [Route("RemoveCompany")] | ||||
|         [ProducesResponseType(StatusCodes.Status200OK)] | ||||
|         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||||
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||||
|         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|         public async Task<IActionResult> RemoveCompanyFromUserService([FromBody] RemoveCompanyFromUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 logger.LogInformation($"{nameof(RemoveCompanyFromUserService)} - Request received - Payload: {JsonSerializer.Serialize(request)}"); | ||||
|  | ||||
|                 if (string.IsNullOrEmpty(request.UserId)) { return BadRequest("Invalid user identifier"); } | ||||
|                 if (string.IsNullOrEmpty(request.CompanyId)) { return BadRequest("Invalid company identifier"); } | ||||
|  | ||||
|                 return await Handle(() => thalosServiceClient.RemoveCompanyFromUserService(request, cancellationToken)).ConfigureAwait(false); | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError($"{nameof(RemoveCompanyFromUserService)} - An Error Occurred- {ex.Message} - {ex.InnerException} - {ex.StackTrace} - with payload {JsonSerializer.Serialize(request)}"); | ||||
|                 throw; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Adds a project to the user's list of companies. | ||||
|         /// </summary> | ||||
|         [HttpPost] | ||||
|         [Route("AddProject")] | ||||
|         [ProducesResponseType(StatusCodes.Status200OK)] | ||||
|         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||||
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||||
|         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|  | ||||
|         public async Task<IActionResult> AddProjectToUserService([FromBody] AddProjectToUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 logger.LogInformation($"{nameof(AddProjectToUserService)} - Request received - Payload: {JsonSerializer.Serialize(request)}"); | ||||
|  | ||||
|                 if (string.IsNullOrEmpty(request.UserId)) { return BadRequest("Invalid user identifier"); } | ||||
|                 if (string.IsNullOrEmpty(request.ProjectId)) { return BadRequest("Invalid project identifier"); } | ||||
|  | ||||
|                 return await Handle(() => thalosServiceClient.AddProjectToUserService(request, cancellationToken)).ConfigureAwait(false); | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError($"{nameof(AddProjectToUserService)} - An Error Occurred- {ex.Message} - {ex.InnerException} - {ex.StackTrace} - with payload {JsonSerializer.Serialize(request)}"); | ||||
|                 throw; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Removes a project from the user's list of companies. | ||||
|         /// </summary> | ||||
|         [HttpDelete] | ||||
|         [Route("RemoveProject")] | ||||
|         [ProducesResponseType(StatusCodes.Status200OK)] | ||||
|         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||||
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||||
|         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status412PreconditionFailed)] | ||||
|         [ProducesResponseType(typeof(Notification), StatusCodes.Status422UnprocessableEntity)] | ||||
|         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||||
|         //[Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] | ||||
|         //[Permission("UserManagement.Write")] | ||||
|         public async Task<IActionResult> RemoveProjectFromUserService([FromBody] RemoveProjectFromUserRequest request, CancellationToken cancellationToken) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 logger.LogInformation($"{nameof(RemoveProjectFromUserService)} - Request received - Payload: {JsonSerializer.Serialize(request)}"); | ||||
|  | ||||
|                 if (string.IsNullOrEmpty(request.UserId)) { return BadRequest("Invalid user identifier"); } | ||||
|                 if (string.IsNullOrEmpty(request.ProjectId)) { return BadRequest("Invalid project identifier"); } | ||||
|  | ||||
|                 return await Handle(() => thalosServiceClient.RemoveProjectFromUserService(request, cancellationToken)).ConfigureAwait(false); | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError($"{nameof(RemoveProjectFromUserService)} - An Error Occurred- {ex.Message} - {ex.InnerException} - {ex.StackTrace} - with payload {JsonSerializer.Serialize(request)}"); | ||||
|                 throw; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets the user by email. | ||||
|         /// </summary> | ||||
|   | ||||
| @@ -9,7 +9,13 @@ | ||||
|  | ||||
|   <ItemGroup> | ||||
|     <PackageReference Include="Asp.Versioning.Mvc" Version="8.1.0" /> | ||||
|     <PackageReference Include="Core.Blueprint.Logging" Version="1.0.1" /> | ||||
|     <PackageReference Include="Core.Blueprint.Logging" Version="1.0.0" /> | ||||
|     <PackageReference Include="Google.Apis.Auth" Version="1.70.0" /> | ||||
|     <PackageReference Include="Google.Apis.Oauth2.v2" Version="1.68.0.1869" /> | ||||
|     <PackageReference Include="Google.Protobuf" Version="3.31.1" /> | ||||
|     <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.17" /> | ||||
|     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.17" /> | ||||
|     <PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.4" /> | ||||
|   </ItemGroup> | ||||
|  | ||||
|   <ItemGroup> | ||||
|   | ||||
| @@ -1,14 +1,28 @@ | ||||
| using Core.Blueprint.KeyVault.Configuration; | ||||
| using Asp.Versioning; | ||||
| using Azure.Identity; | ||||
| using Core.Blueprint.Logging.Configuration; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.BuildingBlocks.Configuration; | ||||
| using Core.Thalos.BuildingBlocks.Extensions; | ||||
| using Core.Thalos.Adapters.Contracts; | ||||
| using Core.Thalos.Adapters.Extensions; | ||||
| using Core.Thalos.Adapters.Services; | ||||
| using Core.Thalos.BFF.Api.Services; | ||||
| using Core.Thalos.External.ClientConfiguration; | ||||
| using Google.Protobuf.WellKnownTypes; | ||||
| using Microsoft.AspNetCore.Authentication; | ||||
| using Microsoft.AspNetCore.Authentication.Cookies; | ||||
| using Microsoft.AspNetCore.Authentication.JwtBearer; | ||||
| using Microsoft.AspNetCore.Authentication.OpenIdConnect; | ||||
| using Microsoft.AspNetCore.ResponseCompression; | ||||
| using Microsoft.Extensions.Configuration.AzureAppConfiguration; | ||||
| using Microsoft.IdentityModel.Tokens; | ||||
| using Microsoft.OpenApi.Any; | ||||
| using Microsoft.OpenApi.Interfaces; | ||||
| using Microsoft.OpenApi.Models; | ||||
| using OpenTelemetry.Logs; | ||||
| using OpenTelemetry.Resources; | ||||
| using Swashbuckle.AspNetCore.SwaggerUI; | ||||
| using System.IO.Compression; | ||||
| using System.Reflection; | ||||
| using System.Security.Claims; | ||||
|  | ||||
| var builder = WebApplication.CreateBuilder(args); | ||||
|  | ||||
| @@ -16,128 +30,171 @@ builder.Configuration | ||||
|     .AddUserSecrets(Assembly.GetExecutingAssembly()) | ||||
|     .AddEnvironmentVariables(); | ||||
|  | ||||
| var services = builder.Services.AddKeyVault(builder.Configuration); | ||||
| // 🔑 Google Auth config | ||||
| var googleClientId = builder.Configuration["Authentication:Google:ClientId"]; | ||||
| var googleClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; | ||||
| var redirectUri = builder.Configuration["Authentication:Google:RedirectUri"]; | ||||
|  | ||||
| var authSettings = await AuthHelper.GetAuthSettings(builder.Services, builder, "thalos_common"); | ||||
|  | ||||
| builder.Services.ConfigureAuthentication(builder.Configuration, authSettings); | ||||
| // 🧩 Authentication | ||||
| builder.Services.AddAuthentication(options => | ||||
| { | ||||
|     options.DefaultAuthenticateScheme = Constant.Scheme; | ||||
|     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; | ||||
| }) | ||||
| .AddScheme<AuthenticationSchemeOptions, | ||||
| GoogleAccessTokenAuthenticationHandler>(Constant.Scheme, null) | ||||
| .AddGoogle(options => | ||||
| { | ||||
|     options.ClientId = googleClientId!; | ||||
|     options.ClientSecret = googleClientSecret!; | ||||
|     //options.SaveTokens = true; | ||||
|     options.CallbackPath = $"/{redirectUri}"; | ||||
| }); | ||||
|  | ||||
| builder.Services.AddAuthorization(); | ||||
| builder.Services.AddScoped<IGoogleAuthHelper, GoogleAuthHelperService>(); | ||||
| builder.Services.AddScoped<IGoogleAuthorization, GoogleAuthorizationService>(); | ||||
| builder.Services.AddEndpointsApiExplorer(); | ||||
|  | ||||
| // 🧩 Swagger + OAuth2 | ||||
| builder.Services.AddSwaggerGen(opts => | ||||
| { | ||||
|     const string schemeName = "oauth2"; | ||||
|  | ||||
|     opts.SwaggerDoc("v1", | ||||
|         new OpenApiInfo { Title = "Core.Thalos.BFF", Version = "v1" }); | ||||
|  | ||||
|     opts.AddSecurityDefinition(schemeName, new OpenApiSecurityScheme | ||||
|     { | ||||
|         Type = SecuritySchemeType.OAuth2, | ||||
|         Scheme = "bearer",              // tells Swagger-UI to build an Authorization header | ||||
|         BearerFormat = "JWT", | ||||
|         Name = "Authorization", | ||||
|         In = ParameterLocation.Header, | ||||
|  | ||||
|         /* ⚠️  The key line – tell Swagger-UI to pick id_token instead of access_token */ | ||||
|         Extensions = new Dictionary<string, IOpenApiExtension> | ||||
|         { | ||||
|             ["x-tokenName"] = new OpenApiString("id_token") | ||||
|         }, | ||||
|  | ||||
|         Flows = new OpenApiOAuthFlows | ||||
|         { | ||||
|             AuthorizationCode = new OpenApiOAuthFlow | ||||
|             { | ||||
|                 AuthorizationUrl = new Uri("https://accounts.google.com/o/oauth2/v2/auth"), | ||||
|                 TokenUrl = new Uri("https://oauth2.googleapis.com/token"), | ||||
|                 Scopes = new Dictionary<string, string> | ||||
|                 { | ||||
|                     { "openid",  "OpenID Connect" }, | ||||
|                     { "email",   "Access email"   }, | ||||
|                     { "profile", "Access profile" } | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|     }); | ||||
|  | ||||
|     // every operation requires the scheme | ||||
|     opts.AddSecurityRequirement(new OpenApiSecurityRequirement | ||||
|     { | ||||
|         [new OpenApiSecurityScheme | ||||
|         { | ||||
|             Reference = new OpenApiReference | ||||
|             { Type = ReferenceType.SecurityScheme, Id = schemeName } | ||||
|         } | ||||
|         ] = new[] { "openid", "email", "profile" } | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| // 🎯 Existing configs (unchanged) | ||||
| builder.Services.AddResponseCompression(); | ||||
| builder.Services.AddProblemDetails(); | ||||
| builder.Services.AddLogs(builder); | ||||
| builder.Services.AddMemoryCache(); | ||||
| builder.Services.AddResponseCaching(configureOptions => { configureOptions.UseCaseSensitivePaths = true; }); | ||||
| builder.Logging.AddOpenTelemetry(options => | ||||
| builder.Services.AddResponseCaching(options => { options.UseCaseSensitivePaths = true; }); | ||||
|  | ||||
| builder.Logging.AddOpenTelemetry(logging => | ||||
| { | ||||
|     options.IncludeScopes = true; | ||||
|     options.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("core.thalos.bff.api")).AddConsoleExporter(); | ||||
|     logging.IncludeScopes = true; | ||||
|     logging.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("core.thalos.bff.api")) | ||||
|            .AddConsoleExporter(); | ||||
| }); | ||||
|  | ||||
| builder.Host.ConfigureServices((context, services) => | ||||
| { | ||||
|     builder.Services.AddHsts(options => | ||||
|     services.AddHsts(options => | ||||
|     { | ||||
|         options.Preload = true; | ||||
|         options.IncludeSubDomains = true; | ||||
|         options.MaxAge = TimeSpan.FromDays(60); | ||||
|     }); | ||||
|     builder.Services.AddResponseCaching(configureOptions => | ||||
|     { | ||||
|         configureOptions.UseCaseSensitivePaths = true; | ||||
|         configureOptions.MaximumBodySize = 2048; | ||||
|     }); | ||||
|     builder.Services.AddHttpsRedirection(options => | ||||
|     { | ||||
|         options.RedirectStatusCode = 308; | ||||
|     }); | ||||
|  | ||||
|     services.AddHttpLogging(http => | ||||
|     { | ||||
|         http.CombineLogs = true; | ||||
|     }); | ||||
|     services.AddHttpsRedirection(options => { options.RedirectStatusCode = 308; }); | ||||
|     services.AddAntiforgery(); | ||||
|     services.AddHttpLogging(http => http.CombineLogs = true); | ||||
|     services.AddCors(options => options.AddPolicy("AllowAll", policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); | ||||
|  | ||||
|     services.AddCors(options => | ||||
|     services.AddMvc().AddJsonOptions(opt => | ||||
|     { | ||||
|         options.AddPolicy("AllowAll", policyBuilder => | ||||
|             policyBuilder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); | ||||
|         opt.JsonSerializerOptions.WriteIndented = true; | ||||
|         opt.JsonSerializerOptions.MaxDepth = 20; | ||||
|         opt.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals; | ||||
|     }); | ||||
|     services.AddMvc().AddJsonOptions(options => | ||||
|  | ||||
|     services.Configure<BrotliCompressionProviderOptions>(opt => opt.Level = CompressionLevel.SmallestSize); | ||||
|     services.Configure<GzipCompressionProviderOptions>(opt => opt.Level = CompressionLevel.SmallestSize); | ||||
|     services.AddResponseCompression(opt => | ||||
|     { | ||||
|         options.JsonSerializerOptions.WriteIndented = true; | ||||
|         options.JsonSerializerOptions.MaxDepth = 20; | ||||
|         options.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals; | ||||
|         opt.EnableForHttps = true; | ||||
|         opt.Providers.Add<BrotliCompressionProvider>(); | ||||
|         opt.Providers.Add<GzipCompressionProvider>(); | ||||
|     }); | ||||
|     services.Configure<BrotliCompressionProviderOptions>(options => | ||||
|     { | ||||
|         options.Level = CompressionLevel.SmallestSize; | ||||
|     }); | ||||
|     services.Configure<GzipCompressionProviderOptions>(options => | ||||
|     { | ||||
|         options.Level = CompressionLevel.SmallestSize; | ||||
|     }); | ||||
|     services.AddResponseCompression(options => | ||||
|     { | ||||
|         options.EnableForHttps = true; | ||||
|         options.Providers.Add<BrotliCompressionProvider>(); | ||||
|         options.Providers.Add<GzipCompressionProvider>(); | ||||
|     }); | ||||
|     services.AddResponseCaching(); | ||||
|  | ||||
|     services.AddControllers(); | ||||
|     services.AddSwaggerGen(builder.Configuration, "Core.Thalos.BFF.Api.xml", authSettings); | ||||
|     services.AddVersioning(builder.Configuration); | ||||
|     services.AddLogging(); | ||||
|     services.AddProblemDetails(); | ||||
|     services.AddHttpContextAccessor(); | ||||
|     services.AddTransient<TrackingMechanismExtension>(); // Register the TrackingIdHandler | ||||
|     services.AddTransient<TrackingMechanismExtension>(); | ||||
|     services.RegisterExternalLayer(builder.Configuration); | ||||
| }); | ||||
|  | ||||
| builder.Services.AddCors(options => | ||||
| { | ||||
|     options.AddDefaultPolicy( | ||||
|         builder => | ||||
|         { | ||||
|             builder.AllowAnyOrigin() | ||||
|                                 .AllowAnyHeader() | ||||
|                                 .AllowAnyMethod(); | ||||
|         }); | ||||
|     services.AddApiVersioning(options => options.ReportApiVersions = true) | ||||
|            .AddApiExplorer(opt => | ||||
|            { | ||||
|                opt.GroupNameFormat = "'v'VVV"; | ||||
|                opt.SubstituteApiVersionInUrl = true; | ||||
|            }); | ||||
| }); | ||||
|  | ||||
| builder.Services.AddScoped<ITokenService, TokenService>(); | ||||
|  | ||||
| builder.Services.AddOutputCache(options => | ||||
| var app = builder.Build(); | ||||
|  | ||||
| app.UseDeveloperExceptionPage(); | ||||
|  | ||||
| app.UseSwagger(); | ||||
|  | ||||
| app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:7239")); | ||||
| app.UseSwaggerUI(options => | ||||
| { | ||||
|     options.AddBasePolicy(builder => | ||||
|         builder.Expire(TimeSpan.FromSeconds(10))); | ||||
|     options.AddPolicy("Expire20", builder => | ||||
|         builder.Expire(TimeSpan.FromSeconds(20))); | ||||
|     options.AddPolicy("Expire30", builder => | ||||
|         builder.Expire(TimeSpan.FromSeconds(30))); | ||||
|     foreach (var version in app.DescribeApiVersions().Select(v => v.GroupName)) | ||||
|         options.SwaggerEndpoint($"/swagger/{version}/swagger.json", version); | ||||
|  | ||||
|     options.DisplayRequestDuration(); | ||||
|     options.EnableTryItOutByDefault(); | ||||
|     options.DocExpansion(DocExpansion.None); | ||||
|  | ||||
|     options.OAuthClientId(googleClientId); | ||||
|     options.OAuthClientSecret(googleClientSecret); | ||||
|     options.OAuthUsePkce(); | ||||
|     options.OAuthScopes("openid", "email", "profile"); | ||||
| }); | ||||
|  | ||||
| //*************************************************************************// | ||||
| var app = builder.Build(); | ||||
| app.UseLogging(builder.Configuration); | ||||
| app.UseSwaggerUI(builder.Configuration, authSettings); | ||||
| app.ConfigureSwagger(builder.Configuration); | ||||
|  | ||||
|  | ||||
| app.UseRouting(); | ||||
| app.UseCors(); | ||||
| app.UseHttpsRedirection(); | ||||
| app.UseStaticFiles(); | ||||
| app.UseResponseCompression(); | ||||
| app.UseOutputCache(); | ||||
| app.UseResponseCaching(); | ||||
| app.UseHttpsRedirection(); | ||||
|  | ||||
| app.UseAuthentication(); | ||||
| app.UseAuthorization(); | ||||
|  | ||||
| app.MapControllers(); | ||||
| //app.MapHealthChecks("/health"); | ||||
|  | ||||
| app.Run(); | ||||
| app.UseHsts(); | ||||
| app.UseAntiforgery(); | ||||
| app.UseLogging(builder.Configuration); | ||||
| app.Run(); | ||||
|   | ||||
							
								
								
									
										7
									
								
								Core.Thalos.BFF.Api/Services/Constant.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										7
									
								
								Core.Thalos.BFF.Api/Services/Constant.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,7 @@ | ||||
| namespace Core.Thalos.BFF.Api.Services | ||||
| { | ||||
|     public static class Constant | ||||
|     { | ||||
|         public const string Scheme = "GoogleAccessToken"; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,61 @@ | ||||
| using Google.Apis.Auth; | ||||
| using Google.Apis.Auth.OAuth2.Flows; | ||||
| using Microsoft.AspNetCore.Authentication; | ||||
| using Microsoft.Extensions.Options; | ||||
| using System.Security.Claims; | ||||
| using System.Text.Encodings.Web; | ||||
|  | ||||
| namespace Core.Thalos.BFF.Api.Services | ||||
| { | ||||
|     public class GoogleAccessTokenAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, | ||||
|          ILoggerFactory logger, | ||||
|          UrlEncoder encoder, | ||||
|          IConfiguration config) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder) | ||||
|     { | ||||
|         protected override async Task<AuthenticateResult> HandleAuthenticateAsync() | ||||
|         { | ||||
|             if (!Request.Headers.ContainsKey("Authorization")) | ||||
|                 return AuthenticateResult.Fail("Missing Authorization header"); | ||||
|  | ||||
|             var authHeader = Request.Headers.Authorization.ToString(); | ||||
|             if (!authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) | ||||
|                 return AuthenticateResult.Fail("Invalid Authorization header"); | ||||
|  | ||||
|             var idToken = authHeader["Bearer ".Length..].Trim(); | ||||
|  | ||||
|             GoogleJsonWebSignature.Payload payload; | ||||
|             try | ||||
|             { | ||||
|                 payload = await GoogleJsonWebSignature.ValidateAsync( | ||||
|                     idToken, | ||||
|                     new GoogleJsonWebSignature.ValidationSettings | ||||
|                     { | ||||
|                         Audience = new[] { config["Authentication:Google:ClientId"]! } | ||||
|                     }); | ||||
|             } | ||||
|             catch (InvalidJwtException) | ||||
|             { | ||||
|                 return AuthenticateResult.Fail("Invalid Google token"); | ||||
|             } | ||||
|  | ||||
|             var claims = new List<Claim> | ||||
|             { | ||||
|                 new Claim(ClaimTypes.NameIdentifier, payload.Subject), | ||||
|                 new Claim(ClaimTypes.Email,          payload.Email), | ||||
|                 new Claim(ClaimTypes.Name,           payload.Name ?? "") | ||||
|             }; | ||||
|  | ||||
|             var identity = new ClaimsIdentity(claims, Constant.Scheme); | ||||
|             var principal = new ClaimsPrincipal(identity); | ||||
|  | ||||
|             var userEmail = principal.FindFirst(ClaimTypes.Email)?.Value; | ||||
|  | ||||
|             if (string.IsNullOrEmpty(userEmail) ||  | ||||
|                 !userEmail.EndsWith("@agilewebs.com", StringComparison.OrdinalIgnoreCase)) | ||||
|                 return AuthenticateResult.Fail("Unauthorized Access"); | ||||
|  | ||||
|             var ticket = new AuthenticationTicket(principal, Constant.Scheme); | ||||
|             return AuthenticateResult.Success(ticket); | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										37
									
								
								Core.Thalos.BFF.Api/Services/IGoogleAuthHelper.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										37
									
								
								Core.Thalos.BFF.Api/Services/IGoogleAuthHelper.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,37 @@ | ||||
| using Google.Apis.Auth.OAuth2; | ||||
| using Google.Apis.Oauth2.v2; | ||||
|  | ||||
| namespace Core.Thalos.BFF.Api.Services | ||||
| { | ||||
|     public interface IGoogleAuthHelper | ||||
|     { | ||||
|         string[] GetScopes(); | ||||
|         string ScopeToString(); | ||||
|         ClientSecrets GetClientSecrets(); | ||||
|     } | ||||
|  | ||||
|     public class GoogleAuthHelperService(IConfiguration config) : IGoogleAuthHelper | ||||
|     { | ||||
|         public ClientSecrets GetClientSecrets() | ||||
|         { | ||||
|             string clientId = config["Authentication:Google:ClientId"]!; | ||||
|             string clientSecret = config["Authentication:Google:ClientSecret"]!; | ||||
|  | ||||
|             return new() { ClientId = clientId, ClientSecret = clientSecret }; | ||||
|         } | ||||
|  | ||||
|         public string[] GetScopes() | ||||
|         { | ||||
|             var scopes = new[] | ||||
|             { | ||||
|                 Oauth2Service.Scope.Openid, | ||||
|                 Oauth2Service.Scope.UserinfoEmail, | ||||
|                 Oauth2Service.Scope.UserinfoProfile | ||||
|             }; | ||||
|  | ||||
|             return scopes; | ||||
|         } | ||||
|  | ||||
|         public string ScopeToString() => string.Join(", ", GetScopes()); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										42
									
								
								Core.Thalos.BFF.Api/Services/IGoogleAuthorization.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								Core.Thalos.BFF.Api/Services/IGoogleAuthorization.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,42 @@ | ||||
| using Google.Apis.Auth.OAuth2; | ||||
| using Google.Apis.Auth.OAuth2.Flows; | ||||
|  | ||||
| namespace Core.Thalos.BFF.Api.Services | ||||
| { | ||||
|     public interface IGoogleAuthorization | ||||
|     { | ||||
|         string GetAuthorizationUrl(); | ||||
|         Task<UserCredential> ExchangeCodeForToken(string code); | ||||
|     } | ||||
|  | ||||
|     public class GoogleAuthorizationService( | ||||
|         IGoogleAuthHelper googleHelper, IConfiguration config) : IGoogleAuthorization | ||||
|     { | ||||
|         private string RedirectUrl = config["Authentication:Google:RedirectUri"]!; | ||||
|  | ||||
|         public async Task<UserCredential> ExchangeCodeForToken(string code) | ||||
|         { | ||||
|             var flow = new GoogleAuthorizationCodeFlow( | ||||
|                 new GoogleAuthorizationCodeFlow.Initializer | ||||
|                 { | ||||
|                     ClientSecrets = googleHelper.GetClientSecrets(), | ||||
|                     Scopes = googleHelper.GetScopes() | ||||
|                 }); | ||||
|  | ||||
|             var token = await flow.ExchangeCodeForTokenAsync( | ||||
|                 "user", code, RedirectUrl, CancellationToken.None); | ||||
|  | ||||
|             return new UserCredential(flow, "user", token); | ||||
|         } | ||||
|  | ||||
|         public string GetAuthorizationUrl() => | ||||
|             new GoogleAuthorizationCodeFlow( | ||||
|                 new GoogleAuthorizationCodeFlow.Initializer | ||||
|                 { | ||||
|  | ||||
|                     ClientSecrets = googleHelper.GetClientSecrets(), | ||||
|                     Scopes = googleHelper.GetScopes(), | ||||
|                     Prompt = "consent" | ||||
|                 }).CreateAuthorizationCodeRequest(RedirectUrl).Build().ToString(); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										4
									
								
								Core.Thalos.BFF.Api/Services/Token.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										4
									
								
								Core.Thalos.BFF.Api/Services/Token.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,4 @@ | ||||
| namespace Core.Thalos.BFF.Api.Services | ||||
| { | ||||
|     public record Token(string IdToken); | ||||
| } | ||||
| @@ -8,18 +8,13 @@ | ||||
|   "LocalGateways": { | ||||
|     "ThalosService": "https://localhost:7253/api" | ||||
|   }, | ||||
|   "ServiceSettings": { | ||||
|     "ApplicationName": "thalos", | ||||
|     "LayerName": "bff" | ||||
|   }, | ||||
|   "Vault": { | ||||
|     "Address": "http://100.123.31.103:8200", | ||||
|     "Token": "hvs.e37LQvLuPhTd5ALS5QQ03Cwm", | ||||
|     "SecretMount": "secret" | ||||
|   }, | ||||
|   "IdentityProviders": { | ||||
|     "Google": true, | ||||
|     "Azure": true | ||||
|   "Authentication": { | ||||
|     "Google": { | ||||
|       "ClientId": "128345072002-mtfdgpcur44o9tbd7q6e0bb9qnp2crfp.apps.googleusercontent.com", | ||||
|       "ClientSecret": "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", | ||||
|       "ApplicationName": "Thalos", | ||||
|       "RedirectUri": "https://localhost:7239/api/v1/Authentication/callback" | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -1,4 +1,6 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Contracts; | ||||
| using Core.Thalos.Adapters.Handlers; | ||||
| using Core.Thalos.Adapters.TokenProvider; | ||||
| using Core.Thalos.External.GatewayConfigurations; | ||||
| using LSA.Dashboard.External.Clients.Dashboard; | ||||
| using Microsoft.AspNetCore.Http; | ||||
|   | ||||
| @@ -1,6 +1,6 @@ | ||||
| using Core.Thalos.Application.UseCases.Roles.Input; | ||||
| using Core.Thalos.Adapters; | ||||
| using Core.Thalos.Application.UseCases.Roles.Input; | ||||
| using Core.Thalos.Application.UseCases.Users.Input; | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.External.Clients.Thalos.Requests.Permissions; | ||||
| using Core.Thalos.External.Clients.Thalos.Requests.Users; | ||||
| using Microsoft.AspNetCore.Mvc; | ||||
| @@ -40,6 +40,18 @@ namespace LSA.Dashboard.External.Clients.Dashboard | ||||
|         [Patch("/v1/User/ChangeStatus")] | ||||
|         Task<ApiResponse<UserAdapter>> ChangeUserStatusService([Header("TrackingId")][Body] ChangeUserStatusRequest request, CancellationToken cancellationToken = default); | ||||
|  | ||||
|         [Post("/v1/User/AddCompany")] | ||||
|         Task<ApiResponse<UserAdapter>> AddCompanyToUserService([Header("TrackingId")][Body] AddCompanyToUserRequest request, CancellationToken cancellationToken = default); | ||||
|  | ||||
|         [Delete("/v1/User/RemoveCompany")] | ||||
|         Task<ApiResponse<UserAdapter>> RemoveCompanyFromUserService([Header("TrackingId")][Body] RemoveCompanyFromUserRequest request, CancellationToken cancellationToken = default); | ||||
|  | ||||
|         [Post("/v1/User/AddProject")] | ||||
|         Task<ApiResponse<UserAdapter>> AddProjectToUserService([Header("TrackingId")][Body] AddProjectToUserRequest request, CancellationToken cancellationToken = default); | ||||
|  | ||||
|         [Delete("/v1/User/RemoveProject")] | ||||
|         Task<ApiResponse<UserAdapter>> RemoveProjectFromUserService([Header("TrackingId")][Body] RemoveProjectFromUserRequest request, CancellationToken cancellationToken = default); | ||||
|  | ||||
|         [Post("/v1/User/GetTokenAdapter")] | ||||
|         Task<ApiResponse<TokenAdapter>> GetTokenAdapterService([Header("TrackingId")][Body] GetTokenAdapterRequest request, CancellationToken cancellationToken = default); | ||||
|  | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Enums; | ||||
|  | ||||
| namespace Core.Thalos.External.Clients.Thalos.Requests.Permissions | ||||
| { | ||||
|   | ||||
| @@ -1,4 +1,5 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Blueprint.Mongo; | ||||
| using Core.Thalos.Adapters.Common.Enums; | ||||
| using StatusEnum = Core.Blueprint.Mongo.StatusEnum; | ||||
|  | ||||
| namespace Core.Thalos.External.Clients.Thalos.Requests.Permissions | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
|  | ||||
| namespace Core.Thalos.External.Clients.Thalos.Requests.Permissions | ||||
| { | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Constants; | ||||
| using StatusEnum = Core.Blueprint.Mongo.StatusEnum; | ||||
|  | ||||
| namespace Core.Thalos.External.Clients.Thalos.Requests.Permissions | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Enums; | ||||
|  | ||||
| namespace Core.Thalos.Application.UseCases.Roles.Input | ||||
| { | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Enums; | ||||
| using System.Text.Json.Serialization; | ||||
|  | ||||
| namespace Core.Thalos.Application.UseCases.Roles.Input | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Enums; | ||||
|  | ||||
| namespace Core.Thalos.Application.UseCases.Roles.Input | ||||
| { | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| using Core.Thalos.BuildingBlocks; | ||||
| using Core.Thalos.Adapters.Common.Enums; | ||||
| using System.Text.Json.Serialization; | ||||
| using StatusEnum = Core.Blueprint.Mongo.StatusEnum; | ||||
|  | ||||
|   | ||||
| @@ -0,0 +1,8 @@ | ||||
| namespace Core.Thalos.Application.UseCases.Users.Input | ||||
| { | ||||
|     public class AddCompanyToUserRequest | ||||
|     { | ||||
|         public string UserId { get; set; } | ||||
|         public string CompanyId { get; set; } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,8 @@ | ||||
| namespace Core.Thalos.Application.UseCases.Users.Input | ||||
| { | ||||
|     public class AddProjectToUserRequest | ||||
|     { | ||||
|         public string UserId { get; set; } | ||||
|         public string ProjectId { get; set; } | ||||
|     } | ||||
| } | ||||
| @@ -7,6 +7,8 @@ | ||||
|         public string? MiddleName { get; set; } | ||||
|         public string LastName { get; set; } = null!; | ||||
|         public string RoleId { get; set; } = null!; | ||||
|         public string[] Companies { get; set; } = null!; | ||||
|         public string[]? Projects { get; set; } | ||||
|         public bool SendInvitation { get; set; } | ||||
|     } | ||||
| } | ||||
|   | ||||
| @@ -0,0 +1,8 @@ | ||||
| namespace Core.Thalos.Application.UseCases.Users.Input | ||||
| { | ||||
|     public class RemoveCompanyFromUserRequest | ||||
|     { | ||||
|         public string UserId { get; set; } | ||||
|         public string CompanyId { get; set; } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,8 @@ | ||||
| namespace Core.Thalos.Application.UseCases.Users.Input | ||||
| { | ||||
|     public class RemoveProjectFromUserRequest | ||||
|     { | ||||
|         public string UserId { get; set; } | ||||
|         public string ProjectId { get; set; } | ||||
|     } | ||||
| } | ||||
| @@ -7,7 +7,7 @@ | ||||
|   </PropertyGroup> | ||||
|  | ||||
|   <ItemGroup> | ||||
|     <PackageReference Include="Core.Thalos.BuildingBlocks" Version="1.0.8" /> | ||||
|     <PackageReference Include="Core.Thalos.BuildingBlocks" Version="1.0.2" /> | ||||
|     <PackageReference Include="Lib.Architecture.BuildingBlocks" Version="1.0.0" /> | ||||
|     <PackageReference Include="Refit" Version="8.0.0" /> | ||||
|   </ItemGroup> | ||||
|   | ||||
		Reference in New Issue
	
	Block a user