Compare commits
13 Commits
3a9c499aab
...
main
Author | SHA1 | Date | |
---|---|---|---|
|
a47030f90c | ||
|
1d519ada9d | ||
|
67d59039c1 | ||
|
b32ea7cf12 | ||
bde1e0c28f | |||
|
38832fd597 | ||
|
5dbb91de94 | ||
|
e4690dfe22 | ||
|
525d82ca27 | ||
|
ac664f16ce | ||
|
c3f58eb172 | ||
|
ce4139d100 | ||
|
582fe194b9 |
52
.gitea/workflows/BuildLibrary.yml
Normal file
52
.gitea/workflows/BuildLibrary.yml
Normal file
@@ -0,0 +1,52 @@
|
||||
name: Build C# Library
|
||||
|
||||
run-name: Build Library project
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET SDK
|
||||
uses: actions/setup-dotnet@v3
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore
|
||||
|
||||
- name: Build library
|
||||
run: dotnet build --configuration Release
|
||||
|
||||
- name: Pack DotBased
|
||||
run: dotnet pack ./DotBased/DotBased.csproj --configuration Release -o ./artifacts
|
||||
|
||||
- name: Pack DotBased.Logging.MEL
|
||||
run: dotnet pack ./DotBased.Logging.MEL/DotBased.Logging.MEL.csproj --configuration Release -o ./artifacts
|
||||
|
||||
- name: Pack DotBased.Logging.Serilog
|
||||
run: dotnet pack ./DotBased.Logging.Serilog/DotBased.Logging.Serilog.csproj --configuration Release -o ./artifacts
|
||||
|
||||
- name: Publish library to Gitea NuGet
|
||||
run: |
|
||||
dotnet nuget add source \
|
||||
--username $GITEA_USER \
|
||||
--password $GITEA_TOKEN \
|
||||
--store-password-in-clear-text \
|
||||
--name gitea \
|
||||
https://git.netzbyte.com/api/packages/$GITEA_USER/nuget/index.json
|
||||
|
||||
# --skip-duplicate - Prevents errors if the package already exists.
|
||||
# --api-key - An random value to silence the 'No API key found' warning.
|
||||
dotnet nuget push ./artifacts/*.nupkg --source gitea --skip-duplicate --api-key SILENCE_API_KEY_WARNING
|
||||
env:
|
||||
GITEA_USER: max
|
||||
GITEA_TOKEN: ${{ secrets.PACKAGES_TOKEN }}
|
@@ -1,98 +0,0 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using DotBased.ASP.Auth.Domains.Auth;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public class AuthDataCache
|
||||
{
|
||||
public AuthDataCache(BasedAuthConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
private readonly BasedAuthConfiguration _configuration;
|
||||
|
||||
private readonly AuthStateCacheCollection<AuthenticationStateModel, AuthenticationState> _authenticationStateCollection = [];
|
||||
|
||||
public Result PurgeSessionState(string id) => _authenticationStateCollection.Remove(id) ? Result.Ok() : Result.Failed("Failed to purge session state from cache! Or the session was not cached...");
|
||||
|
||||
public void CacheSessionState(AuthenticationStateModel stateModel, AuthenticationState? state = null) => _authenticationStateCollection[stateModel.Id] =
|
||||
new AuthStateCacheNode<AuthenticationStateModel, AuthenticationState>(stateModel, state);
|
||||
|
||||
public Result<Tuple<AuthenticationStateModel, AuthenticationState?>> RequestSessionState(string id)
|
||||
{
|
||||
if (!_authenticationStateCollection.TryGetValue(id, out var node))
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed("No cached object found!");
|
||||
string failedMsg;
|
||||
if (node.StateModel != null)
|
||||
{
|
||||
if (node.IsValidLifespan(_configuration.CachedAuthSessionLifespan))
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Ok(new Tuple<AuthenticationStateModel, AuthenticationState?>(node.StateModel, node.State));
|
||||
failedMsg = $"Session has invalid lifespan, removing entry: [{id}] from cache!";
|
||||
}
|
||||
else
|
||||
failedMsg = $"Returned object is null, removing entry: [{id}] from cache!";
|
||||
_authenticationStateCollection.Remove(id);
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed(failedMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public class AuthStateCacheNode<TStateModel, TState> where TStateModel : class where TState : class
|
||||
{
|
||||
public AuthStateCacheNode(TStateModel stateModel, TState? state)
|
||||
{
|
||||
StateModel = stateModel;
|
||||
State = state;
|
||||
}
|
||||
public TStateModel? StateModel { get; private set; }
|
||||
public TState? State { get; private set; }
|
||||
public DateTime DateCached { get; private set; } = DateTime.Now;
|
||||
|
||||
public void UpdateObject(TStateModel obj)
|
||||
{
|
||||
StateModel = obj;
|
||||
DateCached = DateTime.Now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the cached object is within the given lifespan.
|
||||
/// </summary>
|
||||
/// <param name="lifespan">The max. lifespan</param>
|
||||
public bool IsValidLifespan(TimeSpan lifespan) => DateCached.Add(lifespan) > DateTime.Now;
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
if (obj is AuthStateCacheNode<TStateModel, TState> cacheObj)
|
||||
return StateModel != null && StateModel.Equals(cacheObj.StateModel);
|
||||
return false;
|
||||
}
|
||||
|
||||
public override int GetHashCode() => typeof(TStateModel).GetHashCode();
|
||||
public override string ToString() => typeof(TStateModel).ToString();
|
||||
}
|
||||
|
||||
public class AuthStateCacheCollection<TStateModel, TState> : KeyedCollection<string, AuthStateCacheNode<TStateModel, TState>> where TStateModel : class where TState : class
|
||||
{
|
||||
protected override string GetKeyForItem(AuthStateCacheNode<TStateModel, TState> item) => item.StateModel?.ToString() ?? string.Empty;
|
||||
|
||||
public new AuthStateCacheNode<TStateModel, TState>? this[string id]
|
||||
{
|
||||
get => TryGetValue(id, out AuthStateCacheNode<TStateModel, TState>? nodeValue) ? nodeValue : null;
|
||||
set
|
||||
{
|
||||
if (value == null)
|
||||
return;
|
||||
if (TryGetValue(id, out AuthStateCacheNode<TStateModel, TState>? nodeValue))
|
||||
Remove(nodeValue);
|
||||
Add(value);
|
||||
}
|
||||
}
|
||||
|
||||
public void Insert(AuthStateCacheNode<TStateModel, TState> node)
|
||||
{
|
||||
if (Contains(node))
|
||||
Remove(node);
|
||||
Add(node);
|
||||
}
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Services;
|
||||
|
||||
public class AuthenticationService
|
||||
{
|
||||
public AuthenticationService()
|
||||
{
|
||||
/*
|
||||
* - Login
|
||||
* - Logout
|
||||
* - Register
|
||||
*/
|
||||
}
|
||||
}
|
@@ -1,65 +0,0 @@
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public class BasedAuthConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Allow users to registrate.
|
||||
/// </summary>
|
||||
public bool AllowRegistration { get; set; }
|
||||
//TODO: Callback when a user registers, so the application can handle sending emails or generate a code to complete the registration.
|
||||
//TODO: Callback for validation email, phone number
|
||||
/// <summary>
|
||||
/// Allow no passwords on users, not recommended!
|
||||
/// </summary>
|
||||
public bool AllowEmptyPassword { get; set; } = false;
|
||||
/// <summary>
|
||||
/// This path is used for redirecting to the login page.
|
||||
/// </summary>
|
||||
public string LoginPath { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// The path that will be used if the logout is requested.
|
||||
/// </summary>
|
||||
public string LogoutPath { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// The page that the client will be redirected to after logging out.
|
||||
/// </summary>
|
||||
public string LoggedOutPath { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// The max age before a AuthenticationState will expire (default: 7 days).
|
||||
/// </summary>
|
||||
public TimeSpan AuthenticationStateMaxAgeBeforeExpire { get; set; } = TimeSpan.FromDays(7);
|
||||
/// <summary>
|
||||
/// How long a session state will be cached (default: 15 min)
|
||||
/// </summary>
|
||||
public TimeSpan CachedAuthSessionLifespan { get; set; } = TimeSpan.FromMinutes(15);
|
||||
/// <summary>
|
||||
/// Can be used to seed a default user and/or group for first time use.
|
||||
/// </summary>
|
||||
public Action<IAuthDataRepository>? SeedData { get; set; }
|
||||
|
||||
public Type? AuthDataRepositoryType { get; private set; }
|
||||
|
||||
public void SetDataRepositoryType<TDataProviderType>() where TDataProviderType : IAuthDataRepository =>
|
||||
AuthDataRepositoryType = typeof(TDataProviderType);
|
||||
|
||||
public Type? SessionStateProviderType { get; private set; }
|
||||
|
||||
public void SetSessionStateProviderType<TSessionStateProviderType>()
|
||||
where TSessionStateProviderType : ISessionStateProvider =>
|
||||
SessionStateProviderType = typeof(TSessionStateProviderType);
|
||||
}
|
||||
|
||||
public class BasedPasswordOptions
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class BasedUserOptions
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class BasedLockoutOptions
|
||||
{
|
||||
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public static class BasedAuthDefaults
|
||||
{
|
||||
public const string AuthenticationScheme = "DotBasedAuthentication";
|
||||
public const string StorageKey = "dotbased_session";
|
||||
|
||||
public static IComponentRenderMode InteractiveServerWithoutPrerender { get; } =
|
||||
new InteractiveServerRenderMode(prerender: false);
|
||||
}
|
@@ -1,40 +0,0 @@
|
||||
using System.Security.Claims;
|
||||
using DotBased.Logging;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
|
||||
using ILogger = DotBased.Logging.ILogger;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
// RevalidatingServerAuthenticationStateProvider
|
||||
// AuthenticationStateProvider
|
||||
// Handles roles
|
||||
public class BasedServerAuthenticationStateProvider : ServerAuthenticationStateProvider
|
||||
{
|
||||
public BasedServerAuthenticationStateProvider(BasedAuthConfiguration configuration, ProtectedLocalStorage localStorage, SecurityService securityService)
|
||||
{
|
||||
_config = configuration;
|
||||
_localStorage = localStorage;
|
||||
_securityService = securityService;
|
||||
_logger = LogService.RegisterLogger<BasedServerAuthenticationStateProvider>();
|
||||
}
|
||||
|
||||
private BasedAuthConfiguration _config;
|
||||
private readonly ProtectedLocalStorage _localStorage;
|
||||
private readonly SecurityService _securityService;
|
||||
private readonly ILogger _logger;
|
||||
private readonly AuthenticationState _anonState = new(new ClaimsPrincipal());
|
||||
|
||||
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
_logger.Debug("Getting authentication state...");
|
||||
var sessionIdResult = await _localStorage.GetAsync<string>(BasedAuthDefaults.StorageKey);
|
||||
if (!sessionIdResult.Success || sessionIdResult.Value == null)
|
||||
return _anonState;
|
||||
_logger.Debug("Found state [{State}], getting session from {Service}", sessionIdResult.Value, nameof(SecurityService));
|
||||
var stateResult = await _securityService.GetAuthenticationStateFromSessionAsync(sessionIdResult.Value);
|
||||
return stateResult is { Success: true, Value: not null } ? stateResult.Value : _anonState;
|
||||
}
|
||||
}
|
@@ -1,25 +0,0 @@
|
||||
using DotBased.ASP.Auth.Domains.Identity;
|
||||
|
||||
namespace DotBased.ASP.Auth.Domains.Auth;
|
||||
|
||||
public class AuthenticationStateModel
|
||||
{
|
||||
public AuthenticationStateModel(UserModel user)
|
||||
{
|
||||
UserId = user.Id;
|
||||
}
|
||||
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public string UserId { get; set; }
|
||||
public DateTime CreationDate { get; set; } = DateTime.Now;
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
if (obj is AuthenticationStateModel authStateModel)
|
||||
return authStateModel.Id == Id;
|
||||
return false;
|
||||
}
|
||||
// ReSharper disable once NonReadonlyMemberInGetHashCode
|
||||
public override int GetHashCode() => Id.GetHashCode();
|
||||
public override string ToString() => Id;
|
||||
}
|
@@ -1,8 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Domains.Auth;
|
||||
|
||||
public class PermissionModel
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string Permission { get; set; } = string.Empty;
|
||||
}
|
@@ -1,12 +0,0 @@
|
||||
using DotBased.Objects;
|
||||
|
||||
namespace DotBased.ASP.Auth.Domains.Auth;
|
||||
|
||||
public class RoleModel
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public List<PermissionModel> Permissions { get; set; } = [];
|
||||
public List<DbObjectAttribute<IConvertible>> Attributes { get; set; } = [];
|
||||
}
|
@@ -1,8 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Domains.Identity;
|
||||
|
||||
public class GroupItemModel
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
using DotBased.ASP.Auth.Domains.Auth;
|
||||
using DotBased.Objects;
|
||||
|
||||
namespace DotBased.ASP.Auth.Domains.Identity;
|
||||
|
||||
public class GroupModel
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public List<RoleModel> Roles { get; set; } = [];
|
||||
public List<DbObjectAttribute<IConvertible>> Attributes { get; set; } = [];
|
||||
}
|
@@ -1,10 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Domains.Identity;
|
||||
|
||||
public class UserItemModel
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string FamilyName { get; set; } = string.Empty;
|
||||
}
|
@@ -1,31 +0,0 @@
|
||||
using DotBased.ASP.Auth.Domains.Auth;
|
||||
using DotBased.Objects;
|
||||
|
||||
namespace DotBased.ASP.Auth.Domains.Identity;
|
||||
|
||||
public class UserModel
|
||||
{
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
public string PasswordHash { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string PhoneNumber { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string FamilyName { get; set; } = string.Empty;
|
||||
public DateTime Dob { get; set; }
|
||||
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public bool Enabled { get; set; }
|
||||
public bool EmailValidated { get; set; }
|
||||
public bool PhoneNumberConfirmed { get; set; }
|
||||
public bool Lockout { get; set; }
|
||||
public DateTime LockoutEnd { get; set; }
|
||||
public DateTime CreationStamp { get; set; }
|
||||
public DateTime SecurityStamp { get; set; }
|
||||
public DateTime ConcurrencyStamp { get; set; }
|
||||
public int AccessFailedCount { get; set; }
|
||||
public bool ExternalAuthentication { get; set; }
|
||||
|
||||
public List<GroupModel> Groups { get; set; } = [];
|
||||
public List<RoleModel> Roles { get; set; } = [];
|
||||
public List<DbObjectAttribute<IConvertible>> Attributes { get; set; } = [];
|
||||
}
|
@@ -1,8 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Domains;
|
||||
|
||||
public class LoginModel
|
||||
{
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
@@ -1,10 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Domains;
|
||||
|
||||
public class RegisterModel
|
||||
{
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string FamilyName { get; set; } = string.Empty;
|
||||
}
|
@@ -1,21 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DotBased\DotBased.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Models\Auth\States\" />
|
||||
<Folder Include="Models\Repositories\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
@@ -1,55 +0,0 @@
|
||||
using DotBased.ASP.Auth.Services;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public static class DotBasedAuthDependencyInjection
|
||||
{
|
||||
/// <summary>
|
||||
/// Use the DotBased authentication implementation
|
||||
/// </summary>
|
||||
/// <remarks>Use UseBasedServerAuth()!</remarks>
|
||||
/// <param name="services">Service collection</param>
|
||||
/// <param name="configurationAction">DotBased auth configuration</param>
|
||||
public static IServiceCollection AddBasedServerAuth(this IServiceCollection services, Action<BasedAuthConfiguration>? configurationAction = null)
|
||||
{
|
||||
var Configuration = new BasedAuthConfiguration();
|
||||
configurationAction?.Invoke(Configuration);
|
||||
|
||||
services.AddSingleton<BasedAuthConfiguration>(Configuration);
|
||||
if (Configuration.AuthDataRepositoryType == null)
|
||||
throw new ArgumentNullException(nameof(Configuration.AuthDataRepositoryType), $"No '{nameof(IAuthDataRepository)}' configured!");
|
||||
services.AddScoped(typeof(IAuthDataRepository), Configuration.AuthDataRepositoryType);
|
||||
|
||||
services.AddSingleton<AuthDataCache>();
|
||||
services.AddScoped<SecurityService>();
|
||||
|
||||
services.AddScoped<AuthenticationStateProvider, BasedServerAuthenticationStateProvider>();
|
||||
services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultScheme = BasedAuthDefaults.AuthenticationScheme;
|
||||
});/*.AddScheme<BasedAuthenticationHandlerOptions, BasedAuthenticationHandler>(BasedAuthDefaults.AuthenticationScheme, null);*/
|
||||
services.AddAuthorization();
|
||||
services.AddCascadingAuthenticationState();
|
||||
return services;
|
||||
}
|
||||
|
||||
public static WebApplication UseBasedServerAuth(this WebApplication app)
|
||||
{
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// Data
|
||||
var authConfig = app.Services.GetService<BasedAuthConfiguration>();
|
||||
if (authConfig == null)
|
||||
throw new NullReferenceException($"{nameof(BasedAuthConfiguration)} is null!");
|
||||
if (authConfig.AuthDataRepositoryType == null)
|
||||
throw new NullReferenceException($"{nameof(authConfig.AuthDataRepositoryType)} is null, cannot instantiate an instance of {nameof(IAuthDataRepository)}");
|
||||
var dataProvider = (IAuthDataRepository?)Activator.CreateInstance(authConfig.AuthDataRepositoryType);
|
||||
if (dataProvider != null) authConfig.SeedData?.Invoke(dataProvider);
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
@@ -1,22 +0,0 @@
|
||||
using DotBased.ASP.Auth.Domains.Auth;
|
||||
using DotBased.ASP.Auth.Domains.Identity;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public interface IAuthDataRepository
|
||||
{
|
||||
public Task<Result> CreateUserAsync(UserModel user);
|
||||
public Task<Result> UpdateUserAsync(UserModel user);
|
||||
public Task<Result> DeleteUserAsync(UserModel user);
|
||||
public Task<Result<UserModel>> GetUserAsync(string id, string email, string username);
|
||||
public Task<ListResult<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<Result> CreateGroupAsync(GroupModel group);
|
||||
public Task<Result> UpdateGroupAsync(GroupModel group);
|
||||
public Task<Result> DeleteGroupAsync(GroupModel group);
|
||||
public Task<Result<GroupModel>> GetGroupAsync(string id);
|
||||
public Task<ListResult<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<Result> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<Result> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<Result> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<Result<AuthenticationStateModel>> GetAuthenticationStateAsync(string id);
|
||||
}
|
@@ -1,8 +0,0 @@
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public interface ISessionStateProvider
|
||||
{
|
||||
public const string SessionStateName = "BasedServerSession";
|
||||
public Task<Result<string>> GetSessionStateAsync();
|
||||
public Task<Result> SetSessionStateAsync(string state);
|
||||
}
|
@@ -1,107 +0,0 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using DotBased.ASP.Auth.Domains.Auth;
|
||||
using DotBased.ASP.Auth.Domains.Identity;
|
||||
using DotBased.Extensions;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
/// <summary>
|
||||
/// In memory data provider, for testing only!
|
||||
/// </summary>
|
||||
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
|
||||
public class MemoryAuthDataRepository : IAuthDataRepository
|
||||
{
|
||||
public async Task<Result> CreateUserAsync(UserModel user)
|
||||
{
|
||||
if (MemoryData.users.Any(x => x.Id == user.Id || x.Email == user.Email))
|
||||
return Result.Failed("User already exists.");
|
||||
MemoryData.users.Add(user);
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public async Task<Result> UpdateUserAsync(UserModel user)
|
||||
{
|
||||
if (MemoryData.users.All(x => x.Id != user.Id))
|
||||
return Result.Failed("User does not exist!");
|
||||
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public Task<Result> DeleteUserAsync(UserModel user)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Result<UserModel>> GetUserAsync(string id, string email, string username)
|
||||
{
|
||||
UserModel? userModel = null;
|
||||
if (!id.IsNullOrEmpty())
|
||||
userModel = MemoryData.users.FirstOrDefault(u => u.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||
if (!email.IsNullOrEmpty())
|
||||
userModel = MemoryData.users.FirstOrDefault(u => u.Email.Equals(email, StringComparison.OrdinalIgnoreCase));
|
||||
if (!username.IsNullOrEmpty())
|
||||
userModel = MemoryData.users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.OrdinalIgnoreCase));
|
||||
return userModel != null ? Result<UserModel>.Ok(userModel) : Result<UserModel>.Failed("No user found!");
|
||||
}
|
||||
|
||||
public Task<ListResult<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "")
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result> CreateGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result> UpdateGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result> DeleteGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result<GroupModel>> GetGroupAsync(string id)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ListResult<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "")
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Result> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
if (MemoryData.AuthenticationStates.Contains(authenticationState)) return Result.Failed("Item already exists!");
|
||||
MemoryData.AuthenticationStates.Add(authenticationState);
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public Task<Result> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
MemoryData.AuthenticationStates.Remove(authenticationState);
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public async Task<Result<AuthenticationStateModel>> GetAuthenticationStateAsync(string id)
|
||||
{
|
||||
var item = MemoryData.AuthenticationStates.FirstOrDefault(x => x.Id == id);
|
||||
if (item == null) return Result<AuthenticationStateModel>.Failed("Could not get the session state!");
|
||||
return Result<AuthenticationStateModel>.Ok(item);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class MemoryData
|
||||
{
|
||||
public static readonly List<UserModel> users = [];
|
||||
public static readonly List<GroupModel> Groups = [];
|
||||
public static readonly List<AuthenticationStateModel> AuthenticationStates = [];
|
||||
}
|
@@ -1,11 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class AuthConfiguration
|
||||
{
|
||||
public CacheConfiguration Cache { get; set; } = new();
|
||||
public LockoutConfiguration Lockout { get; set; } = new();
|
||||
public PasswordConfiguration Password { get; set; } = new();
|
||||
public ProviderConfiguration Provider { get; set; } = new();
|
||||
public RepositoryConfiguration Repository { get; set; } = new();
|
||||
public UserConfiguration User { get; set; } = new();
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class CacheConfiguration
|
||||
{
|
||||
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class LockoutConfiguration
|
||||
{
|
||||
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class PasswordConfiguration
|
||||
{
|
||||
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class ProviderConfiguration
|
||||
{
|
||||
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class RepositoryConfiguration
|
||||
{
|
||||
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Models.Configuration;
|
||||
|
||||
public class UserConfiguration
|
||||
{
|
||||
|
||||
}
|
@@ -1,9 +0,0 @@
|
||||
namespace DotBased.ASP.Auth.Managers;
|
||||
|
||||
public class SecurityManager
|
||||
{
|
||||
public SecurityManager()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@@ -1,137 +0,0 @@
|
||||
using System.Security.Claims;
|
||||
using DotBased.ASP.Auth.Domains;
|
||||
using DotBased.ASP.Auth.Domains.Auth;
|
||||
using DotBased.ASP.Auth.Domains.Identity;
|
||||
using DotBased.Extensions;
|
||||
using DotBased.Logging;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
|
||||
|
||||
namespace DotBased.ASP.Auth;
|
||||
|
||||
public class SecurityService
|
||||
{
|
||||
public SecurityService(IAuthDataRepository authDataRepository, AuthDataCache dataCache, ProtectedLocalStorage localStorage)
|
||||
{
|
||||
_authDataRepository = authDataRepository;
|
||||
_dataCache = dataCache;
|
||||
_localStorage = localStorage;
|
||||
_logger = LogService.RegisterLogger<SecurityService>();
|
||||
}
|
||||
|
||||
private readonly IAuthDataRepository _authDataRepository;
|
||||
private readonly AuthDataCache _dataCache;
|
||||
private readonly ProtectedLocalStorage _localStorage;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public async Task<Result<AuthenticationState>> GetAuthenticationStateFromSessionAsync(string id)
|
||||
{
|
||||
if (id.IsNullOrEmpty())
|
||||
return Result<AuthenticationState>.Failed("No valid id!");
|
||||
AuthenticationStateModel? authStateModel = null;
|
||||
var stateCache = _dataCache.RequestSessionState(id);
|
||||
if (!stateCache.Success || stateCache.Value == null)
|
||||
{
|
||||
var stateResult = await _authDataRepository.GetAuthenticationStateAsync(id);
|
||||
if (stateResult is { Success: true, Value: not null })
|
||||
{
|
||||
authStateModel = stateResult.Value;
|
||||
_dataCache.CacheSessionState(authStateModel);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (stateCache.Value.Item2 != null)
|
||||
return Result<AuthenticationState>.Ok(stateCache.Value.Item2);
|
||||
authStateModel = stateCache.Value.Item1;
|
||||
}
|
||||
|
||||
if (authStateModel == null)
|
||||
return Result<AuthenticationState>.Failed("Failed to get auth state!");
|
||||
|
||||
var userResult = await _authDataRepository.GetUserAsync(authStateModel.UserId, string.Empty, string.Empty);
|
||||
if (userResult is not { Success: true, Value: not null })
|
||||
return Result<AuthenticationState>.Failed("Failed to get user from state!");
|
||||
var claims = new List<Claim>()
|
||||
{
|
||||
new(ClaimTypes.Sid, userResult.Value.Id),
|
||||
new(ClaimTypes.Name, userResult.Value.Name),
|
||||
new(ClaimTypes.NameIdentifier, userResult.Value.UserName),
|
||||
new(ClaimTypes.Surname, userResult.Value.FamilyName),
|
||||
new(ClaimTypes.Email, userResult.Value.Email)
|
||||
};
|
||||
claims.AddRange(userResult.Value.Groups.Select(group => new Claim(ClaimTypes.GroupSid, group.Id)));
|
||||
claims.AddRange(userResult.Value.Roles.Select(role => new Claim(ClaimTypes.Role, role.Name)));
|
||||
claims.AddRange(userResult.Value.Groups.Select(g => g.Roles).SelectMany(gRolesList => gRolesList, (_, role) => new Claim(ClaimTypes.Role, role.Name)));
|
||||
var claimsIdentity = new ClaimsIdentity(claims, BasedAuthDefaults.AuthenticationScheme);
|
||||
var authState = new AuthenticationState(new ClaimsPrincipal(claimsIdentity));
|
||||
_dataCache.CacheSessionState(authStateModel, authState);
|
||||
return Result<AuthenticationState>.Ok(authState);
|
||||
}
|
||||
|
||||
public async Task<Result<AuthenticationStateModel>> LoginAsync(LoginModel login)
|
||||
{
|
||||
try
|
||||
{
|
||||
UserModel? user = null;
|
||||
Result<UserModel> usrResult;
|
||||
if (!login.UserName.IsNullOrEmpty())
|
||||
{
|
||||
usrResult = await _authDataRepository.GetUserAsync(string.Empty, string.Empty, login.UserName);
|
||||
if (usrResult is { Success: true, Value: not null })
|
||||
user = usrResult.Value;
|
||||
}
|
||||
else if (!login.Email.IsNullOrEmpty())
|
||||
{
|
||||
usrResult = await _authDataRepository.GetUserAsync(string.Empty, login.Email, string.Empty);
|
||||
if (usrResult is { Success: true, Value: not null })
|
||||
user = usrResult.Value;
|
||||
}
|
||||
else
|
||||
return Result<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
|
||||
|
||||
if (user == null || !usrResult.Success)
|
||||
return Result<AuthenticationStateModel>.Failed("No user found!");
|
||||
|
||||
if (user.PasswordHash != login.Password) //TODO: Hash password and compare
|
||||
return Result<AuthenticationStateModel>.Failed("Login failed, invalid password.");
|
||||
var state = new AuthenticationStateModel(user);
|
||||
var authResult = await _authDataRepository.CreateAuthenticationStateAsync(state);
|
||||
if (!authResult.Success)
|
||||
return Result<AuthenticationStateModel>.Failed("Failed to store session to database!");
|
||||
_dataCache.CacheSessionState(state);
|
||||
await _localStorage.SetAsync(BasedAuthDefaults.StorageKey, state.Id);
|
||||
return Result<AuthenticationStateModel>.Ok(state);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Failed to login!");
|
||||
return Result<AuthenticationStateModel>.Failed("Login failed, exception thrown!");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> LogoutAsync(string state)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (state.IsNullOrEmpty())
|
||||
return Result.Failed($"Argument {nameof(state)} is empty!");
|
||||
|
||||
var stateResult = await _authDataRepository.GetAuthenticationStateAsync(state);
|
||||
if (!stateResult.Success || stateResult.Value == null)
|
||||
return stateResult;
|
||||
var authState = stateResult.Value;
|
||||
|
||||
_dataCache.PurgeSessionState(state);
|
||||
var updatedStateResult = await _authDataRepository.DeleteAuthenticationStateAsync(authState);
|
||||
if (updatedStateResult.Success) return updatedStateResult;
|
||||
_logger.Warning(updatedStateResult.Message);
|
||||
return updatedStateResult;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Failed to logout!");
|
||||
return Result.Failed("Failed to logout, exception thrown!");
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,11 +0,0 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace DotBased.AspNet.Auth;
|
||||
|
||||
public static class BasedAuthExtensions
|
||||
{
|
||||
public static IServiceCollection AddBasedAuthentication(this IServiceCollection services)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
}
|
@@ -1,31 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Models\" />
|
||||
<Folder Include="Repositories\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DotBased\DotBased.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.AspNetCore.Authentication">
|
||||
<HintPath>..\..\..\..\..\usr\lib64\dotnet\shared\Microsoft.AspNetCore.App\8.0.11\Microsoft.AspNetCore.Authentication.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions">
|
||||
<HintPath>..\..\..\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\8.0.2\lib\net8.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="8.0.11" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@@ -4,13 +4,13 @@ namespace DotBased.Logging.MEL;
|
||||
|
||||
public class BasedLogger : Microsoft.Extensions.Logging.ILogger
|
||||
{
|
||||
private const string _messageTemplateKey = "{OriginalFormat}";
|
||||
private const string MessageTemplateKey = "{OriginalFormat}";
|
||||
public BasedLogger(ILogger logger)
|
||||
{
|
||||
basedLogger = logger;
|
||||
_basedLogger = logger;
|
||||
}
|
||||
|
||||
private readonly ILogger basedLogger;
|
||||
private readonly ILogger _basedLogger;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
@@ -18,7 +18,7 @@ public class BasedLogger : Microsoft.Extensions.Logging.ILogger
|
||||
return;
|
||||
var severity = ConvertLogLevelToSeverity(logLevel);
|
||||
var capsule = ConstructCapsule(severity, eventId, state, exception, formatter);
|
||||
basedLogger.Log(capsule);
|
||||
_basedLogger.Log(capsule);
|
||||
}
|
||||
|
||||
private LogCapsule ConstructCapsule<TState>(LogSeverity severity, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
@@ -29,7 +29,7 @@ public class BasedLogger : Microsoft.Extensions.Logging.ILogger
|
||||
{
|
||||
foreach (var prop in stateEnum)
|
||||
{
|
||||
if (prop is { Key: _messageTemplateKey, Value: string propValueString })
|
||||
if (prop is { Key: MessageTemplateKey, Value: string propValueString })
|
||||
{
|
||||
msgTemplate = propValueString;
|
||||
continue;
|
||||
@@ -37,16 +37,8 @@ public class BasedLogger : Microsoft.Extensions.Logging.ILogger
|
||||
templateParams.Add(prop.Value);
|
||||
}
|
||||
}
|
||||
|
||||
return new LogCapsule()
|
||||
{
|
||||
Exception = exception,
|
||||
Message = msgTemplate,
|
||||
Parameters = templateParams.ToArray(),
|
||||
Severity = severity,
|
||||
TimeStamp = DateTime.Now,
|
||||
Logger = basedLogger as LoggerBase ?? throw new NullReferenceException(nameof(basedLogger))
|
||||
};
|
||||
|
||||
return new LogCapsule(_basedLogger as LoggerBase ?? throw new NullReferenceException(nameof(_basedLogger)), severity, msgTemplate, exception, templateParams.ToArray(), DateTime.Now);
|
||||
}
|
||||
|
||||
private LogSeverity ConvertLogLevelToSeverity(LogLevel level)
|
||||
@@ -66,5 +58,5 @@ public class BasedLogger : Microsoft.Extensions.Logging.ILogger
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default;
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
}
|
@@ -1,10 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>12</LangVersion>
|
||||
<Authors>NetzByte</Authors>
|
||||
<PackageProjectUrl>https://git.netzbyte.com/max/DotBased</PackageProjectUrl>
|
||||
<RepositoryUrl>https://git.netzbyte.com/max/DotBased</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@@ -1,9 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>default</LangVersion>
|
||||
<Authors>NetzByte</Authors>
|
||||
<PackageProjectUrl>https://git.netzbyte.com/max/DotBased</PackageProjectUrl>
|
||||
<RepositoryUrl>https://git.netzbyte.com/max/DotBased</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
17
DotBased.sln
17
DotBased.sln
@@ -8,8 +8,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.Logging.Serilog",
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{2156FB93-C252-4B33-8A0C-73C82FABB163}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.ASP.Auth", "DotBased.ASP.Auth\DotBased.ASP.Auth.csproj", "{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.Logging.MEL", "DotBased.Logging.MEL\DotBased.Logging.MEL.csproj", "{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{DBDB4538-85D4-45AC-9E0A-A684467AEABA}"
|
||||
@@ -18,10 +16,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestWebApi", "TestWebApi\Te
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blazor.Wasm", "Blazor.Wasm\Blazor.Wasm.csproj", "{AC8343A5-7953-4E1D-A926-406BE4D7E819}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNet", "AspNet", "{624E7B11-8A18-46E5-AB1F-6AF6097F9D4D}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.AspNet.Auth", "DotBased.AspNet.Auth\DotBased.AspNet.Auth.csproj", "{6F407D81-DFAC-4936-ACDD-D75E9FDE2E7B}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -40,10 +34,6 @@ Global
|
||||
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
@@ -56,18 +46,11 @@ Global
|
||||
{AC8343A5-7953-4E1D-A926-406BE4D7E819}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AC8343A5-7953-4E1D-A926-406BE4D7E819}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AC8343A5-7953-4E1D-A926-406BE4D7E819}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{6F407D81-DFAC-4936-ACDD-D75E9FDE2E7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6F407D81-DFAC-4936-ACDD-D75E9FDE2E7B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6F407D81-DFAC-4936-ACDD-D75E9FDE2E7B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6F407D81-DFAC-4936-ACDD-D75E9FDE2E7B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
|
||||
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
|
||||
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
|
||||
{BADA4BAF-142B-47A8-95FC-B25E1D3D0020} = {DBDB4538-85D4-45AC-9E0A-A684467AEABA}
|
||||
{AC8343A5-7953-4E1D-A926-406BE4D7E819} = {DBDB4538-85D4-45AC-9E0A-A684467AEABA}
|
||||
{624E7B11-8A18-46E5-AB1F-6AF6097F9D4D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
|
||||
{6F407D81-DFAC-4936-ACDD-D75E9FDE2E7B} = {624E7B11-8A18-46E5-AB1F-6AF6097F9D4D}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
BIN
DotBased/DotBased-ICO.png
Normal file
BIN
DotBased/DotBased-ICO.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 73 KiB |
@@ -4,7 +4,18 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>default</LangVersion>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Authors>NetzByte</Authors>
|
||||
<PackageIcon>DotBased-ICO.png</PackageIcon>
|
||||
<PackageProjectUrl>https://git.netzbyte.com/max/DotBased</PackageProjectUrl>
|
||||
<RepositoryUrl>https://git.netzbyte.com/max/DotBased</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="DotBased-ICO.png">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath></PackagePath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@@ -3,21 +3,4 @@ namespace DotBased.Logging;
|
||||
/// <summary>
|
||||
/// This will contain all the log event information that the log adapter will receive.
|
||||
/// </summary>
|
||||
public class LogCapsule
|
||||
{
|
||||
/// <summary>
|
||||
/// The log serverty this log event is being logged.
|
||||
/// </summary>
|
||||
public LogSeverity Severity { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
public Exception? Exception { get; set; }
|
||||
public object?[]? Parameters { get; set; }
|
||||
/// <summary>
|
||||
/// Time stamp on when this event happend
|
||||
/// </summary>
|
||||
public DateTime TimeStamp { get; set; }
|
||||
/// <summary>
|
||||
/// The logger that generated this capsule
|
||||
/// </summary>
|
||||
public LoggerBase Logger { get; set; }
|
||||
}
|
||||
public record LogCapsule(LoggerBase Logger, LogSeverity Severity, string Message, Exception? Exception, object?[]? Parameters, DateTime TimeStamp);
|
@@ -7,88 +7,37 @@ public class Logger(LoggerInformation loggerInformation, string name) : LoggerBa
|
||||
{
|
||||
public override void Verbose(string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Verbose,
|
||||
TimeStamp = DateTime.Now
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Verbose, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override void Trace(string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Trace,
|
||||
TimeStamp = DateTime.Now
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Trace, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override void Debug(string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Debug,
|
||||
TimeStamp = DateTime.Now
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Debug, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override void Information(string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Info,
|
||||
TimeStamp = DateTime.Now
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Info, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override void Warning(string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Warning,
|
||||
TimeStamp = DateTime.Now
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Warning, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override void Error(Exception exception, string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Error,
|
||||
TimeStamp = DateTime.Now,
|
||||
Exception = exception
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Error, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override void Fatal(Exception exception, string message, params object?[]? parameters)
|
||||
{
|
||||
Log(new LogCapsule()
|
||||
{
|
||||
Logger = this,
|
||||
Message = message,
|
||||
Parameters = parameters,
|
||||
Severity = LogSeverity.Fatal,
|
||||
TimeStamp = DateTime.Now,
|
||||
Exception = exception
|
||||
});
|
||||
Log(new LogCapsule(this, LogSeverity.Fatal, message, null, parameters, DateTime.Now));
|
||||
}
|
||||
|
||||
public override int GetHashCode() => HashCode.Combine(LoggerInformation.TypeFullName, LoggerInformation.AssemblyFullname);
|
||||
|
93
DotBased/Monads/Result.cs
Normal file
93
DotBased/Monads/Result.cs
Normal file
@@ -0,0 +1,93 @@
|
||||
namespace DotBased.Monads;
|
||||
|
||||
public class Result
|
||||
{
|
||||
protected Result()
|
||||
{
|
||||
IsSuccess = true;
|
||||
}
|
||||
|
||||
protected Result(Exception exception)
|
||||
{
|
||||
IsSuccess = false;
|
||||
Error = ResultError.Error(exception);
|
||||
}
|
||||
|
||||
protected Result(ResultError error)
|
||||
{
|
||||
IsSuccess = false;
|
||||
Error = error;
|
||||
}
|
||||
|
||||
public bool IsSuccess { get; }
|
||||
public ResultError? Error { get; set; }
|
||||
|
||||
public static implicit operator Result(Exception exception) => new(exception);
|
||||
public static implicit operator Result(ResultError error) => new(error);
|
||||
|
||||
public static Result Success() => new();
|
||||
public static Result Fail(ResultError error) => new(error);
|
||||
public static Result Exception(Exception exception) => new(exception);
|
||||
|
||||
|
||||
public TMatch Match<TMatch>(Func<TMatch> success, Func<ResultError, TMatch> failure) => IsSuccess ? success() : failure(Error!);
|
||||
|
||||
public void Match(Action success, Action<ResultError> failure)
|
||||
{
|
||||
if (IsSuccess)
|
||||
{
|
||||
success();
|
||||
}
|
||||
else
|
||||
{
|
||||
failure(Error!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Result<TResult> : Result
|
||||
{
|
||||
protected Result(TResult result)
|
||||
{
|
||||
_result = result;
|
||||
}
|
||||
|
||||
protected Result(Exception exception) : base(exception)
|
||||
{
|
||||
_result = default;
|
||||
}
|
||||
|
||||
protected Result(ResultError error) : base(error)
|
||||
{
|
||||
_result = default;
|
||||
}
|
||||
|
||||
private readonly TResult? _result;
|
||||
public TResult Value => IsSuccess ? _result! : throw new InvalidOperationException("Result is invalid");
|
||||
|
||||
public static implicit operator Result<TResult>(TResult result) => new(result);
|
||||
public static implicit operator Result<TResult>(Exception exception) => new(exception);
|
||||
public static implicit operator Result<TResult>(ResultError error) => new(error);
|
||||
|
||||
public static Result<TResult> Success(TResult result) => new(result);
|
||||
public new static Result<TResult> Fail(ResultError error) => new(error);
|
||||
public new static Result<TResult> Exception(Exception exception) => new(exception);
|
||||
|
||||
public TMatch Match<TMatch>(Func<TResult, TMatch> success, Func<ResultError, TMatch> failure) =>
|
||||
IsSuccess && Value != null ? success(Value) : failure(Error ?? ResultError.Fail("No error and value is null!"));
|
||||
}
|
||||
|
||||
public class ResultError
|
||||
{
|
||||
private ResultError(string description, Exception? exception)
|
||||
{
|
||||
Description = description;
|
||||
Exception = exception;
|
||||
}
|
||||
|
||||
public string Description { get; }
|
||||
public Exception? Exception { get; }
|
||||
|
||||
public static ResultError Fail(string description) => new(description, null);
|
||||
public static ResultError Error(Exception exception, string description = "") => new(description, exception);
|
||||
}
|
@@ -1,77 +0,0 @@
|
||||
namespace DotBased;
|
||||
|
||||
/// <summary>
|
||||
/// Simple result class for returning a result state or a message and an exception.
|
||||
/// </summary>
|
||||
public class Result
|
||||
{
|
||||
public Result(bool success, string message, Exception? exception)
|
||||
{
|
||||
Success = success;
|
||||
Message = message;
|
||||
Exception = exception;
|
||||
}
|
||||
|
||||
public Result(Result bObj)
|
||||
{
|
||||
Success = bObj.Success;
|
||||
Message = bObj.Message;
|
||||
Exception = bObj.Exception;
|
||||
}
|
||||
|
||||
public bool Success { get; set; }
|
||||
public string Message { get; set; }
|
||||
public Exception? Exception { get; set; }
|
||||
|
||||
public static Result Ok() => new(true, string.Empty, null);
|
||||
public static Result Failed(string message, Exception? exception = null) => new(false, message, exception);
|
||||
}
|
||||
|
||||
public class Result<TValue> : Result
|
||||
{
|
||||
public Result(bool success, string message, TValue? value, Exception? exception) : base(success, message, exception)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
public Result(Result bObj) : base(bObj)
|
||||
{
|
||||
|
||||
}
|
||||
public TValue? Value { get; set; }
|
||||
|
||||
public static Result<TValue> Ok(TValue value) => new(true, string.Empty, value, null);
|
||||
|
||||
public new static Result<TValue> Failed(string message, Exception? exception = null) =>
|
||||
new(false, message, default, exception);
|
||||
}
|
||||
|
||||
public class ListResult<TItem> : Result
|
||||
{
|
||||
public ListResult(bool success, string message, int totalCount, IEnumerable<TItem>? items, Exception? exception) : base(success, message, exception)
|
||||
{
|
||||
Items = items != null ? new List<TItem>(items) : new List<TItem>();
|
||||
TotalCount = totalCount;
|
||||
}
|
||||
|
||||
public ListResult(Result bObj) : base(bObj)
|
||||
{
|
||||
Items = new List<TItem>();
|
||||
}
|
||||
|
||||
public readonly IReadOnlyList<TItem> Items;
|
||||
/// <summary>
|
||||
/// The amount of items that this result contains.
|
||||
/// </summary>
|
||||
public int Count => Items.Count;
|
||||
|
||||
/// <summary>
|
||||
/// The total amount of item that is available.
|
||||
/// </summary>
|
||||
public int TotalCount { get; }
|
||||
|
||||
public static ListResult<TItem> Ok(IEnumerable<TItem> items, int totalCount = -1) =>
|
||||
new(true, string.Empty, totalCount, items, null);
|
||||
|
||||
public new static ListResult<TItem> Failed(string message, Exception? exception = null) =>
|
||||
new(false, message, -1, null, exception);
|
||||
}
|
@@ -1,4 +1,5 @@
|
||||
using System.Security.Cryptography;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.Utilities;
|
||||
|
||||
@@ -12,7 +13,7 @@ public static class Cryptography
|
||||
var outputStream = new StringWriter();
|
||||
var parameters = csp.ExportParameters(false);
|
||||
if (parameters.Exponent == null || parameters.Modulus == null)
|
||||
return Result<string>.Failed("RSAParameters are empty!");
|
||||
return ResultError.Fail("RSAParameters are empty!");
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
var writer = new BinaryWriter(stream);
|
||||
@@ -23,7 +24,7 @@ public static class Cryptography
|
||||
innerWriter.Write((byte)0x30); // SEQUENCE
|
||||
EncodeLength(innerWriter, 13);
|
||||
innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER
|
||||
byte[] rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
|
||||
var rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
|
||||
EncodeLength(innerWriter, rsaEncryptionOid.Length);
|
||||
innerWriter.Write(rsaEncryptionOid);
|
||||
innerWriter.Write((byte)0x05); // NULL
|
||||
@@ -44,20 +45,20 @@ public static class Cryptography
|
||||
bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength);
|
||||
}
|
||||
|
||||
int bitStringLength = (int)bitStringStream.Length;
|
||||
var bitStringLength = (int)bitStringStream.Length;
|
||||
EncodeLength(innerWriter, bitStringLength);
|
||||
innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength);
|
||||
}
|
||||
|
||||
int length = (int)innerStream.Length;
|
||||
var length = (int)innerStream.Length;
|
||||
EncodeLength(writer, length);
|
||||
writer.Write(innerStream.GetBuffer(), 0, length);
|
||||
}
|
||||
|
||||
char[] base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
|
||||
var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
|
||||
// WriteLine terminates with \r\n, we want only \n
|
||||
outputStream.Write("-----BEGIN PUBLIC KEY-----\n");
|
||||
for (int i = 0; i < base64.Length; i += 64)
|
||||
for (var i = 0; i < base64.Length; i += 64)
|
||||
{
|
||||
outputStream.Write(base64, i, Math.Min(64, base64.Length - i));
|
||||
outputStream.Write("\n");
|
||||
@@ -66,7 +67,7 @@ public static class Cryptography
|
||||
outputStream.Write("-----END PUBLIC KEY-----");
|
||||
}
|
||||
|
||||
return Result<string>.Ok(outputStream.ToString());
|
||||
return outputStream.ToString();
|
||||
}
|
||||
|
||||
private static void EncodeLength(BinaryWriter stream, int length)
|
||||
@@ -82,15 +83,15 @@ public static class Cryptography
|
||||
default:
|
||||
{
|
||||
// Long form
|
||||
int temp = length;
|
||||
int bytesRequired = 0;
|
||||
var temp = length;
|
||||
var bytesRequired = 0;
|
||||
while (temp > 0)
|
||||
{
|
||||
temp >>= 8;
|
||||
bytesRequired++;
|
||||
}
|
||||
stream.Write((byte)(bytesRequired | 0x80));
|
||||
for (int i = bytesRequired - 1; i >= 0; i--)
|
||||
for (var i = bytesRequired - 1; i >= 0; i--)
|
||||
{
|
||||
stream.Write((byte)(length >> (8 * i) & 0xff));
|
||||
}
|
||||
@@ -102,7 +103,7 @@ public static class Cryptography
|
||||
private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true)
|
||||
{
|
||||
stream.Write((byte)0x02); // INTEGER
|
||||
int prefixZeros = value.TakeWhile(t => t == 0).Count();
|
||||
var prefixZeros = value.TakeWhile(t => t == 0).Count();
|
||||
if (value.Length - prefixZeros == 0)
|
||||
{
|
||||
EncodeLength(stream, 1);
|
||||
@@ -120,7 +121,7 @@ public static class Cryptography
|
||||
{
|
||||
EncodeLength(stream, value.Length - prefixZeros);
|
||||
}
|
||||
for (int i = prefixZeros; i < value.Length; i++)
|
||||
for (var i = prefixZeros; i < value.Length; i++)
|
||||
{
|
||||
stream.Write(value[i]);
|
||||
}
|
||||
|
@@ -5,9 +5,9 @@ namespace DotBased.Utilities;
|
||||
|
||||
public static class Culture
|
||||
{
|
||||
private static List<CultureInfo> _sysCultures = new List<CultureInfo>();
|
||||
private static Dictionary<string, RegionInfo> _regions = new Dictionary<string, RegionInfo>();
|
||||
private static readonly ILogger _logger = LogService.RegisterLogger(typeof(Culture));
|
||||
private static List<CultureInfo> _sysCultures = [];
|
||||
private static readonly Dictionary<string, RegionInfo> Regions = new();
|
||||
private static readonly ILogger Logger = LogService.RegisterLogger(typeof(Culture));
|
||||
|
||||
/// <summary>
|
||||
/// Get all system known cultures.
|
||||
@@ -16,7 +16,7 @@ public static class Culture
|
||||
/// <returns>The list with <see cref="CultureInfo"/>'s the system knows</returns>
|
||||
public static IEnumerable<CultureInfo> GetSystemCultures()
|
||||
{
|
||||
_logger.Debug("Getting system cultures...");
|
||||
Logger.Debug("Getting system cultures...");
|
||||
if (_sysCultures.Count == 0)
|
||||
_sysCultures = CultureInfo.GetCultures(CultureTypes.AllCultures).ToList();
|
||||
return _sysCultures;
|
||||
@@ -29,16 +29,16 @@ public static class Culture
|
||||
/// <returns>A list with regions from the system</returns>
|
||||
public static Dictionary<string, RegionInfo> GetRegions()
|
||||
{
|
||||
if (_regions.Count == 0)
|
||||
if (Regions.Count == 0)
|
||||
{
|
||||
var cultureInfos = GetSystemCultures().Where(cul => !cul.IsNeutralCulture).Where(cul => cul.LCID != 0x7F);
|
||||
foreach (var culture in cultureInfos)
|
||||
{
|
||||
var region = new RegionInfo(culture.Name);
|
||||
_regions.Add(culture.Name, region);
|
||||
Regions.Add(culture.Name, region);
|
||||
}
|
||||
}
|
||||
return _regions;
|
||||
return Regions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -52,7 +52,7 @@ public static class Culture
|
||||
_sysCultures.Clear();
|
||||
break;
|
||||
case CacheType.Region:
|
||||
_regions.Clear();
|
||||
Regions.Clear();
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(type), type, null);
|
||||
|
@@ -12,29 +12,30 @@ public static class Suffix
|
||||
/// Converts the bytes to the memory suffix.
|
||||
/// </summary>
|
||||
/// <param name="bytes">The bytes to convert</param>
|
||||
/// <param name="decimalPlaces">How manay decimal places will be placed</param>
|
||||
/// <param name="decimalPlaces">How manny decimal places will be placed</param>
|
||||
/// <returns>The suffixed bytes in the correct format</returns>
|
||||
public static string BytesToSizeSuffix(long bytes, int decimalPlaces = 1)
|
||||
{
|
||||
if (decimalPlaces < 0)
|
||||
decimalPlaces = 1;
|
||||
switch (bytes)
|
||||
if (decimalPlaces < 0) decimalPlaces = 1;
|
||||
|
||||
if (bytes == 0)
|
||||
return $"{0.ToString($"N{decimalPlaces}")} bytes";
|
||||
|
||||
var negative = bytes < 0;
|
||||
var absBytes = (ulong)(negative ? -bytes : bytes);
|
||||
|
||||
var mag = (int)Math.Log(absBytes, 1024);
|
||||
var adjustedSize = absBytes / Math.Pow(1024, mag);
|
||||
|
||||
if (Math.Round(adjustedSize, decimalPlaces) >= 1000 && mag < SizeSuffixes.Length - 1)
|
||||
{
|
||||
case < 0:
|
||||
return "-" + BytesToSizeSuffix(-bytes, decimalPlaces);
|
||||
case 0:
|
||||
return string.Format("{0:n" + decimalPlaces + "} bytes", 0);
|
||||
}
|
||||
|
||||
int mag = (int)Math.Log(bytes, 1024);
|
||||
|
||||
decimal adjustedSize = (decimal)bytes / (1L << (mag * 10));
|
||||
|
||||
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
|
||||
{
|
||||
mag += 1;
|
||||
mag++;
|
||||
adjustedSize /= 1024;
|
||||
}
|
||||
return string.Format("{0:n" + decimalPlaces + "} {1}", adjustedSize, SizeSuffixes[mag]);
|
||||
|
||||
var format = $"N{decimalPlaces}";
|
||||
var result = $"{adjustedSize.ToString(format)} {SizeSuffixes[mag]}";
|
||||
|
||||
return negative ? "-" + result : result;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user