Skip to content

Commit

Permalink
(#56) auth: add library [build-test-force] [pack-all-force]
Browse files Browse the repository at this point in the history
  • Loading branch information
SaintAngeLs committed Sep 23, 2024
1 parent 55501a5 commit fa138e3
Show file tree
Hide file tree
Showing 19 changed files with 759 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/Paralax.Auth/scripts/build-and-pack.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/bin/bash

echo "Executing post-success scripts for branch $GITHUB_REF_NAME"
echo "Starting build and NuGet package creation for Paralax framework..."

cd src/Paralax.Auth/src/Paralax.Auth

echo "Restoring NuGet packages..."
dotnet restore

PACKAGE_VERSION="1.0.$GITHUB_RUN_NUMBER"
echo "Building and packing the Paralax.Auth library..."
dotnet pack -c release /p:PackageVersion=$PACKAGE_VERSION --no-restore -o ./nupkg

PACKAGE_PATH="./nupkg/Paralax.Auth.$PACKAGE_VERSION.nupkg"

if [ -f "$PACKAGE_PATH" ]; then
echo "Checking if the package is already signed..."
if dotnet nuget verify "$PACKAGE_PATH" | grep -q 'Package is signed'; then
echo "Package is already signed, skipping signing."
else
echo "Signing the NuGet package..."
dotnet nuget sign "$PACKAGE_PATH" \
--certificate-path "$CERTIFICATE_PATH" \
--timestamper http://timestamp.digicert.com
fi

echo "Uploading Paralax.Auth package to NuGet..."
dotnet nuget push "$PACKAGE_PATH" -k "$NUGET_API_KEY" \
-s https://api.nuget.org/v3/index.json --skip-duplicate
echo "Package uploaded to NuGet."
else
echo "Error: Package $PACKAGE_PATH not found."
exit 1
fi
18 changes: 18 additions & 0 deletions src/Paralax.Auth/scripts/test-and-collect-coverage.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash

echo "Running tests and collecting coverage for Paralax.Auth..."

cd src/Paralax.Auth/tests/Paralax.Auth

echo "Restoring NuGet packages..."
dotnet restore

echo "Running tests and generating code coverage report..."
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults

# Check if tests succeeded
if [ $? -ne 0 ]; then
echo "Tests failed. Exiting..."
exit 1
fi

Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Paralax.Auth
{
public class AccessTokenValidatorMiddleware : IMiddleware
{
private readonly IAccessTokenService _accessTokenService;
private readonly IEnumerable<string> _endpoints;

public AccessTokenValidatorMiddleware(IAccessTokenService accessTokenService, JwtOptions options)
{
_accessTokenService = accessTokenService;
_endpoints = options.AllowAnonymousEndpoints ?? Enumerable.Empty<string>();
}

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var path = context.Request.Path.HasValue ? context.Request.Path.Value : string.Empty;

if (_endpoints.Contains(path))
{
await next(context);
return;
}

if (await _accessTokenService.IsCurrentActiveToken())
{
await next(context);
return;
}

context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
}
}
12 changes: 12 additions & 0 deletions src/Paralax.Auth/src/Paralax.Auth/AuthAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Authorization;

namespace Paralax.Auth
{
public class AuthAttribute : AuthorizeAttribute
{
public AuthAttribute(string scheme, string policy = "") : base(policy)
{
AuthenticationSchemes = scheme;
}
}
}
56 changes: 56 additions & 0 deletions src/Paralax.Auth/src/Paralax.Auth/Builders/JwtOptionsBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;

namespace Paralax.Auth.Builders
{
internal sealed class JwtOptionsBuilder : IJwtOptionsBuilder
{
private readonly JwtOptions _options = new();

public IJwtOptionsBuilder WithIssuerSigningKey(string issuerSigningKey)
{
_options.IssuerSigningKey = issuerSigningKey;
return this;
}

public IJwtOptionsBuilder WithIssuer(string issuer)
{
_options.ValidIssuer = issuer;
return this;
}

public IJwtOptionsBuilder WithExpiry(TimeSpan expiry)
{
_options.Expiry = expiry;
return this;
}

public IJwtOptionsBuilder WithExpiryMinutes(int expiryMinutes)
{
_options.ExpiryMinutes = expiryMinutes;
return this;
}

public IJwtOptionsBuilder WithLifetimeValidation(bool validateLifetime)
{
_options.ValidateLifetime = validateLifetime;
return this;
}

public IJwtOptionsBuilder WithAudienceValidation(bool validateAudience)
{
_options.ValidateAudience = validateAudience;
return this;
}

public IJwtOptionsBuilder WithValidAudience(string validAudience)
{
_options.ValidAudience = validAudience;
return this;
}

public JwtOptions Build()
{
return _options;
}
}
}
23 changes: 23 additions & 0 deletions src/Paralax.Auth/src/Paralax.Auth/Dates/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;

namespace Paralax.Auth.Dates
{
internal static class Extensions
{
// Converts DateTime to Unix timestamp (seconds since 1 January 1970)
public static long ToTimestamp(this DateTime dateTime)
=> new DateTimeOffset(dateTime).ToUnixTimeSeconds();

// Converts Unix timestamp to DateTime (UTC)
public static DateTime FromTimestamp(this long timestamp)
=> DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;

// Converts DateTime to Unix timestamp in milliseconds
public static long ToTimestampMilliseconds(this DateTime dateTime)
=> new DateTimeOffset(dateTime).ToUnixTimeMilliseconds();

// Converts Unix timestamp in milliseconds to DateTime (UTC)
public static DateTime FromTimestampMilliseconds(this long timestampMilliseconds)
=> DateTimeOffset.FromUnixTimeMilliseconds(timestampMilliseconds).UtcDateTime;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;

namespace Paralax.Auth
{
/// <summary>
/// This class bypasses the usual authentication process, returning a successful authentication result for any request.
/// This is useful when authentication is disabled, allowing the request to be processed without enforcing security checks.
/// </summary>
internal sealed class DisabledAuthenticationPolicyEvaluator : IPolicyEvaluator
{
/// <summary>
/// Simulates the authentication process and returns a successful result.
/// </summary>
/// <param name="policy">Authorization policy to be evaluated.</param>
/// <param name="context">The current HTTP context.</param>
/// <returns>A successful authentication result.</returns>
public Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
{
// Creating an authentication ticket with an empty claims principal and properties
var authenticationTicket = new AuthenticationTicket(new ClaimsPrincipal(),
new AuthenticationProperties(), JwtBearerDefaults.AuthenticationScheme);

// Returning a successful authentication result
return Task.FromResult(AuthenticateResult.Success(authenticationTicket));
}

/// <summary>
/// Simulates the authorization process and returns a successful result.
/// </summary>
/// <param name="policy">Authorization policy to be evaluated.</param>
/// <param name="authenticationResult">The result of the authentication process.</param>
/// <param name="context">The current HTTP context.</param>
/// <param name="resource">An optional resource object.</param>
/// <returns>A successful policy authorization result.</returns>
public Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy,
AuthenticateResult authenticationResult, HttpContext context, object resource)
{
// Returning a successful authorization result
return Task.FromResult(PolicyAuthorizationResult.Success());
}
}
}
Loading

0 comments on commit fa138e3

Please sign in to comment.