Skip to content

Commit

Permalink
SonarQube fixes, Sam's comment. Missing username and logout implement
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineatstariongroup committed Jan 21, 2025
1 parent 54c4cb3 commit 94ddad7
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 148 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,12 @@ public async Task<AuthenticationPerson> Authenticate(string username, string pas
}
catch (NpgsqlException ex)
{
transaction?.RollbackAsync();

this.Logger.LogCritical( "The AuthenticationPersonAuthenticator could not interact with the CDP4-COMET database");

throw new AuthenticatorException("The authenticator could not connect to the CDP4-COMET database", innerException: ex);
}
catch (Exception ex)
{
transaction?.RollbackAsync();

this.Logger.LogCritical(ex, "There was an error while authenticating the user credentials");

throw new AuthenticatorException("There was an error while authenticating the user credentials", innerException: ex);
Expand Down
7 changes: 1 addition & 6 deletions CometServer/Authentication/JwtTokenService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ namespace CometServer.Authentication
/// </summary>
public class JwtTokenService : IJwtTokenService
{
/// <summary>
/// Provides the expiration times of a generated JWT token, in minutes
/// </summary>
private const int ExpirationMinutes = 30;

/// <summary>
/// The (injected) logger
/// </summary>
Expand Down Expand Up @@ -83,7 +78,7 @@ public JwtTokenService(ILogger<JwtTokenService> logger, IAppConfigService appCon
/// <returns>The created JWT token</returns>
public string CreateToken(AuthenticationPerson authenticationPerson)
{
var expiration = DateTime.UtcNow.AddMinutes(ExpirationMinutes);
var expiration = DateTime.UtcNow.AddMinutes(this.appConfigService.AppConfig.AuthenticationConfig.LocalJwtAuthenticationConfig.TokenExpirationMinutes);

var jwtSecurityToken = this.CreateJwtSecurityToken(
CreateClaims(authenticationPerson),
Expand Down
113 changes: 0 additions & 113 deletions CometServer/CometServer.csproj.orig

This file was deleted.

14 changes: 12 additions & 2 deletions CometServer/Configuration/LocalJwtAuthenticationConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public LocalJwtAuthenticationConfig()
this.ValidIssuer = "CDP4-COMET";
this.ValidAudience = "localhost:5000";
this.SymmetricSecurityKey = "needs-to-be-updated-with-a-secret";
}
}

/// <summary>
/// Initializes a new instance of the <see cref="LocalJwtAuthenticationConfig"/> class
Expand All @@ -55,8 +55,13 @@ public LocalJwtAuthenticationConfig(IConfiguration configuration)
this.ValidIssuer = configuration["Authentication:LocalJwtBearer:ValidIssuer"];
this.ValidAudience = configuration["Authentication:LocalJwtBearer:ValidAudience"];
this.SymmetricSecurityKey = configuration["Authentication:LocalJwtBearer:SymmetricSecurityKey"];

if (int.TryParse(configuration["Authentication:LocalJwtBearer:TokenExpirationMinutes"], out var tokenExpirationMinutes))
{
this.TokenExpirationMinutes = tokenExpirationMinutes;
}
}

/// <summary>
/// Gets or sets a value indicating whether Local JWT Authentication is enabled or not
/// </summary>
Expand All @@ -82,5 +87,10 @@ public LocalJwtAuthenticationConfig(IConfiguration configuration)
/// Gets or sets the symmetric security key with which the bearer tokens are generated and also validated
/// </summary>
public string SymmetricSecurityKey { get; set; }

/// <summary>
/// Gets or sets the expiration time of a generated JWT Token, in minutes (defaults: 30)
/// </summary>
public int TokenExpirationMinutes { get; set; } = 30;
}
}
3 changes: 3 additions & 0 deletions CometServer/Extensions/HttpRequestExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ public static string QueryNameMethodPath(this HttpRequest httpRequest)
/// <returns>Value of the assert</returns>
public static bool DoesAuthorizationHeaderMatches(this HttpRequest request, string expectedAuthorizationScheme)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(expectedAuthorizationScheme);

var authorizationHeader = request.Headers.Authorization;

if (string.IsNullOrEmpty(authorizationHeader))
Expand Down
36 changes: 23 additions & 13 deletions CometServer/Modules/10-25/ApiBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ protected async Task<string> Authorize(IAppConfigService appConfigService, ICred
case PersonIdentifierPropertyKind.Iid:
if (!Guid.TryParse(claim.Value, out var userId))
{
throw new AuthenticationException();
throw new AuthenticationException("Provided claim value is not a valid GUID.");
}

await this.Authorize(appConfigService, credentialsService, userId);
Expand All @@ -236,10 +236,10 @@ protected async Task<string> Authorize(IAppConfigService appConfigService, ICred
return claim.Value;
}

this.logger.LogWarning("Identifier claim {ClaimName} missing User Claims",
this.logger.LogWarning("Identifier claim {ClaimName} missing from User Claims",
appConfigService.AppConfig.AuthenticationConfig.ExternalJwtAuthenticationConfig.IdentifierClaimName);

throw new AuthorizationException();
throw new AuthorizationException($"Identifer claim {appConfigService.AppConfig.AuthenticationConfig.ExternalJwtAuthenticationConfig.IdentifierClaimName} missing from User Claims");
}

/// <summary>
Expand Down Expand Up @@ -642,13 +642,13 @@ protected async Task WriteMessagePackResponse(IHeaderInfoProvider headerInfoProv
/// <returns>
/// The <see cref="HttpResponse"/>.
/// </returns>
protected void WriteMultipartResponse(IHeaderInfoProvider headerInfoProvider, IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileBinaryService fileBinaryService, IPermissionInstanceFilterService permissionInstanceFilterService, List<FileRevision> fileRevisions, List<Thing> resourceResponse, Version version, HttpResponse httpResponse, HttpStatusCode statusCode = HttpStatusCode.OK)
protected Task WriteMultipartResponse(IHeaderInfoProvider headerInfoProvider, IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileBinaryService fileBinaryService, IPermissionInstanceFilterService permissionInstanceFilterService, List<FileRevision> fileRevisions, List<Thing> resourceResponse, Version version, HttpResponse httpResponse, HttpStatusCode statusCode = HttpStatusCode.OK)
{
headerInfoProvider.RegisterResponseHeaders(httpResponse, ContentTypeKind.MULTIPARTMIXED, HttpConstants.BoundaryString);

httpResponse.StatusCode = (int)statusCode;

this.PrepareMultiPartResponse(metaInfoProvider,jsonSerializer, fileBinaryService, permissionInstanceFilterService, httpResponse.Body, fileRevisions, resourceResponse, version);
return this.PrepareMultiPartResponse(metaInfoProvider,jsonSerializer, fileBinaryService, permissionInstanceFilterService, httpResponse.Body, fileRevisions, resourceResponse, version);
}

/// <summary>
Expand Down Expand Up @@ -690,12 +690,12 @@ protected void WriteMultipartResponse(IHeaderInfoProvider headerInfoProvider, IM
/// <returns>
/// The <see cref="HttpResponse"/>.
/// </returns>
protected void WriteArchivedResponse(IHeaderInfoProvider headerInfoProvider, IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileArchiveService fileArchiveService, IPermissionInstanceFilterService permissionInstanceFilterService, List<Thing> resourceResponse, string partition, string[] routeSegments, Version version, HttpResponse httpResponse, HttpStatusCode statusCode = HttpStatusCode.OK)
protected Task WriteArchivedResponse(IHeaderInfoProvider headerInfoProvider, IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileArchiveService fileArchiveService, IPermissionInstanceFilterService permissionInstanceFilterService, List<Thing> resourceResponse, string partition, string[] routeSegments, Version version, HttpResponse httpResponse, HttpStatusCode statusCode = HttpStatusCode.OK)
{
headerInfoProvider.RegisterResponseHeaders(httpResponse, ContentTypeKind.MULTIPARTMIXED, HttpConstants.BoundaryString);
httpResponse.StatusCode = (int)statusCode;

this.PrepareArchivedResponse(metaInfoProvider,jsonSerializer, fileArchiveService, permissionInstanceFilterService, httpResponse.Body, resourceResponse, version, partition, routeSegments);
return this.PrepareArchivedResponse(metaInfoProvider,jsonSerializer, fileArchiveService, permissionInstanceFilterService, httpResponse.Body, resourceResponse, version, partition, routeSegments);
}

/// <summary>
Expand Down Expand Up @@ -858,7 +858,7 @@ private void CreateFilteredMessagePackResponseStream(IMessagePackSerializer mess
/// <param name="jsonSerializer">
/// The <see cref="ICdp4JsonSerializer"/> used to serialize data to JSOIN
/// </param>
private void PrepareMultiPartResponse(IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileBinaryService fileBinaryService, IPermissionInstanceFilterService permissionInstanceFilterService, Stream targetStream, List<FileRevision> fileRevisions, List<Thing> resourceResponse, Version requestDataModelVersion)
private async Task PrepareMultiPartResponse(IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileBinaryService fileBinaryService, IPermissionInstanceFilterService permissionInstanceFilterService, Stream targetStream, List<FileRevision> fileRevisions, List<Thing> resourceResponse, Version requestDataModelVersion)
{
if (fileRevisions.Count == 0)
{
Expand Down Expand Up @@ -892,7 +892,12 @@ private void PrepareMultiPartResponse(IMetaInfoProvider metaInfoProvider, ICdp4J
{
fileSize = fileStream.Length;
buffer = new byte[(int)fileSize];
fileStream.Read(buffer, 0, (int)fileSize);
var readBytes = fileStream.Read(buffer, 0, (int)fileSize);

if (readBytes != fileSize)
{
this.logger.LogWarning("Failed to read {FileSize} bytes, only read {ReadBytes}", fileSize, readBytes);
}
}

// write out the binary content to the first multipart content entry
Expand All @@ -906,7 +911,7 @@ private void PrepareMultiPartResponse(IMetaInfoProvider metaInfoProvider, ICdp4J
}

// stream the multipart content to the request contents target stream
content.CopyToAsync(targetStream).Wait();
await content.CopyToAsync(targetStream);
AddMultiPartMimeEndpoint(targetStream);
}

Expand Down Expand Up @@ -940,7 +945,7 @@ private void PrepareMultiPartResponse(IMetaInfoProvider metaInfoProvider, ICdp4J
/// <param name="routeSegments">
/// The route segments.
/// </param>
private void PrepareArchivedResponse(IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileArchiveService fileArchiveService, IPermissionInstanceFilterService permissionInstanceFilterService, Stream targetStream, List<Thing> resourceResponse, Version requestDataModelVersion, string partition, string[] routeSegments)
private async Task PrepareArchivedResponse(IMetaInfoProvider metaInfoProvider, ICdp4JsonSerializer jsonSerializer, IFileArchiveService fileArchiveService, IPermissionInstanceFilterService permissionInstanceFilterService, Stream targetStream, List<Thing> resourceResponse, Version requestDataModelVersion, string partition, string[] routeSegments)
{
var temporaryTopFolder = fileArchiveService.CreateFolderAndFileStructureOnDisk(resourceResponse, partition, routeSegments);

Expand Down Expand Up @@ -973,7 +978,12 @@ private void PrepareArchivedResponse(IMetaInfoProvider metaInfoProvider, ICdp4Js
{
fileSize = fileStream.Length;
buffer = new byte[(int)fileSize];
fileStream.Read(buffer, 0, (int)fileSize);
var readBytes = fileStream.Read(buffer, 0, (int)fileSize);

if (readBytes != fileSize)
{
this.logger.LogWarning("Failed to read {FileSize} bytes, only read {ReadBytes}", fileSize, readBytes);
}
}

var binaryContent = new ByteArrayContent(buffer);
Expand All @@ -989,7 +999,7 @@ private void PrepareArchivedResponse(IMetaInfoProvider metaInfoProvider, ICdp4Js
content.Add(binaryContent);

// stream the multipart content to the request contents target stream
content.CopyToAsync(targetStream).Wait();
await content.CopyToAsync(targetStream);

AddMultiPartMimeEndpoint(targetStream);
}
Expand Down
Loading

0 comments on commit 94ddad7

Please sign in to comment.