Compare commits

53 Commits

Author SHA1 Message Date
max
e8739defad Merge branch 'main' into feature/base_authority 2025-08-02 16:41:45 +02:00
max
3a9c499aab [CHANGE] Remove old ASP auth project 2025-08-02 16:27:16 +02:00
max
333cf66cb4 [WIP] 2025-05-18 22:36:12 +02:00
max
217c55df00 [WIP] 2025-05-18 18:03:40 +02:00
max
b3763fb795 [WIP] Start impl auth handler 2025-05-18 01:01:07 +02:00
max
c225576c44 [WIP] Update AuthenticationService info 2025-05-18 00:35:04 +02:00
max
46dbd8c6f5 [WIP] 2025-05-05 16:00:18 +02:00
max
05b95c6050 [WIP] Working schemes 2025-05-02 23:50:09 +02:00
max
edf8891ddc [WIP] Reworked auth schemes and added framework reference to Microsoft.AspNetCore.App 2025-05-02 23:27:41 +02:00
max
723c654d70 [REMOVE] Removed unused project 2025-05-02 20:49:08 +02:00
max
e22b7790dd [WIP] Reworking authentication service 2025-04-28 17:11:46 +02:00
max
d69359e937 [WIP] 2025-04-27 23:12:02 +02:00
max
e6d7578d49 [WIP] 2025-04-27 17:28:51 +02:00
max
46cf20893b [CHANGE] Reworking auth schemes & services, handlers, etc. 2025-04-27 17:23:14 +02:00
max
8e72d123fd [CHANGE] Small updates repositories 2025-04-19 23:46:29 +02:00
max
095b66f6f3 [CHANGE] Removed old result monad 2025-04-12 14:26:47 +02:00
max
7ed219d08a [CHANGE] Moved repositories to new monads 2025-04-12 14:20:40 +02:00
max
ec7e260511 [REMOVE] Remove old AuthorityResult 2025-04-11 21:07:45 +02:00
max
ba0de46068 [REFACTOR] Refactored UserRepository to use new monads 2025-04-11 21:07:08 +02:00
max
21fe08c04f [CHANGE] Updated ValidationResult to monad version 2025-04-11 20:12:53 +02:00
max
f0cb7218ac [CHANGE] Updated role repository tasks 2025-04-11 19:57:20 +02:00
max
0a5950cfa2 [CHANGE] Reworking Result monads 2025-04-07 14:59:37 +02:00
max
bb010b0cea [ADD] Add updated monads 2025-04-07 00:11:00 +02:00
max
d8b08a763e [CHANGE] Adding functionality to manager 2025-04-06 21:34:40 +02:00
max
d6c0ad1138 [CHANGE] Search all roles from users/groups 2025-02-24 16:52:57 +01:00
max
e65b937128 [CHANGE] Managers 2025-02-24 16:35:23 +01:00
max
79d8fcfb8d [CHANGE] Update errors to IReadOnlyList 2025-02-24 16:07:56 +01:00
max
c6e11efdf2 [ADD] Added repository implementations 2025-02-17 19:58:50 +01:00
max
13b70c22f2 [CHANGE] Updated queries, exception handler, role repository. 2025-02-17 00:40:55 +01:00
max
6c67276dca [IMPL] Added base user repository implementation 2025-02-10 16:25:25 +01:00
max
1f593a364b [CHANGE] updating queries && parameter update 2025-02-10 16:11:58 +01:00
max
eef7cfb2b9 [ADD] Creating queries 2025-02-10 02:40:27 +01:00
max
65d625a30d [ADD] Join tables. Added attributes to role. 2025-02-10 02:11:35 +01:00
max
2938e1311f [DB] DbContext relations 2025-02-02 23:33:00 +01:00
max
0f6b2fec88 DBContext & repository 2025-02-02 01:06:36 +01:00
max
5b4509cac3 [ADD] Added sqlite to test project, created di for ef core context. Reworked repositories to use result class. 2025-02-01 01:02:27 +01:00
max
e914023c5a [ADD] Added EF Core project for authority db 2025-01-27 23:15:23 +01:00
max
c27890a31f [CHANGE] Building data structure 2025-01-27 01:21:09 +01:00
max
3ccd3106c1 [CHANGE] Updated models 2025-01-08 16:30:51 +01:00
max
fd733b7238 [ADD] Add cancellation tokens to async functions 2025-01-08 16:22:59 +01:00
max
28fcd74acf [REFACTOR] Split manager class, refactored/cleaned classes 2025-01-08 16:06:25 +01:00
max
90cd0a2828 [CHANGE] Removed generics and using base classes 2025-01-08 15:55:00 +01:00
max
12efc92ac4 [CHANGE] Implementation updates 2025-01-04 00:52:04 +01:00
max
efc8259930 [CHANGE] Implementing managers. repositories 2025-01-03 00:14:12 +01:00
max
2d96a25906 [CHANGE] Repository manager 2024-12-30 15:40:52 +01:00
max
172d5838e7 [ADD] Pwd validator, reworked classes 2024-12-26 20:01:57 +01:00
max
ebfafa2f29 [ADD] Implementing services/handlers 2024-12-25 22:50:04 +01:00
max
361af34036 [CHANGE] Add extension method 2024-12-23 15:59:24 +01:00
max
5c4ebd2b32 [ADD] Added verifiers, validators & config. 2024-12-23 01:26:21 +01:00
max
797323789e [ADD] Added base options 2024-12-23 00:59:13 +01:00
max
44e64793b7 [ADD] Adding models, repositories. Implementing business logic. 2024-12-22 02:15:34 +01:00
max
7ebe1e1752 [CHANGE] Extended base user model 2024-12-21 16:14:27 +01:00
max
2361e12847 [ADD] Base Authority initial commit 2024-12-21 15:30:17 +01:00
149 changed files with 2686 additions and 913 deletions

0
Blazor.Wasm/App.razor Normal file → Executable file
View File

0
Blazor.Wasm/Blazor.Wasm.csproj Normal file → Executable file
View File

0
Blazor.Wasm/Layout/MainLayout.razor Normal file → Executable file
View File

0
Blazor.Wasm/Layout/MainLayout.razor.css Normal file → Executable file
View File

0
Blazor.Wasm/Layout/NavMenu.razor Normal file → Executable file
View File

0
Blazor.Wasm/Layout/NavMenu.razor.css Normal file → Executable file
View File

0
Blazor.Wasm/Pages/Counter.razor Normal file → Executable file
View File

0
Blazor.Wasm/Pages/Home.razor Normal file → Executable file
View File

0
Blazor.Wasm/Pages/Weather.razor Normal file → Executable file
View File

0
Blazor.Wasm/Program.cs Normal file → Executable file
View File

0
Blazor.Wasm/Properties/launchSettings.json Normal file → Executable file
View File

0
Blazor.Wasm/_Imports.razor Normal file → Executable file
View File

0
Blazor.Wasm/wwwroot/css/app.css Normal file → Executable file
View File

0
Blazor.Wasm/wwwroot/css/bootstrap/bootstrap.min.css vendored Normal file → Executable file
View File

View File

0
Blazor.Wasm/wwwroot/favicon.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

0
Blazor.Wasm/wwwroot/icon-192.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

0
Blazor.Wasm/wwwroot/index.html Normal file → Executable file
View File

0
Blazor.Wasm/wwwroot/sample-data/weather.json Normal file → Executable file
View File

View File

@@ -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);
}
}

View File

@@ -1,13 +0,0 @@
namespace DotBased.ASP.Auth.Services;
public class AuthenticationService
{
public AuthenticationService()
{
/*
* - Login
* - Logout
* - Register
*/
}
}

View File

@@ -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
{
}

View File

@@ -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);
}

View File

@@ -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;
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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; } = [];
}

View File

@@ -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;
}

View File

@@ -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; } = [];
}

View File

@@ -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;
}

View File

@@ -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; } = [];
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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 = [];
}

View File

@@ -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();
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class CacheConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class LockoutConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class PasswordConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class ProviderConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class RepositoryConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class UserConfiguration
{
}

View File

@@ -1,9 +0,0 @@
namespace DotBased.ASP.Auth.Managers;
public class SecurityManager
{
public SecurityManager()
{
}
}

View File

@@ -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!");
}
}
}

View File

@@ -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;
}
}

View File

@@ -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>

View File

@@ -0,0 +1,60 @@
using DotBased.AspNet.Authority.EFCore.Models;
using DotBased.AspNet.Authority.Models.Authority;
using Microsoft.EntityFrameworkCore;
namespace DotBased.AspNet.Authority.EFCore;
public class AuthorityContext(DbContextOptions<AuthorityContext> options) : DbContext(options)
{
public DbSet<AuthorityAttribute> Attributes { get; set; }
public DbSet<AuthorityGroup> Groups { get; set; }
public DbSet<AuthorityRole> Roles { get; set; }
public DbSet<AuthorityUser> Users { get; set; }
public DbSet<RoleLink> RoleLinks { get; set; }
public DbSet<UserGroups> UserGroups { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AuthorityAttribute>(attributeEntity =>
{
attributeEntity.ToTable("authority_attributes");
attributeEntity.HasKey(a => new { a.ForeignKey, a.AttributeKey });
});
modelBuilder.Entity<AuthorityGroup>(groupEntity =>
{
groupEntity.ToTable("authority_groups");
groupEntity.HasKey(x => x.Id);
groupEntity.HasMany(g => g.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<AuthorityRole>(roleEntity =>
{
roleEntity.ToTable("authority_roles");
roleEntity.HasKey(x => x.Id);
roleEntity.HasMany(r => r.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<AuthorityUser>(userEntity =>
{
userEntity.ToTable("authority_users");
userEntity.HasKey(x => x.Id);
userEntity.HasMany(u => u.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<RoleLink>(rgEntity =>
{
rgEntity.ToTable("role_links");
rgEntity.HasKey(rg => new { rg.RoleId, rg.LinkId });
});
modelBuilder.Entity<UserGroups>(ugEntity =>
{
ugEntity.ToTable("user_groups");
ugEntity.HasKey(ug => new { ug.UserId, ug.GroupId });
});
base.OnModelCreating(modelBuilder);
}
}

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DotBased.AspNet.Authority\DotBased.AspNet.Authority.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.12">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.12" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,19 @@
using DotBased.AspNet.Authority.EFCore.Repositories;
using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace DotBased.AspNet.Authority.EFCore;
public static class Extensions
{
public static AuthorityBuilder AddAuthorityContext(this AuthorityBuilder builder, Action<DbContextOptionsBuilder> options)
{
builder.Services.AddDbContextFactory<AuthorityContext>(options);
builder.Services.AddScoped<IAttributeRepository, AttributeRepository>();
builder.Services.AddScoped<IGroupRepository, GroupRepository>();
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
return builder;
}
}

View File

@@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.EFCore.Models;
public class RoleLink
{
public Guid RoleId { get; set; }
public Guid LinkId { get; set; }
}

View File

@@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.EFCore.Models;
public class UserGroups
{
public Guid UserId { get; set; }
public Guid GroupId { get; set; }
}

View File

@@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.EFCore.Models;
public class UserRoles
{
public Guid RoleId { get; set; }
public Guid UserId { get; set; }
}

View File

@@ -0,0 +1,23 @@
# EF Core database
## Add migration project
```csharp
options.UseSqlite("Data Source=dev-dotbased.db", c => c.MigrationsAssembly("PROJECT-NAME"));
```
## EF Tool
Add migration
```shell
dotnet ef migrations add MIGRATION-NAME --project PROJECT-NAME
```
Remove migrations
```shell
dotnet ef migrations remove --project PROJECT-NAME
```
Update database
```shell
dotnet ef database update --project PROJECT-NAME
```

View File

@@ -0,0 +1,86 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<AttributeRepository> logger) : RepositoryBase, IAttributeRepository
{
public async Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "",
CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Attributes.AsQueryable();
if (!string.IsNullOrEmpty(search))
{
query = query.Where(a => $"{a.AttributeKey} {a.ForeignKey} {a.AttributeValue}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
}
var total = await query.CountAsync(cancellationToken);
var select = await query.OrderBy(a => a.AttributeKey).Skip(offset).Take(limit).Select(a => new AuthorityAttributeItem()
{
BoundId = a.ForeignKey,
AttributeKey = a.AttributeKey,
AttributeValue = a.AttributeValue
}).ToListAsync(cancellationToken);
return QueryItems<AuthorityAttributeItem>.Create(select, total, limit, offset);
}
public async Task<AuthorityAttribute?> GetAttributeByKeyAsync(string key, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
return await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == key, cancellationToken);
}
public async Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute,
CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty)
{
throw new Exception($"Attribute {attribute.AttributeKey} not found");
}
var entry = context.Attributes.Add(attribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
}
public async Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
if (currentAttribute == null)
{
return null;
}
if (currentAttribute.Version != attribute.Version)
{
logger.LogError("Attribute version validation failed for attribute {attribute}", currentAttribute.AttributeKey);
return null;
}
var entry = context.Attributes.Update(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
}
public async Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
if (currentAttribute == null)
{
logger.LogError("Attribute not found.");
return false;
}
context.Attributes.Remove(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
}
}

View File

@@ -0,0 +1,116 @@
using DotBased.AspNet.Authority.EFCore.Models;
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<GroupRepository> logger) : RepositoryBase, IGroupRepository
{
public async Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Groups.AsQueryable();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(g => $"{g.Name} {g.Id}".Contains(search));
}
var total = await query.CountAsync(cancellationToken);
var select = await query.OrderBy(g => g.Name).Skip(offset).Take(limit).Select(g => new AuthorityGroupItem()
{
Id = g.Id,
Name = g.Name
}).ToListAsync(cancellationToken);
return QueryItems<AuthorityGroupItem>.Create(select, total, limit, offset);
}
public async Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!Guid.TryParse(id, out var groupId))
{
throw new Exception($"Invalid group id: {id}");
}
return await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
}
public async Task<bool> AddUsersToGroupAsync(List<AuthorityUser> users, AuthorityGroup group, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!context.Groups.Any(g => g.Id == group.Id))
{
return false;
}
var usersToAdd = users.Where(u => !context.UserGroups.Any(ug => ug.UserId == u.Id)).ToList();
if (usersToAdd.Count == 0)
{
return false;
}
foreach (var user in usersToAdd)
{
context.UserGroups.Add(new UserGroups() { UserId = user.Id, GroupId = group.Id });
}
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult > 0;
}
public async Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var userJoinGroups = context.UserGroups.Where(ug => ug.UserId == user.Id).Select(ug => ug.GroupId);
var userGroups = context.Groups.Where(g => userJoinGroups.Contains(g.Id));
return userGroups.ToList();
}
public async Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (group.Id == Guid.Empty)
{
throw new Exception($"Invalid group id: {group.Id}");
}
var entry = context.Groups.Add(group);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
}
public async Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id ,cancellationToken);
if (currentGroup == null)
{
logger.LogError("Group with id {groupId} not found.", group.Id);
return null;
}
if (currentGroup.Version != group.Version)
{
logger.LogError("Group version validation failed.");
return null;
}
var entry = context.Groups.Update(group);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
}
public async Task<bool> DeleteGroupsAsync(List<AuthorityGroup> groups, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var groupIds = groups.Select(g => g.Id).ToList();
context.Groups.RemoveRange(groups);
context.UserGroups.RemoveRange(context.UserGroups.Where(ug => groupIds.Contains(ug.GroupId)));
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => groupIds.Contains(rl.LinkId)));
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
}
}

View File

@@ -0,0 +1,6 @@
namespace DotBased.AspNet.Authority.EFCore.Repositories;
public abstract class RepositoryBase
{
}

View File

@@ -0,0 +1,126 @@
using DotBased.AspNet.Authority.EFCore.Models;
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<RoleRepository> logger) : RepositoryBase, IRoleRepository
{
public async Task<QueryItems<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Roles.AsQueryable();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(r =>
$"{r.Name} {r.Id}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
}
var total = await query.CountAsync(cancellationToken);
var select = await query.OrderBy(r => r.Name).Skip(offset).Take(limit).Select(r => new AuthorityRoleItem()
{
Id = r.Id,
Name = r.Name
}).ToListAsync(cancellationToken: cancellationToken);
return QueryItems<AuthorityRoleItem>.Create(select, total, limit, offset);
}
public async Task<AuthorityRole?> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var role = await context.Roles.Where(r => r.Id == id).Include(r => r.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
return role;
}
public async Task<AuthorityRole?> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (role.Id == Guid.Empty)
{
throw new Exception("Role id is required!");
}
var entity = context.Roles.Add(role);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entity.Entity : null;
}
public async Task<AuthorityRole?> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentRole = await context.Roles.FirstOrDefaultAsync(r => r.Id == role.Id, cancellationToken: cancellationToken);
if (currentRole == null)
{
throw new Exception($"Role with id {role.Id} not found!");
}
if (role.Version != currentRole.Version)
{
throw new Exception("Role version does not match!");
}
var entity = context.Roles.Update(role);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entity.Entity : null;
}
public async Task<bool> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var roleIds = roles.Select(r => r.Id).ToList();
context.Roles.RemoveRange(roles);
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => roleIds.Contains(rl.RoleId)));
var removedRoles = await context.SaveChangesAsync(cancellationToken);
if (removedRoles != 0) return true;
logger.LogError("Failed to remove roles");
return false;
}
public async Task<bool> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
foreach (var role in roles)
{
context.RoleLinks.Add(new RoleLink { LinkId = linkId, RoleId = role.Id });
}
var linkedRoles = await context.SaveChangesAsync(cancellationToken);
if (linkedRoles == roles.Count)
{
return true;
}
logger.LogError("Failed to link all given roles, {linkedRoles}/{totalRoles} roles linked!", linkedRoles, roles.Count);
return false;
}
public async Task<List<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var linkedRoles = context.RoleLinks.Where(r => linkIds.Contains(r.LinkId)).Select(r => r.RoleId);
var roleList = await context.Roles.Where(r => linkedRoles.Contains(r.Id)).ToListAsync(cancellationToken);
return roleList.DistinctBy(r => r.Id).ToList();
}
public async Task<bool> UnlinkRolesAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var roleIds = roles.Select(r => r.Id).ToList();
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => rg.LinkId == linkId && roleIds.Contains(rg.RoleId)));
var unlinkedRoles = await context.SaveChangesAsync(cancellationToken);
if (unlinkedRoles != 0) return true;
logger.LogError("Failed to remove linked roles");
return false;
}
public async Task<List<Guid>> GetRolesFromLinkAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
return await context.RoleLinks.Where(r => r.LinkId == linkId && roles.Any(ar => ar.Id == r.RoleId)).Select(r => r.RoleId).ToListAsync(cancellationToken);
}
}

View File

@@ -0,0 +1,147 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<UserRepository> logger) : RepositoryBase, IUserRepository
{
public async Task<QueryItems<AuthorityUserItem>> GetUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Users.AsQueryable();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(u =>
$"{u.Id} {u.Name} {u.UserName} {u.EmailAddress} {u.PhoneNumber}".Contains(search,
StringComparison.CurrentCultureIgnoreCase));
}
var totalCount = query.Count();
var selected = await query.OrderBy(u => u.UserName).Skip(offset).Take(limit).Select(u => new AuthorityUserItem()
{
Id = u.Id,
UserName = u.UserName,
EmailAddress = u.EmailAddress,
PhoneNumber = u.PhoneNumber
}).ToListAsync(cancellationToken: cancellationToken);
return QueryItems<AuthorityUserItem>.Create(selected, totalCount, limit, offset);
}
public async Task<AuthorityUser?> GetUserByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (id == Guid.Empty)
{
throw new Exception("Id is required!");
}
return await context.Users.Where(u => u.Id == id).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
}
public async Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (user.Id == Guid.Empty)
{
throw new Exception("User id is required!");
}
var entity = context.Users.Add(user);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entity.Entity : null;
}
public async Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken: cancellationToken);
if (usr == null)
{
throw new Exception("User not found!");
}
if (usr.Version != user.Version || usr.SecurityVersion != user.SecurityVersion)
{
throw new Exception("User does not have the correct security version!");
}
var entity = context.Users.Update(user);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entity.Entity : null;
}
public async Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var usrIds = users.Select(u => u.Id);
context.Users.RemoveRange(users);
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => usrIds.Contains(rl.LinkId)));
var removedResult = await context.SaveChangesAsync(cancellationToken);
if (removedResult != 0) return true;
logger.LogError("Failed to delete users");
return false;
}
public async Task<AuthorityUser?> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
return await context.Users.Where(u => u.EmailAddress == email).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
}
public async Task<bool> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
if (usr == null)
{
throw new Exception("User not found!");
}
if (usr.Version != user.Version)
{
throw new Exception("User does not have the correct security version!");
}
usr.Version = version;
context.Users.Update(usr);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
}
public async Task<long> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var usrVersion = await context.Users.Where(u => u.Id == user.Id).Select(u => u.Version).FirstOrDefaultAsync(cancellationToken);
return usrVersion;
}
public async Task<bool> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
if (usr == null)
{
throw new Exception("User not found!");
}
if (usr.SecurityVersion != user.SecurityVersion)
{
throw new Exception("User does not have the correct security version!");
}
usr.SecurityVersion = securityVersion;
context.Users.Update(usr);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
}
public async Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var usrVersion = await context.Users.Where(u => u.Id == user.Id).Select(u => u.SecurityVersion).FirstOrDefaultAsync(cancellationToken);
return usrVersion;
}
}

View File

@@ -0,0 +1,10 @@
namespace DotBased.AspNet.Authority.Attributes;
/// <summary>
/// Indicates to protect the property before saving/loading to the repository.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ProtectAttribute : Attribute
{
}

View File

@@ -0,0 +1,13 @@
using Microsoft.Extensions.DependencyInjection;
namespace DotBased.AspNet.Authority;
public class AuthorityBuilder
{
public AuthorityBuilder(IServiceCollection services)
{
Services = services;
}
public IServiceCollection Services { get; }
}

View File

@@ -0,0 +1,40 @@
namespace DotBased.AspNet.Authority;
public static class AuthorityDefaults
{
public static class Scheme
{
public static class Authority
{
public const string AuthenticationScheme = "AuthorityLogin";
}
public static class Cookie
{
public const string AuthenticationScheme = "AuthorityCookie";
public const string CookieName = "AuthorityAuth";
}
public static class Token
{
public const string AuthenticationScheme = "AuthorityToken";
public const string TokenName = "AuthorityAuthToken";
}
}
public static class Paths
{
public const string Default = "/";
public const string Login = "/auth/login";
public const string Logout = "/auth/logout";
public const string Challenge = "/auth/challenge";
public const string Forbidden = "/forbidden";
public const string Info = "/info";
}
public static class ClaimTypes
{
public const string Attribute = "Authority.Attribute";
public const string AuthenticatedScheme = "Authority.Scheme.Authenticated";
}
}

View File

@@ -0,0 +1,97 @@
using DotBased.AspNet.Authority.Crypto;
using DotBased.AspNet.Authority.Handlers;
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Options;
using DotBased.AspNet.Authority.Models.Options.Auth;
using DotBased.AspNet.Authority.Services;
using DotBased.AspNet.Authority.Validators;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace DotBased.AspNet.Authority;
public static class AuthorityProviderExtensions
{
public static AuthorityBuilder AddAuthority(this IServiceCollection services) => AddAuthority(services, _ => { });
public static AuthorityBuilder AddAuthority(this IServiceCollection services, Action<AuthorityOptions> optionsAction)
{
services.AddOptions();
ArgumentNullException.ThrowIfNull(optionsAction);
services.Configure(optionsAction);
services.TryAddScoped<ICryptographer, Cryptographer>();
services.TryAddScoped<IPasswordHasher, PasswordHasher>();
services.TryAddScoped<IPasswordValidator, PasswordOptionsValidator>();
services.TryAddScoped<IPasswordValidator, PasswordEqualsValidator>();
services.TryAddScoped<IUserValidator, UserValidator>();
/*services.TryAddScoped<IEmailVerifier, EmailVerifier>();
services.TryAddScoped<IPhoneNumberVerifier, PhoneNumberVerifier>();
services.TryAddScoped<IUserVerifier, UserVerifier>();*/
services.TryAddScoped<AuthorityManager>();
return new AuthorityBuilder(services);
}
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder, Action<AuthorityAuthenticationOptions> configureOptions)
{
ArgumentNullException.ThrowIfNull(configureOptions);
builder.Services.Configure(configureOptions);
builder.Services.AddScoped<IAuthenticationService, AuthorityAuthenticationService>();
var authorityOptions = new AuthorityAuthenticationOptions();
configureOptions.Invoke(authorityOptions);
var authBuilder = builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = authorityOptions.DefaultScheme;
options.DefaultAuthenticateScheme = authorityOptions.DefaultAuthenticateScheme;
options.DefaultChallengeScheme = authorityOptions.DefaultChallengeScheme;
options.DefaultSignInScheme = authorityOptions.DefaultSignInScheme;
options.DefaultSignOutScheme = authorityOptions.DefaultSignOutScheme;
options.DefaultForbidScheme = authorityOptions.DefaultForbidScheme;
});
return authBuilder;
}
public static AuthenticationBuilder AddAuthorityLoginScheme(this AuthenticationBuilder builder, string scheme) =>
AddAuthorityLoginScheme(builder, scheme, _ => { });
public static AuthenticationBuilder AddAuthorityLoginScheme(this AuthenticationBuilder builder,
string scheme,
Action<AuthorityLoginOptions> configureOptions)
{
builder.AddScheme<AuthorityLoginOptions, AuthorityLoginAuthenticationHandler>(scheme, scheme, configureOptions);
return builder;
}
public static AuthenticationBuilder AddAuthorityCookie(this AuthenticationBuilder builder, string scheme)
{
builder.AddCookie(scheme, options =>
{
options.Cookie.Name = AuthorityDefaults.Scheme.Cookie.CookieName;
options.Cookie.Path = AuthorityDefaults.Paths.Default;
options.Cookie.Expiration = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.LoginPath = AuthorityDefaults.Paths.Login;
options.LogoutPath = AuthorityDefaults.Paths.Logout;
options.AccessDeniedPath = AuthorityDefaults.Paths.Forbidden;
options.SlidingExpiration = true;
//options.SessionStore
});
return builder;
}
public static AuthenticationBuilder AddAuthorityToken(this AuthenticationBuilder builder, string scheme)
{
return builder;
}
public static AuthorityBuilder MapAuthorityEndpoints(this AuthorityBuilder builder)
{
return builder;
}
}

View File

@@ -0,0 +1,59 @@
using System.Text.Json;
using DotBased.AspNet.Authority.Models.Data.System;
using DotBased.AspNet.Authority.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DotBased.AspNet.Authority.Controllers;
[ApiController]
[Route("[controller]")]
public class AuthorityController(IAuthenticationService authenticationService) : ControllerBase
{
[HttpGet(AuthorityDefaults.Paths.Login)]
[AllowAnonymous]
public async Task<ActionResult> LoginFromSchemeAsync([FromQuery(Name = "s")] string? scheme, [FromQuery(Name = "ss")] string? sessionScheme)
{
await authenticationService.AuthenticateAsync(HttpContext, scheme);
return Ok();
}
[HttpGet(AuthorityDefaults.Paths.Challenge)]
[AllowAnonymous]
public IActionResult ChallengeLogin([FromQuery(Name = "s")] string? scheme, [FromQuery(Name = "returnUrl")] string returnUrl = "/")
{
return Challenge(scheme, returnUrl);
}
[HttpGet(AuthorityDefaults.Paths.Logout)]
public async Task<ActionResult> LogoutAsync()
{
await HttpContext.SignOutAsync();
return Ok();
}
[HttpGet(AuthorityDefaults.Paths.Info)]
[AllowAnonymous]
public async Task<ActionResult<JsonDocument>> GetAuthorityInfoAsync()
{
if (authenticationService is not AuthorityAuthenticationService authService)
{
return BadRequest();
}
var schemesInfos = authService.GetAllSchemeInfos();
var info = new AuthorityInformation
{
IsAuthenticated = false,
SchemeInformation = new SchemeInformation
{
DefaultScheme = authService.Options.DefaultScheme ?? "Unknown",
AvailableSchemes = schemesInfos.ToList()
}
};
return Ok(info);
}
}

View File

@@ -0,0 +1,14 @@
namespace DotBased.AspNet.Authority.Crypto;
public class Cryptographer : ICryptographer
{
public Task<string?> EncryptAsync(string data)
{
throw new NotImplementedException();
}
public Task<string?> DecryptAsync(string data)
{
throw new NotImplementedException();
}
}

View File

@@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.Crypto;
public interface ICryptographer
{
public Task<string?> EncryptAsync(string data);
public Task<string?> DecryptAsync(string data);
}

View File

@@ -0,0 +1,6 @@
namespace DotBased.AspNet.Authority.Crypto;
public interface IPasswordHasher
{
public Task<string> HashPasswordAsync(string password);
}

View File

@@ -0,0 +1,9 @@
namespace DotBased.AspNet.Authority.Crypto;
public class PasswordHasher : IPasswordHasher
{
public async Task<string> HashPasswordAsync(string password)
{
throw new NotImplementedException();
}
}

View File

@@ -6,16 +6,21 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DotBased\DotBased.csproj" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" /> <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Models\Auth\States\" /> <ProjectReference Include="..\DotBased\DotBased.csproj" />
<Folder Include="Models\Repositories\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Models\Security\" />
<Folder Include="Schemas\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,102 @@
using System.Buffers.Text;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Encodings.Web;
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Options.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
namespace DotBased.AspNet.Authority.Handlers;
/// <summary>
/// Handles authentication for Authority logins.
/// </summary>
public class AuthorityLoginAuthenticationHandler(IOptionsMonitor<AuthorityLoginOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
AuthorityManager manager) : AuthenticationHandler<AuthorityLoginOptions>(options, logger, encoder)
{
// Validate credentials
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authResult = GetBasicAuthorization(out var email, out var password);
if (authResult != null || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
return AuthenticateResult.Fail(authResult ?? "Failed to get basic authorization from header.");
}
var userResult = await manager.GetUserByEmailAsync(email);
if (userResult is { IsSuccess: false, Error: not null })
{
return AuthenticateResult.Fail(userResult.Error.Description);
}
var user = userResult.Value;
var passwordValidateResult = await manager.ValidatePasswordAsync(user, password);
if (!passwordValidateResult.IsSuccess)
{
return AuthenticateResult.Fail(passwordValidateResult.Error?.Description ?? "Failed to validate password.");
}
var identityClaims = new List<Claim>();
var rolesResult = await manager.GetAllUserRolesAsync(user);
if (rolesResult.IsSuccess)
{
var roles = rolesResult.Value;
foreach (var authorityRole in roles)
{
identityClaims.Add(new Claim(ClaimTypes.Role, authorityRole.Name));
}
}
var principal = new ClaimsPrincipal(new ClaimsIdentity(identityClaims, Scheme.Name));
var ticket = new AuthenticationTicket(principal, Scheme.Name);
var result = AuthenticateResult.Success(ticket);
return result;
}
private string? GetBasicAuthorization(out string? email, out string? password)
{
email = null;
password = null;
if (StringValues.IsNullOrEmpty(Context.Request.Headers.Authorization))
{
return "Missing authorization header";
}
var basicAuth = string.Empty;
foreach (var authorizationValue in Context.Request.Headers.Authorization)
{
if (string.IsNullOrWhiteSpace(authorizationValue))
{
continue;
}
if (AuthenticationHeaderValue.TryParse(authorizationValue, out var basicAuthHeader) && !string.IsNullOrWhiteSpace(basicAuthHeader.Parameter))
{
basicAuth = basicAuthHeader.Parameter;
}
}
if (!Base64.IsValid(basicAuth))
{
return "Invalid basic authorization data!";
}
var base64Auth = Convert.FromBase64String(basicAuth);
var decodedAuth = System.Text.Encoding.UTF8.GetString(base64Auth);
var parts = decodedAuth.Split(':');
if (parts.Length != 2)
{
return "No email and/or password found!";
}
email = parts[0];
password = parts[1];
return null;
}
}

View File

@@ -0,0 +1,19 @@
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.Monads;
namespace DotBased.AspNet.Authority.Managers;
public partial class AuthorityManager
{
public async Task<Result<List<AuthorityGroup>>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
try
{
return await GroupRepository.GetUserGroupsAsync(user, cancellationToken);
}
catch (Exception e)
{
return e;
}
}
}

View File

@@ -0,0 +1,99 @@
using System.Reflection;
using DotBased.AspNet.Authority.Attributes;
using DotBased.AspNet.Authority.Crypto;
using DotBased.AspNet.Authority.Models.Options;
using DotBased.AspNet.Authority.Repositories;
using DotBased.AspNet.Authority.Validators;
using DotBased.Logging;
using Microsoft.Extensions.Options;
namespace DotBased.AspNet.Authority.Managers;
public partial class AuthorityManager(
IOptions<AuthorityOptions> options,
IServiceProvider services,
ICryptographer cryptographer,
IUserRepository userRepository,
IGroupRepository groupRepository,
IRoleRepository roleRepository,
IPasswordHasher passwordHasher)
{
private readonly ILogger _logger = LogService.RegisterLogger<AuthorityManager>();
public IServiceProvider Services { get; } = services;
public AuthorityOptions Options { get; } = options.Value;
public ICryptographer Cryptographer { get; } = cryptographer;
public IUserRepository UserRepository { get; } = userRepository;
public IGroupRepository GroupRepository { get; } = groupRepository;
public IRoleRepository RoleRepository { get; } = roleRepository;
public IPasswordHasher PasswordHasher { get; } = passwordHasher;
public IEnumerable<IPasswordValidator> PasswordValidators { get; } = [];
public IEnumerable<IUserValidator> UserValidators { get; } = [];
public long GenerateVersion() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
/// <summary>
/// Protect or unprotect the properties with the <see cref="ProtectAttribute"/>
/// </summary>
/// <param name="data">The data model</param>
/// <param name="protection">True for protect false for unprotect.</param>
/// <typeparam name="TModel">The class with the properties to protect.</typeparam>
public async Task HandlePropertyProtection<TModel>(TModel data, bool protection)
{
var props = GetProtectedPropertiesValues(data);
if (props.Count == 0)
{
return;
}
var handledProperties = 0;
foreach (var property in props)
{
if (property.PropertyType != typeof(string))
{
_logger.Warning("Property({PropName}) with type: {PropType} detected, encrypting only supports strings! Skipping property!", property.Name, property.PropertyType);
continue;
}
string? cryptString;
if (protection)
{
cryptString = await Cryptographer.EncryptAsync(property.GetValue(data)?.ToString() ?? string.Empty);
}
else
{
cryptString = await Cryptographer.DecryptAsync(property.GetValue(data)?.ToString() ?? string.Empty);
}
if (cryptString == null)
{
_logger.Warning("{Protection} failed for property {PropName}", protection ? "Encryption" : "Decryption", property.Name);
continue;
}
property.SetValue(data, cryptString);
handledProperties++;
}
_logger.Debug("{HandledPropCount}/{TotalPropCount} protection properties handled!", handledProperties, props.Count);
}
public bool IsPropertyProtected<TModel>(string propertyName)
{
var protectedProperties = GetProtectedProperties<TModel>();
var propertyFound = protectedProperties.Where(propInfo => propInfo.Name == propertyName);
return propertyFound.Any();
}
public List<PropertyInfo> GetProtectedPropertiesValues<TModel>(TModel model)
{
var protectedProperties = GetProtectedProperties<TModel>();
return protectedProperties.Count != 0 ? protectedProperties : [];
}
public List<PropertyInfo> GetProtectedProperties<TModel>()
=> typeof(TModel).GetProperties().Where(p => Attribute.IsDefined(p, typeof(ProtectAttribute))).ToList();
}

View File

@@ -0,0 +1,138 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.Monads;
namespace DotBased.AspNet.Authority.Managers;
public partial class AuthorityManager
{
public async Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{
role.Version = GenerateVersion();
var createResult = await RoleRepository.CreateRoleAsync(role, cancellationToken);
if (createResult == null)
{
return ResultError.Fail("Failed to create new role.");
}
return createResult;
}
public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
{
var success = await RoleRepository.DeleteRolesAsync(roles, cancellationToken);
return success ? Result.Success() : ResultError.Fail("Failed to delete roles.");
}
public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{
var result = await RoleRepository.UpdateRoleAsync(role, cancellationToken);
if (result == null)
{
return ResultError.Fail("Failed to update role.");
}
return result;
}
public async Task<Result<QueryItems<AuthorityRoleItem>>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
var searchResult = await RoleRepository.GetRolesAsync(limit, offset, search, cancellationToken);
return searchResult;
}
public async Task<Result> AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
{
var usrValidation = await IsValidUserAsync(user, cancellationToken);
if (!usrValidation.IsSuccess)
{
return usrValidation;
}
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
var rolesToAdd = roles;
if (linkedRoles.Count != 0)
{
rolesToAdd = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
}
var addSuccess = await RoleRepository.AddRolesLinkAsync(rolesToAdd, user.Id, cancellationToken);
return addSuccess ? Result.Success() : ResultError.Fail("Failed to add roles.");
}
public async Task<Result> RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
{
var usrValidation = await IsValidUserAsync(user, cancellationToken);
if (!usrValidation.IsSuccess)
{
return usrValidation;
}
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
var rolesToRemove = roles;
if (linkedRoles.Count != 0)
{
rolesToRemove = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
}
var removeResult = await RoleRepository.UnlinkRolesAsync(rolesToRemove, user.Id, cancellationToken);
return removeResult ? Result.Success() : ResultError.Fail("Failed to remove roles.");
}
public async Task<Result> AddRolesToGroupAsync(List<AuthorityRole> roles, AuthorityGroup group, CancellationToken cancellationToken = default)
{
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(group.Id, roles, cancellationToken);
var rolesToAdd = roles;
if (linkedRoles.Count != 0)
{
rolesToAdd = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
}
var linkResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, group.Id, cancellationToken);
return linkResult ? Result.Success() : ResultError.Fail("Failed to add roles.");
}
public async Task<Result<List<AuthorityRole>>> GetAllUserRolesAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
try
{
var usrValidation = await IsValidUserAsync(user, cancellationToken);
if (!usrValidation.IsSuccess)
{
return usrValidation.Error ?? ResultError.Fail("User validation failed.");
}
var searchIds = new List<Guid> { user.Id };
var usrGroups = await GetUserGroupsAsync(user, cancellationToken);
if (usrGroups.IsSuccess)
{
searchIds.AddRange(usrGroups.Value.Select(g => g.Id).ToList());
}
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken);
return linkedRolesResult;
}
catch (Exception e)
{
return e;
}
}
public async Task<Result<List<AuthorityRole>>> GetGroupRolesAsync(List<Guid> groupIds, CancellationToken cancellationToken = default)
{
try
{
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(groupIds, cancellationToken);
return linkedRolesResult;
}
catch (Exception e)
{
return e;
}
}
}

View File

@@ -0,0 +1,129 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Models.Validation;
using DotBased.AspNet.Authority.Monads;
using DotBased.Monads;
namespace DotBased.AspNet.Authority.Managers;
public partial class AuthorityManager
{
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUser user, string password)
{
List<ValidationError> errors = [];
foreach (var validator in PasswordValidators)
{
var validatorResult = await validator.ValidatePasswordAsync(this, user, password);
if (!validatorResult.IsSuccess)
{
errors.AddRange(validatorResult.ValidationErrors);
}
}
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
}
public async Task<ValidationResult> ValidateUserAsync(AuthorityUser user)
{
List<ValidationError> errors = [];
foreach (var userValidator in UserValidators)
{
var validationResult = await userValidator.ValidateUserAsync(this, user);
if (!validationResult.IsSuccess)
{
errors.AddRange(validationResult.ValidationErrors);
}
}
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
}
public async Task<Result<AuthorityUser>> GetUserByEmailAsync(string email)
{
if (string.IsNullOrEmpty(email))
{
return ResultError.Fail("No email given.");
}
var user = await userRepository.GetUserByEmailAsync(email);
if (user == null)
{
return ResultError.Fail("No user found with given email.");
}
return user;
}
public async Task<Result<QueryItems<AuthorityUserItem>>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
{
var result = await UserRepository.GetUsersAsync(maxResults, offset, query, cancellationToken);
return result;
}
public async Task<AuthorityResult<AuthorityUser>> UpdatePasswordAsync(AuthorityUser user, string password, CancellationToken cancellationToken = default)
{
var passwordValidation = await ValidatePasswordAsync(user, password);
if (!passwordValidation.IsSuccess)
{
return passwordValidation.ValidationErrors.ToList();
}
user.PasswordHash = await PasswordHasher.HashPasswordAsync(password);
user.SecurityVersion = GenerateVersion();
var updateResult = await UserRepository.UpdateUserAsync(user, cancellationToken);
if (updateResult == null)
{
return ResultError.Fail("Failed to update user password.");
}
return updateResult;
}
public async Task<AuthorityResult<AuthorityUser>> CreateUserAsync(AuthorityUser userModel, string password, CancellationToken cancellationToken = default)
{
var userValidation = await ValidateUserAsync(userModel);
var passwordValidation = await ValidatePasswordAsync(userModel, password);
if (!userValidation.IsSuccess || !passwordValidation.IsSuccess)
{
List<ValidationError> errors = [];
errors.AddRange(userValidation.ValidationErrors);
errors.AddRange(passwordValidation.ValidationErrors);
return errors;
}
userModel.Version = GenerateVersion();
userModel.SecurityVersion = GenerateVersion();
var hashedPassword = await PasswordHasher.HashPasswordAsync(password);
userModel.PasswordHash = hashedPassword;
var userCreationResult = await UserRepository.CreateUserAsync(userModel, cancellationToken);
if (userCreationResult == null)
{
return ResultError.Fail("Failed to create user.");
}
return userCreationResult;
}
public async Task<Result<AuthorityUser>> UpdateUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
{
var updateResult = await UserRepository.UpdateUserAsync(model, cancellationToken);
if (updateResult == null)
{
return ResultError.Fail("Failed to update user.");
}
return updateResult;
}
public async Task<Result> DeleteUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
{
var deleteResult = await UserRepository.DeleteUsersAsync([model], cancellationToken);
return deleteResult ? Result.Success() : ResultError.Fail("Failed to delete user.");
}
public async Task<Result> IsValidUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
var usrResult = await UserRepository.GetVersionAsync(user, cancellationToken);
return usrResult == 0 ? ResultError.Fail("Invalid user version detected.") : Result.Success();
}
}

View File

@@ -0,0 +1,14 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityAttribute(string attributeKey, Guid foreignKey)
{
public Guid ForeignKey { get; set; } = foreignKey;
public string AttributeKey { get; set; } = attributeKey;
public string AttributeValue { get; set; } = string.Empty;
public string? Type { get; set; }
public long Version { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityAttributeItem
{
public Guid BoundId { get; set; }
public string AttributeKey { get; set; } = string.Empty;
public string AttributeValue { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,18 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityGroup()
{
public AuthorityGroup(string name) : this()
{
Name = name;
}
public Guid Id { get; set; } = Guid.NewGuid();
public string? Name { get; set; }
public long Version { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
public ICollection<AuthorityAttribute> Attributes { get; set; } = [];
}

View File

@@ -0,0 +1,8 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityGroupItem
{
public Guid Id { get; set; } = Guid.NewGuid();
public string? Name { get; set; }
}

View File

@@ -0,0 +1,21 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityRole()
{
public AuthorityRole(string name) : this()
{
Name = name;
}
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public long Version { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
public IEnumerable<AuthorityAttribute> Attributes { get; set; } = [];
public override string ToString() => Name;
}

View File

@@ -0,0 +1,8 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityRoleItem
{
public Guid Id { get; set; } = Guid.NewGuid();
public string? Name { get; set; }
}

View File

@@ -0,0 +1,60 @@
using System.Text;
using DotBased.AspNet.Authority.Attributes;
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityUser()
{
public AuthorityUser(string userName) : this()
{
UserName = userName;
}
public Guid Id { get; set; } = Guid.NewGuid();
public bool Enabled { get; set; }
public bool Confirmed { get; set; }
public bool Locked { get; set; }
public DateTime LockedDate { get; set; }
public string UserName { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string? PasswordHash { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
public bool TwoFactorEnabled { get; set; }
public long Version { get; set; }
public long SecurityVersion { get; set; }
[Protect]
public string? EmailAddress { get; set; }
public bool EmailConfirmed { get; set; }
[Protect]
public string? PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public ICollection<AuthorityAttribute> Attributes { get; set; } = [];
public override string ToString()
{
var strBuilder = new StringBuilder();
strBuilder.Append(!string.IsNullOrWhiteSpace(Name) ? Name : UserName);
if (string.IsNullOrWhiteSpace(EmailAddress)) return strBuilder.ToString();
strBuilder.Append(strBuilder.Length == 0 ? EmailAddress : $" ({EmailAddress})");
return strBuilder.ToString();
}
}

View File

@@ -0,0 +1,9 @@
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityUserItem
{
public Guid Id { get; set; }
public string UserName { get; set; } = string.Empty;
public string? EmailAddress { get; set; } = string.Empty;
public string? PhoneNumber { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.Models.Data.Auth;
public class AuthenticationSessionType
{
public string Id { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,16 @@
namespace DotBased.AspNet.Authority.Models.Data.Auth;
public class AuthenticationType
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Provider { get; set; } = string.Empty;
public bool Redirects { get; set; }
public AuthenticationTypePaths Paths { get; set; } = new();
}
public class AuthenticationTypePaths
{
public string Login { get; set; } = string.Empty;
public string Logout { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,25 @@
using DotBased.AspNet.Authority.Models.Data.Auth;
using DotBased.AspNet.Authority.Models.Options.Auth;
namespace DotBased.AspNet.Authority.Models.Data.System;
public class AuthorityInformation
{
public string ServerName { get; set; } = "Authority.Server";
public bool IsAuthenticated { get; set; }
public List<AuthenticationType> AuthenticationTypes { get; set; } = [];
public List<AuthenticationSessionType> SessionTypes { get; set; } = [];
public SchemeInformation? SchemeInformation { get; set; }
public AuthenticatedInformation? AuthenticatedInformation { get; set; }
}
public class SchemeInformation
{
public string? DefaultScheme { get; set; }
public List<SchemeInfo> AvailableSchemes { get; set; } = [];
}
public class AuthenticatedInformation
{
public string? AuthenticatedScheme { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class AuthenticationSecurityOptions
{
public SecurityMode SecurityMode { get; set; } = SecurityMode.Normal;
public List<string> AllowedLoginMethods { get; set; } = ["*"];
}
public enum SecurityMode
{
Loose = 0,
Normal = 1,
Strict = 2
}

View File

@@ -0,0 +1,32 @@
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class AuthorityAuthenticationOptions
{
public AuthenticationSecurityOptions Security { get; set; } = new AuthenticationSecurityOptions();
public SessionOptions Session { get; set; } = new SessionOptions();
public string DefaultScheme { get; set; } = string.Empty;
public string DefaultAuthenticateScheme { get; set; } = string.Empty;
public string DefaultChallengeScheme { get; set; } = string.Empty;
public string DefaultForbidScheme { get; set; } = string.Empty;
public string DefaultSignInScheme { get; set; } = string.Empty;
public string DefaultSignOutScheme { get; set; } = string.Empty;
/// <summary>
/// List of schemes that the Authority application will support to authenticate against.
/// </summary>
public List<SchemeInfo> SchemeInfoMap { get; set; } = [];
}
public class SchemeInfo
{
public string Scheme { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public SchemeType Type { get; set; }
public string AuthenticationType { get; set; } = string.Empty;
public string? Endpoint { get; set; }
}
public enum SchemeType
{
Authentication,
SessionStore
}

View File

@@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Authentication;
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class AuthorityLoginOptions : AuthenticationSchemeOptions
{
}

View File

@@ -0,0 +1,6 @@
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class SessionOptions
{
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromMinutes(30);
}

View File

@@ -0,0 +1,11 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class AuthorityOptions
{
public LockdownOptions Lockdown { get; set; } = new();
public LockoutOptions Lockout { get; set; } = new();
public PasswordOptions Password { get; set; } = new();
public ProviderOptions Provider { get; set; } = new();
public RepositoryOptions Repository { get; set; } = new();
public UserOptions User { get; set; } = new();
}

View File

@@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.Models.Options;
public enum ListOption
{
Blacklist,
Whitelist
}

View File

@@ -0,0 +1,6 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class LockdownOptions
{
public bool EnableLockout { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class LockoutOptions
{
public bool EnableLockout { get; set; } = true;
public int FailedAttempts { get; set; } = 3;
public TimeSpan LockoutTimeout { get; set; } = TimeSpan.FromMinutes(30);
}

View File

@@ -0,0 +1,14 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class PasswordOptions
{
public int RequiredLength { get; set; } = 10;
public int MinimalUniqueChars { get; set; } = 1;
public bool RequireLowercase { get; set; }
public bool RequireUppercase { get; set; }
public bool RequireDigit { get; set; }
public bool RequireNonAlphanumeric { get; set; }
public List<string> PasswordBlackList { get; set; } = ["password", "1234"];
public StringComparer PasswordBlackListComparer { get; set; } = StringComparer.OrdinalIgnoreCase;
}

View File

@@ -0,0 +1,6 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class ProviderOptions
{
}

View File

@@ -0,0 +1,10 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class RepositoryOptions
{
/// <summary>
/// Use data encryption when a property has the <see cref="DotBased.AspNet.Authority.Attributes.ProtectAttribute"/> defined.
/// <value>Default: true</value>
/// </summary>
public bool UseDataProtection { get; set; } = true;
}

View File

@@ -0,0 +1,8 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class SignInOptions
{
public bool RequireVerifiedEmail { get; set; }
public bool RequireVerifiedPhoneNumber { get; set; }
public bool RequireConfirmedAccount { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace DotBased.AspNet.Authority.Models.Options;
public class UserOptions
{
public bool EnableRegister { get; set; }
public bool RequireUniqueEmail { get; set; }
public string UserNameCharacters { get; set; } = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
public ListOption UserNameCharacterListType { get; set; } = ListOption.Whitelist;
public List<string> UserNameBlackList { get; set; } = ["admin", "administrator", "dev", "developer"];
public StringComparer UserNameBlackListComparer { get; set; } = StringComparer.OrdinalIgnoreCase;
}

View File

@@ -0,0 +1,21 @@
namespace DotBased.AspNet.Authority.Models;
public class QueryItems<TItem>
{
private QueryItems(IEnumerable<TItem> items, int totalCount, int limit, int offset)
{
Items = items.ToList();
TotalCount = totalCount;
Limit = limit;
Offset = offset;
}
public readonly IReadOnlyCollection<TItem> Items;
public int Count => Items.Count;
public int TotalCount { get; }
public int Limit { get; }
public int Offset { get; }
public static QueryItems<TItem> Create(IEnumerable<TItem> items, int totalCount, int limit, int offset) => new(items, totalCount, limit, offset);
}

Some files were not shown because too many files have changed in this diff Show More