Compare commits
53 Commits
main
...
feature/ba
Author | SHA1 | Date | |
---|---|---|---|
|
e8739defad | ||
|
3a9c499aab | ||
|
333cf66cb4 | ||
|
217c55df00 | ||
|
b3763fb795 | ||
|
c225576c44 | ||
|
46dbd8c6f5 | ||
|
05b95c6050 | ||
|
edf8891ddc | ||
|
723c654d70 | ||
|
e22b7790dd | ||
|
d69359e937 | ||
|
e6d7578d49 | ||
|
46cf20893b | ||
|
8e72d123fd | ||
|
095b66f6f3 | ||
|
7ed219d08a | ||
|
ec7e260511 | ||
|
ba0de46068 | ||
|
21fe08c04f | ||
|
f0cb7218ac | ||
|
0a5950cfa2 | ||
|
bb010b0cea | ||
|
d8b08a763e | ||
|
d6c0ad1138 | ||
|
e65b937128 | ||
|
79d8fcfb8d | ||
|
c6e11efdf2 | ||
|
13b70c22f2 | ||
|
6c67276dca | ||
|
1f593a364b | ||
|
eef7cfb2b9 | ||
|
65d625a30d | ||
|
2938e1311f | ||
|
0f6b2fec88 | ||
|
5b4509cac3 | ||
|
e914023c5a | ||
|
c27890a31f | ||
|
3ccd3106c1 | ||
|
fd733b7238 | ||
|
28fcd74acf | ||
|
90cd0a2828 | ||
|
12efc92ac4 | ||
|
efc8259930 | ||
|
2d96a25906 | ||
|
172d5838e7 | ||
|
ebfafa2f29 | ||
|
361af34036 | ||
|
5c4ebd2b32 | ||
|
797323789e | ||
|
44e64793b7 | ||
|
7ebe1e1752 | ||
|
2361e12847 |
0
Blazor.Wasm/App.razor
Normal file → Executable file
0
Blazor.Wasm/App.razor
Normal file → Executable file
0
Blazor.Wasm/Blazor.Wasm.csproj
Normal file → Executable file
0
Blazor.Wasm/Blazor.Wasm.csproj
Normal file → Executable file
0
Blazor.Wasm/Layout/MainLayout.razor
Normal file → Executable file
0
Blazor.Wasm/Layout/MainLayout.razor
Normal file → Executable file
0
Blazor.Wasm/Layout/MainLayout.razor.css
Normal file → Executable file
0
Blazor.Wasm/Layout/MainLayout.razor.css
Normal file → Executable file
0
Blazor.Wasm/Layout/NavMenu.razor
Normal file → Executable file
0
Blazor.Wasm/Layout/NavMenu.razor
Normal file → Executable file
0
Blazor.Wasm/Layout/NavMenu.razor.css
Normal file → Executable file
0
Blazor.Wasm/Layout/NavMenu.razor.css
Normal file → Executable file
0
Blazor.Wasm/Pages/Counter.razor
Normal file → Executable file
0
Blazor.Wasm/Pages/Counter.razor
Normal file → Executable file
0
Blazor.Wasm/Pages/Home.razor
Normal file → Executable file
0
Blazor.Wasm/Pages/Home.razor
Normal file → Executable file
0
Blazor.Wasm/Pages/Weather.razor
Normal file → Executable file
0
Blazor.Wasm/Pages/Weather.razor
Normal file → Executable file
0
Blazor.Wasm/Program.cs
Normal file → Executable file
0
Blazor.Wasm/Program.cs
Normal file → Executable file
0
Blazor.Wasm/Properties/launchSettings.json
Normal file → Executable file
0
Blazor.Wasm/Properties/launchSettings.json
Normal file → Executable file
0
Blazor.Wasm/_Imports.razor
Normal file → Executable file
0
Blazor.Wasm/_Imports.razor
Normal file → Executable file
0
Blazor.Wasm/wwwroot/css/app.css
Normal file → Executable file
0
Blazor.Wasm/wwwroot/css/app.css
Normal file → Executable file
0
Blazor.Wasm/wwwroot/css/bootstrap/bootstrap.min.css
vendored
Normal file → Executable file
0
Blazor.Wasm/wwwroot/css/bootstrap/bootstrap.min.css
vendored
Normal file → Executable file
0
Blazor.Wasm/wwwroot/css/bootstrap/bootstrap.min.css.map
Normal file → Executable file
0
Blazor.Wasm/wwwroot/css/bootstrap/bootstrap.min.css.map
Normal file → Executable file
0
Blazor.Wasm/wwwroot/favicon.png
Normal file → Executable file
0
Blazor.Wasm/wwwroot/favicon.png
Normal file → Executable 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
0
Blazor.Wasm/wwwroot/icon-192.png
Normal file → Executable 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
0
Blazor.Wasm/wwwroot/index.html
Normal file → Executable file
0
Blazor.Wasm/wwwroot/sample-data/weather.json
Normal file → Executable file
0
Blazor.Wasm/wwwroot/sample-data/weather.json
Normal file → Executable 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);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -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,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>
|
|
60
DotBased.AspNet.Authority.EFCore/AuthorityContext.cs
Normal file
60
DotBased.AspNet.Authority.EFCore/AuthorityContext.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
@@ -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>
|
19
DotBased.AspNet.Authority.EFCore/Extensions.cs
Normal file
19
DotBased.AspNet.Authority.EFCore/Extensions.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
7
DotBased.AspNet.Authority.EFCore/Models/RoleLink.cs
Normal file
7
DotBased.AspNet.Authority.EFCore/Models/RoleLink.cs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||||
|
|
||||||
|
public class RoleLink
|
||||||
|
{
|
||||||
|
public Guid RoleId { get; set; }
|
||||||
|
public Guid LinkId { get; set; }
|
||||||
|
}
|
7
DotBased.AspNet.Authority.EFCore/Models/UserGroups.cs
Normal file
7
DotBased.AspNet.Authority.EFCore/Models/UserGroups.cs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||||
|
|
||||||
|
public class UserGroups
|
||||||
|
{
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
public Guid GroupId { get; set; }
|
||||||
|
}
|
7
DotBased.AspNet.Authority.EFCore/Models/UserRoles.cs
Normal file
7
DotBased.AspNet.Authority.EFCore/Models/UserRoles.cs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||||
|
|
||||||
|
public class UserRoles
|
||||||
|
{
|
||||||
|
public Guid RoleId { get; set; }
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
}
|
23
DotBased.AspNet.Authority.EFCore/README.md
Normal file
23
DotBased.AspNet.Authority.EFCore/README.md
Normal 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
|
||||||
|
```
|
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
116
DotBased.AspNet.Authority.EFCore/Repositories/GroupRepository.cs
Normal file
116
DotBased.AspNet.Authority.EFCore/Repositories/GroupRepository.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,6 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||||
|
|
||||||
|
public abstract class RepositoryBase
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
126
DotBased.AspNet.Authority.EFCore/Repositories/RoleRepository.cs
Normal file
126
DotBased.AspNet.Authority.EFCore/Repositories/RoleRepository.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
147
DotBased.AspNet.Authority.EFCore/Repositories/UserRepository.cs
Normal file
147
DotBased.AspNet.Authority.EFCore/Repositories/UserRepository.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
10
DotBased.AspNet.Authority/Attributes/ProtectAttribute.cs
Executable file
10
DotBased.AspNet.Authority/Attributes/ProtectAttribute.cs
Executable 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
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
13
DotBased.AspNet.Authority/AuthorityBuilder.cs
Executable file
13
DotBased.AspNet.Authority/AuthorityBuilder.cs
Executable 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; }
|
||||||
|
}
|
40
DotBased.AspNet.Authority/AuthorityDefaults.cs
Executable file
40
DotBased.AspNet.Authority/AuthorityDefaults.cs
Executable 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";
|
||||||
|
}
|
||||||
|
}
|
97
DotBased.AspNet.Authority/AuthorityProviderExtensions.cs
Executable file
97
DotBased.AspNet.Authority/AuthorityProviderExtensions.cs
Executable 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;
|
||||||
|
}
|
||||||
|
}
|
59
DotBased.AspNet.Authority/Controllers/AuthorityController.cs
Normal file
59
DotBased.AspNet.Authority/Controllers/AuthorityController.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
14
DotBased.AspNet.Authority/Crypto/Cryptographer.cs
Executable file
14
DotBased.AspNet.Authority/Crypto/Cryptographer.cs
Executable 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();
|
||||||
|
}
|
||||||
|
}
|
7
DotBased.AspNet.Authority/Crypto/ICryptographer.cs
Executable file
7
DotBased.AspNet.Authority/Crypto/ICryptographer.cs
Executable 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);
|
||||||
|
}
|
6
DotBased.AspNet.Authority/Crypto/IPasswordHasher.cs
Executable file
6
DotBased.AspNet.Authority/Crypto/IPasswordHasher.cs
Executable file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.Crypto;
|
||||||
|
|
||||||
|
public interface IPasswordHasher
|
||||||
|
{
|
||||||
|
public Task<string> HashPasswordAsync(string password);
|
||||||
|
}
|
9
DotBased.AspNet.Authority/Crypto/PasswordHasher.cs
Executable file
9
DotBased.AspNet.Authority/Crypto/PasswordHasher.cs
Executable file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.Crypto;
|
||||||
|
|
||||||
|
public class PasswordHasher : IPasswordHasher
|
||||||
|
{
|
||||||
|
public async Task<string> HashPasswordAsync(string password)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
}
|
17
DotBased.ASP.Auth/DotBased.ASP.Auth.csproj → DotBased.AspNet.Authority/DotBased.AspNet.Authority.csproj
Normal file → Executable file
17
DotBased.ASP.Auth/DotBased.ASP.Auth.csproj → DotBased.AspNet.Authority/DotBased.AspNet.Authority.csproj
Normal file → Executable 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>
|
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
19
DotBased.AspNet.Authority/Managers/AuthorityGroupManager.cs
Executable file
19
DotBased.AspNet.Authority/Managers/AuthorityGroupManager.cs
Executable 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
99
DotBased.AspNet.Authority/Managers/AuthorityManager.cs
Executable file
99
DotBased.AspNet.Authority/Managers/AuthorityManager.cs
Executable 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();
|
||||||
|
}
|
138
DotBased.AspNet.Authority/Managers/AuthorityRoleManager.cs
Executable file
138
DotBased.AspNet.Authority/Managers/AuthorityRoleManager.cs
Executable 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
129
DotBased.AspNet.Authority/Managers/AuthorityUserManager.cs
Executable file
129
DotBased.AspNet.Authority/Managers/AuthorityUserManager.cs
Executable 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();
|
||||||
|
}
|
||||||
|
}
|
14
DotBased.AspNet.Authority/Models/Authority/AuthorityAttribute.cs
Executable file
14
DotBased.AspNet.Authority/Models/Authority/AuthorityAttribute.cs
Executable 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; }
|
||||||
|
}
|
@@ -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;
|
||||||
|
}
|
18
DotBased.AspNet.Authority/Models/Authority/AuthorityGroup.cs
Executable file
18
DotBased.AspNet.Authority/Models/Authority/AuthorityGroup.cs
Executable 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; } = [];
|
||||||
|
}
|
@@ -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; }
|
||||||
|
}
|
21
DotBased.AspNet.Authority/Models/Authority/AuthorityRole.cs
Executable file
21
DotBased.AspNet.Authority/Models/Authority/AuthorityRole.cs
Executable 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;
|
||||||
|
}
|
@@ -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; }
|
||||||
|
}
|
60
DotBased.AspNet.Authority/Models/Authority/AuthorityUser.cs
Executable file
60
DotBased.AspNet.Authority/Models/Authority/AuthorityUser.cs
Executable 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();
|
||||||
|
}
|
||||||
|
}
|
@@ -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;
|
||||||
|
}
|
@@ -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;
|
||||||
|
}
|
@@ -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;
|
||||||
|
}
|
@@ -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; }
|
||||||
|
}
|
@@ -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
|
||||||
|
}
|
@@ -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
|
||||||
|
}
|
@@ -0,0 +1,8 @@
|
|||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
|
||||||
|
namespace DotBased.AspNet.Authority.Models.Options.Auth;
|
||||||
|
|
||||||
|
public class AuthorityLoginOptions : AuthenticationSchemeOptions
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
@@ -0,0 +1,6 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.Models.Options.Auth;
|
||||||
|
|
||||||
|
public class SessionOptions
|
||||||
|
{
|
||||||
|
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromMinutes(30);
|
||||||
|
}
|
11
DotBased.AspNet.Authority/Models/Options/AuthorityOptions.cs
Executable file
11
DotBased.AspNet.Authority/Models/Options/AuthorityOptions.cs
Executable 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();
|
||||||
|
}
|
7
DotBased.AspNet.Authority/Models/Options/ListOption.cs
Executable file
7
DotBased.AspNet.Authority/Models/Options/ListOption.cs
Executable file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.Models.Options;
|
||||||
|
|
||||||
|
public enum ListOption
|
||||||
|
{
|
||||||
|
Blacklist,
|
||||||
|
Whitelist
|
||||||
|
}
|
6
DotBased.AspNet.Authority/Models/Options/LockdownOptions.cs
Executable file
6
DotBased.AspNet.Authority/Models/Options/LockdownOptions.cs
Executable file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.Models.Options;
|
||||||
|
|
||||||
|
public class LockdownOptions
|
||||||
|
{
|
||||||
|
public bool EnableLockout { get; set; }
|
||||||
|
}
|
8
DotBased.AspNet.Authority/Models/Options/LockoutOptions.cs
Executable file
8
DotBased.AspNet.Authority/Models/Options/LockoutOptions.cs
Executable 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);
|
||||||
|
}
|
14
DotBased.AspNet.Authority/Models/Options/PasswordOptions.cs
Executable file
14
DotBased.AspNet.Authority/Models/Options/PasswordOptions.cs
Executable 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;
|
||||||
|
}
|
6
DotBased.AspNet.Authority/Models/Options/ProviderOptions.cs
Executable file
6
DotBased.AspNet.Authority/Models/Options/ProviderOptions.cs
Executable file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace DotBased.AspNet.Authority.Models.Options;
|
||||||
|
|
||||||
|
public class ProviderOptions
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
10
DotBased.AspNet.Authority/Models/Options/RepositoryOptions.cs
Executable file
10
DotBased.AspNet.Authority/Models/Options/RepositoryOptions.cs
Executable 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;
|
||||||
|
}
|
8
DotBased.AspNet.Authority/Models/Options/SignInOptions.cs
Executable file
8
DotBased.AspNet.Authority/Models/Options/SignInOptions.cs
Executable 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; }
|
||||||
|
}
|
12
DotBased.AspNet.Authority/Models/Options/UserOptions.cs
Executable file
12
DotBased.AspNet.Authority/Models/Options/UserOptions.cs
Executable 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;
|
||||||
|
}
|
21
DotBased.AspNet.Authority/Models/QueryItems.cs
Normal file
21
DotBased.AspNet.Authority/Models/QueryItems.cs
Normal 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
Reference in New Issue
Block a user