Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/PATRO23-133 - User context provider #45

Merged
merged 2 commits into from
Apr 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/modules/example/api/Controllers/ExampleController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ namespace Intive.Patronage2023.Modules.Example.Api.Controllers;
[Route("[controller]")]
public class ExampleController : ControllerBase
{
private readonly IExecutionContextAccessor contextAccessor;
private readonly ICommandBus commandBus;
private readonly IQueryBus queryBus;
private readonly IValidator<CreateExample> createExampleValidator;
Expand All @@ -30,12 +31,14 @@ public class ExampleController : ControllerBase
/// <param name="queryBus">Query bus.</param>
/// <param name="createExampleValidator">Create example validator.</param>
/// <param name="getExamplesValidator">Get examples validator.</param>
public ExampleController(ICommandBus commandBus, IQueryBus queryBus, IValidator<CreateExample> createExampleValidator, IValidator<GetExamples> getExamplesValidator)
/// <param name="contextAccessor">Execution context accessor.</param>
public ExampleController(ICommandBus commandBus, IQueryBus queryBus, IValidator<CreateExample> createExampleValidator, IValidator<GetExamples> getExamplesValidator, IExecutionContextAccessor contextAccessor)
{
this.createExampleValidator = createExampleValidator;
this.getExamplesValidator = getExamplesValidator;
this.commandBus = commandBus;
this.queryBus = queryBus;
this.contextAccessor = contextAccessor;
}

/// <summary>
Expand Down Expand Up @@ -94,4 +97,24 @@ public async Task<IActionResult> CreateExample([FromBody] CreateExample request)

throw new AppException("One or more error occured when trying to create example.", validationResult.Errors);
}

/// <summary>
/// Get user guid.
/// </summary>
/// <returns>User guid or null.</returns>
/// <response code="200">Returns current user guid.</response>
/// <response code="401">If the user is unauthorized or token is invalid.</response>
[HttpGet("/UserGuid")]
[ProducesResponseType(typeof(Guid?), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public IActionResult GetUserId()
{
var userId = this.contextAccessor.GetUserId(this.HttpContext);
if (userId == null)
{
return this.Unauthorized();
}

return this.Ok(userId);
}
}
3 changes: 2 additions & 1 deletion src/modules/example/api/ExampleModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Intive.Patronage2023.Modules.Example.Infrastructure.Data;
using Intive.Patronage2023.Modules.Example.Infrastructure.Domain;
using Intive.Patronage2023.Shared.Abstractions;

using Intive.Patronage2023.Shared.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace Intive.Patronage2023.Modules.Example.Api;
Expand All @@ -26,6 +26,7 @@ public static IServiceCollection AddExampleModule(this IServiceCollection servic
{
services.AddDbContext<ExampleDbContext>(options => options.UseSqlServer(configurationManager.GetConnectionString("AppDb")));

services.AddScoped<IExecutionContextAccessor, ExecutionContextAccessor>();
services.AddScoped<IExampleRepository, ExampleRepository>();
services.AddScoped<IValidator<CreateExample>, CreateExampleValidator>();
services.AddScoped<IValidator<GetExamples>, GetExamplesValidator>();
Expand Down
16 changes: 16 additions & 0 deletions src/shared/abstractions/IExecutionContextAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Http;

namespace Intive.Patronage2023.Shared.Abstractions;

/// <summary>
/// Interface to retrive user id from HttpContext.
/// </summary>
public interface IExecutionContextAccessor
{
/// <summary>
/// Returns user id extraced from token.
/// </summary>
/// <param name="httpContext">Context to retrive token from.</param>
/// <returns>User id or null if token/claim does not exits.</returns>
Guid? GetUserId(HttpContext httpContext);
}
34 changes: 34 additions & 0 deletions src/shared/infrastructure/ExecutionContextAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.IdentityModel.Tokens.Jwt;
using Intive.Patronage2023.Shared.Abstractions;
using Microsoft.AspNetCore.Http;

namespace Intive.Patronage2023.Shared.Infrastructure;

/// <summary>
/// Implementation of IExecutionContextAccessor.
/// </summary>
public class ExecutionContextAccessor : IExecutionContextAccessor
{
/// <inheritdoc />
public Guid? GetUserId(HttpContext httpContext)
{
string? jwtToken = httpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
if (jwtToken == null)
{
// User is not authenticated
return null;
}

var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.ReadJwtToken(jwtToken);

if (token == null || token.Claims.All(c => c.Type != "sub"))
{
// JWT token is invalid
return null;
}

var userId = Guid.Parse(token.Claims.First(c => c.Type == "sub").Value);
return userId;
}
}