mirror of
https://github.com/hmaxnl/DotBased.git
synced 2025-04-18 19:48:12 +02:00
Merge 095b66f6f3
into 21675300bb
This commit is contained in:
commit
ffa982e91d
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
10
DotBased.ASP.Auth/AuthDataCache.cs
Normal file → Executable file
10
DotBased.ASP.Auth/AuthDataCache.cs
Normal file → Executable file
|
@ -15,26 +15,26 @@ public class AuthDataCache
|
|||
|
||||
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 ResultOld PurgeSessionState(string id) => _authenticationStateCollection.Remove(id) ? ResultOld.Ok() : ResultOld.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)
|
||||
public ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>> RequestSessionState(string id)
|
||||
{
|
||||
if (!_authenticationStateCollection.TryGetValue(id, out var node))
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed("No cached object found!");
|
||||
return ResultOld<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));
|
||||
return ResultOld<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);
|
||||
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed(failedMsg);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
0
DotBased.ASP.Auth/AuthenticationService.cs
Normal file → Executable file
0
DotBased.ASP.Auth/AuthenticationService.cs
Normal file → Executable file
0
DotBased.ASP.Auth/BasedAuthConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/BasedAuthConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/BasedAuthDefaults.cs
Normal file → Executable file
0
DotBased.ASP.Auth/BasedAuthDefaults.cs
Normal file → Executable file
0
DotBased.ASP.Auth/BasedServerAuthenticationStateProvider.cs
Normal file → Executable file
0
DotBased.ASP.Auth/BasedServerAuthenticationStateProvider.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Auth/AuthenticationStateModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Auth/AuthenticationStateModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Auth/PermissionModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Auth/PermissionModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Auth/RoleModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Auth/RoleModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/GroupItemModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/GroupItemModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/GroupModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/GroupModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/UserItemModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/UserItemModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/UserModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/Identity/UserModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/LoginModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/LoginModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/RegisterModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Domains/RegisterModel.cs
Normal file → Executable file
0
DotBased.ASP.Auth/DotBased.ASP.Auth.csproj
Normal file → Executable file
0
DotBased.ASP.Auth/DotBased.ASP.Auth.csproj
Normal file → Executable file
2
DotBased.ASP.Auth/DotBasedAuthDependencyInjection.cs
Normal file → Executable file
2
DotBased.ASP.Auth/DotBasedAuthDependencyInjection.cs
Normal file → Executable file
|
@ -30,7 +30,7 @@ public static class DotBasedAuthDependencyInjection
|
|||
services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultScheme = BasedAuthDefaults.AuthenticationScheme;
|
||||
});/*.AddScheme<BasedAuthenticationHandlerOptions, BasedAuthenticationHandler>(BasedAuthDefaults.AuthenticationScheme, null);*/
|
||||
});
|
||||
services.AddAuthorization();
|
||||
services.AddCascadingAuthenticationState();
|
||||
return services;
|
||||
|
|
28
DotBased.ASP.Auth/IAuthDataRepository.cs
Normal file → Executable file
28
DotBased.ASP.Auth/IAuthDataRepository.cs
Normal file → Executable file
|
@ -5,18 +5,18 @@ 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);
|
||||
public Task<ResultOld> CreateUserAsync(UserModel user);
|
||||
public Task<ResultOld> UpdateUserAsync(UserModel user);
|
||||
public Task<ResultOld> DeleteUserAsync(UserModel user);
|
||||
public Task<ResultOld<UserModel>> GetUserAsync(string id, string email, string username);
|
||||
public Task<ListResultOld<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<ResultOld> CreateGroupAsync(GroupModel group);
|
||||
public Task<ResultOld> UpdateGroupAsync(GroupModel group);
|
||||
public Task<ResultOld> DeleteGroupAsync(GroupModel group);
|
||||
public Task<ResultOld<GroupModel>> GetGroupAsync(string id);
|
||||
public Task<ListResultOld<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<ResultOld> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<ResultOld> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<ResultOld> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<ResultOld<AuthenticationStateModel>> GetAuthenticationStateAsync(string id);
|
||||
}
|
4
DotBased.ASP.Auth/ISessionStateProvider.cs
Normal file → Executable file
4
DotBased.ASP.Auth/ISessionStateProvider.cs
Normal file → Executable file
|
@ -3,6 +3,6 @@ namespace DotBased.ASP.Auth;
|
|||
public interface ISessionStateProvider
|
||||
{
|
||||
public const string SessionStateName = "BasedServerSession";
|
||||
public Task<Result<string>> GetSessionStateAsync();
|
||||
public Task<Result> SetSessionStateAsync(string state);
|
||||
public Task<ResultOld<string>> GetSessionStateAsync();
|
||||
public Task<ResultOld> SetSessionStateAsync(string state);
|
||||
}
|
48
DotBased.ASP.Auth/MemoryAuthDataRepository.cs
Normal file → Executable file
48
DotBased.ASP.Auth/MemoryAuthDataRepository.cs
Normal file → Executable file
|
@ -10,28 +10,28 @@ namespace DotBased.ASP.Auth;
|
|||
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
|
||||
public class MemoryAuthDataRepository : IAuthDataRepository
|
||||
{
|
||||
public async Task<Result> CreateUserAsync(UserModel user)
|
||||
public async Task<ResultOld> CreateUserAsync(UserModel user)
|
||||
{
|
||||
if (MemoryData.users.Any(x => x.Id == user.Id || x.Email == user.Email))
|
||||
return Result.Failed("User already exists.");
|
||||
return ResultOld.Failed("User already exists.");
|
||||
MemoryData.users.Add(user);
|
||||
return Result.Ok();
|
||||
return ResultOld.Ok();
|
||||
}
|
||||
|
||||
public async Task<Result> UpdateUserAsync(UserModel user)
|
||||
public async Task<ResultOld> UpdateUserAsync(UserModel user)
|
||||
{
|
||||
if (MemoryData.users.All(x => x.Id != user.Id))
|
||||
return Result.Failed("User does not exist!");
|
||||
return ResultOld.Failed("User does not exist!");
|
||||
|
||||
return Result.Ok();
|
||||
return ResultOld.Ok();
|
||||
}
|
||||
|
||||
public Task<Result> DeleteUserAsync(UserModel user)
|
||||
public Task<ResultOld> DeleteUserAsync(UserModel user)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Result<UserModel>> GetUserAsync(string id, string email, string username)
|
||||
public async Task<ResultOld<UserModel>> GetUserAsync(string id, string email, string username)
|
||||
{
|
||||
UserModel? userModel = null;
|
||||
if (!id.IsNullOrEmpty())
|
||||
|
@ -40,62 +40,62 @@ public class MemoryAuthDataRepository : IAuthDataRepository
|
|||
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!");
|
||||
return userModel != null ? ResultOld<UserModel>.Ok(userModel) : ResultOld<UserModel>.Failed("No user found!");
|
||||
}
|
||||
|
||||
public Task<ListResult<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "")
|
||||
public Task<ListResultOld<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "")
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result> CreateGroupAsync(GroupModel group)
|
||||
public Task<ResultOld> CreateGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result> UpdateGroupAsync(GroupModel group)
|
||||
public Task<ResultOld> UpdateGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result> DeleteGroupAsync(GroupModel group)
|
||||
public Task<ResultOld> DeleteGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<Result<GroupModel>> GetGroupAsync(string id)
|
||||
public Task<ResultOld<GroupModel>> GetGroupAsync(string id)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ListResult<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "")
|
||||
public Task<ListResultOld<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "")
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Result> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
public async Task<ResultOld> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
if (MemoryData.AuthenticationStates.Contains(authenticationState)) return Result.Failed("Item already exists!");
|
||||
if (MemoryData.AuthenticationStates.Contains(authenticationState)) return ResultOld.Failed("Item already exists!");
|
||||
MemoryData.AuthenticationStates.Add(authenticationState);
|
||||
return Result.Ok();
|
||||
return ResultOld.Ok();
|
||||
}
|
||||
|
||||
public Task<Result> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
public Task<ResultOld> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
public async Task<ResultOld> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
MemoryData.AuthenticationStates.Remove(authenticationState);
|
||||
return Result.Ok();
|
||||
return ResultOld.Ok();
|
||||
}
|
||||
|
||||
public async Task<Result<AuthenticationStateModel>> GetAuthenticationStateAsync(string id)
|
||||
public async Task<ResultOld<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);
|
||||
if (item == null) return ResultOld<AuthenticationStateModel>.Failed("Could not get the session state!");
|
||||
return ResultOld<AuthenticationStateModel>.Ok(item);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
0
DotBased.ASP.Auth/Models/Configuration/AuthConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/AuthConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/CacheConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/CacheConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/LockoutConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/LockoutConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/PasswordConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/PasswordConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/ProviderConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/ProviderConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/RepositoryConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/RepositoryConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/UserConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/Models/Configuration/UserConfiguration.cs
Normal file → Executable file
0
DotBased.ASP.Auth/SecurityManager.cs
Normal file → Executable file
0
DotBased.ASP.Auth/SecurityManager.cs
Normal file → Executable file
48
DotBased.ASP.Auth/SecurityService.cs
Normal file → Executable file
48
DotBased.ASP.Auth/SecurityService.cs
Normal file → Executable file
|
@ -24,10 +24,10 @@ public class SecurityService
|
|||
private readonly ProtectedLocalStorage _localStorage;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public async Task<Result<AuthenticationState>> GetAuthenticationStateFromSessionAsync(string id)
|
||||
public async Task<ResultOld<AuthenticationState>> GetAuthenticationStateFromSessionAsync(string id)
|
||||
{
|
||||
if (id.IsNullOrEmpty())
|
||||
return Result<AuthenticationState>.Failed("No valid id!");
|
||||
return ResultOld<AuthenticationState>.Failed("No valid id!");
|
||||
AuthenticationStateModel? authStateModel = null;
|
||||
var stateCache = _dataCache.RequestSessionState(id);
|
||||
if (!stateCache.Success || stateCache.Value == null)
|
||||
|
@ -42,16 +42,16 @@ public class SecurityService
|
|||
else
|
||||
{
|
||||
if (stateCache.Value.Item2 != null)
|
||||
return Result<AuthenticationState>.Ok(stateCache.Value.Item2);
|
||||
return ResultOld<AuthenticationState>.Ok(stateCache.Value.Item2);
|
||||
authStateModel = stateCache.Value.Item1;
|
||||
}
|
||||
|
||||
if (authStateModel == null)
|
||||
return Result<AuthenticationState>.Failed("Failed to get auth state!");
|
||||
return ResultOld<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!");
|
||||
return ResultOld<AuthenticationState>.Failed("Failed to get user from state!");
|
||||
var claims = new List<Claim>()
|
||||
{
|
||||
new(ClaimTypes.Sid, userResult.Value.Id),
|
||||
|
@ -66,56 +66,56 @@ public class SecurityService
|
|||
var claimsIdentity = new ClaimsIdentity(claims, BasedAuthDefaults.AuthenticationScheme);
|
||||
var authState = new AuthenticationState(new ClaimsPrincipal(claimsIdentity));
|
||||
_dataCache.CacheSessionState(authStateModel, authState);
|
||||
return Result<AuthenticationState>.Ok(authState);
|
||||
return ResultOld<AuthenticationState>.Ok(authState);
|
||||
}
|
||||
|
||||
public async Task<Result<AuthenticationStateModel>> LoginAsync(LoginModel login)
|
||||
public async Task<ResultOld<AuthenticationStateModel>> LoginAsync(LoginModel login)
|
||||
{
|
||||
try
|
||||
{
|
||||
UserModel? user = null;
|
||||
Result<UserModel> usrResult;
|
||||
ResultOld<UserModel> usrResultOld;
|
||||
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;
|
||||
usrResultOld = await _authDataRepository.GetUserAsync(string.Empty, string.Empty, login.UserName);
|
||||
if (usrResultOld is { Success: true, Value: not null })
|
||||
user = usrResultOld.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;
|
||||
usrResultOld = await _authDataRepository.GetUserAsync(string.Empty, login.Email, string.Empty);
|
||||
if (usrResultOld is { Success: true, Value: not null })
|
||||
user = usrResultOld.Value;
|
||||
}
|
||||
else
|
||||
return Result<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
|
||||
|
||||
if (user == null || !usrResult.Success)
|
||||
return Result<AuthenticationStateModel>.Failed("No user found!");
|
||||
if (user == null || !usrResultOld.Success)
|
||||
return ResultOld<AuthenticationStateModel>.Failed("No user found!");
|
||||
|
||||
if (user.PasswordHash != login.Password) //TODO: Hash password and compare
|
||||
return Result<AuthenticationStateModel>.Failed("Login failed, invalid password.");
|
||||
return ResultOld<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!");
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Failed to store session to database!");
|
||||
_dataCache.CacheSessionState(state);
|
||||
await _localStorage.SetAsync(BasedAuthDefaults.StorageKey, state.Id);
|
||||
return Result<AuthenticationStateModel>.Ok(state);
|
||||
return ResultOld<AuthenticationStateModel>.Ok(state);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Failed to login!");
|
||||
return Result<AuthenticationStateModel>.Failed("Login failed, exception thrown!");
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Login failed, exception thrown!");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> LogoutAsync(string state)
|
||||
public async Task<ResultOld> LogoutAsync(string state)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (state.IsNullOrEmpty())
|
||||
return Result.Failed($"Argument {nameof(state)} is empty!");
|
||||
return ResultOld.Failed($"Argument {nameof(state)} is empty!");
|
||||
|
||||
var stateResult = await _authDataRepository.GetAuthenticationStateAsync(state);
|
||||
if (!stateResult.Success || stateResult.Value == null)
|
||||
|
@ -131,7 +131,7 @@ public class SecurityService
|
|||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Failed to logout!");
|
||||
return Result.Failed("Failed to logout, exception thrown!");
|
||||
return ResultOld.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;
|
||||
}
|
||||
}
|
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 IServiceCollection AddAuthorityContext(this IServiceCollection services, Action<DbContextOptionsBuilder> options)
|
||||
{
|
||||
services.AddDbContextFactory<AuthorityContext>(options);
|
||||
services.AddScoped<IAttributeRepository, AttributeRepository>();
|
||||
services.AddScoped<IGroupRepository, GroupRepository>();
|
||||
services.AddScoped<IRoleRepository, RoleRepository>();
|
||||
services.AddScoped<IUserRepository, UserRepository>();
|
||||
return services;
|
||||
}
|
||||
}
|
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
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<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> DeleteGroupAsync(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 false;
|
||||
}
|
||||
context.Groups.Remove(currentGroup);
|
||||
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>> GetAuthorityUsersAsync(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?> GetAuthorityUserByIdAsync(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; }
|
||||
}
|
11
DotBased.AspNet.Authority/AuthorityDefaults.cs
Executable file
11
DotBased.AspNet.Authority/AuthorityDefaults.cs
Executable file
|
@ -0,0 +1,11 @@
|
|||
namespace DotBased.AspNet.Authority;
|
||||
|
||||
public static class AuthorityDefaults
|
||||
{
|
||||
public static class Scheme
|
||||
{
|
||||
public const string AuthenticationScheme = "Authority.Scheme.Authentication";
|
||||
public const string ExternalScheme = "Authority.Scheme.External";
|
||||
}
|
||||
|
||||
}
|
57
DotBased.AspNet.Authority/AuthorityProviderExtensions.cs
Executable file
57
DotBased.AspNet.Authority/AuthorityProviderExtensions.cs
Executable file
|
@ -0,0 +1,57 @@
|
|||
using DotBased.AspNet.Authority.Crypto;
|
||||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Options;
|
||||
using DotBased.AspNet.Authority.Validators;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace DotBased.AspNet.Authority;
|
||||
|
||||
public static class AuthorityProviderExtensions
|
||||
{
|
||||
public static AuthorityBuilder AddAuthority(this IServiceCollection services, Action<AuthorityOptions>? optionsAction = null)
|
||||
{
|
||||
if (optionsAction != null)
|
||||
{
|
||||
services.AddOptions();
|
||||
services.Configure<AuthorityOptions>(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 AuthorityBuilder AddAuthorityRepository<TRepository>(this AuthorityBuilder authorityBuilder) where TRepository : class
|
||||
{
|
||||
return authorityBuilder;
|
||||
}
|
||||
|
||||
public static AuthorityBuilder MapAuthorityEndpoints(this AuthorityBuilder builder)
|
||||
{
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static Type GetBaseGenericArgumentType<TModel>(Type baseType)
|
||||
{
|
||||
var userGenericBaseTypeDefinition = typeof(TModel).BaseType?.GetGenericTypeDefinition();
|
||||
if (userGenericBaseTypeDefinition != null && userGenericBaseTypeDefinition == baseType)
|
||||
{
|
||||
var userBaseGenericArguments = userGenericBaseTypeDefinition.GetGenericArguments();
|
||||
if (userBaseGenericArguments.Length <= 0)
|
||||
{
|
||||
throw new ArgumentException("Base implementation does not have the required generic argument.", nameof(TModel));
|
||||
}
|
||||
|
||||
return userBaseGenericArguments[0];
|
||||
}
|
||||
throw new ArgumentException($"Given object {typeof(TModel).Name} does not have the base implementation type of: {baseType.Name}", nameof(TModel));
|
||||
}
|
||||
}
|
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();
|
||||
}
|
||||
}
|
15
DotBased.AspNet.Auth/DotBased.AspNet.Auth.csproj → DotBased.AspNet.Authority/DotBased.AspNet.Authority.csproj
Normal file → Executable file
15
DotBased.AspNet.Auth/DotBased.AspNet.Auth.csproj → DotBased.AspNet.Authority/DotBased.AspNet.Authority.csproj
Normal file → Executable file
|
@ -7,8 +7,9 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Models\" />
|
||||
<Folder Include="Repositories\" />
|
||||
<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>
|
||||
|
@ -16,16 +17,12 @@
|
|||
</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>
|
||||
<Folder Include="Models\Data\" />
|
||||
<Folder Include="Models\Security\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
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;
|
||||
}
|
||||
}
|
||||
}
|
113
DotBased.AspNet.Authority/Managers/AuthorityUserManager.cs
Executable file
113
DotBased.AspNet.Authority/Managers/AuthorityUserManager.cs
Executable file
|
@ -0,0 +1,113 @@
|
|||
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<QueryItems<AuthorityUserItem>>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = await UserRepository.GetAuthorityUsersAsync(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;
|
||||
}
|
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);
|
||||
}
|
24
DotBased.AspNet.Authority/Models/Validation/ValidationError.cs
Executable file
24
DotBased.AspNet.Authority/Models/Validation/ValidationError.cs
Executable file
|
@ -0,0 +1,24 @@
|
|||
namespace DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
public class ValidationError
|
||||
{
|
||||
public ValidationError(string validator, string errorCode, string description)
|
||||
{
|
||||
Validator = validator;
|
||||
ErrorCode = errorCode;
|
||||
Description = description;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The validator name that generated this error.
|
||||
/// </summary>
|
||||
public string Validator { get; }
|
||||
/// <summary>
|
||||
/// The error code
|
||||
/// </summary>
|
||||
public string ErrorCode { get; }
|
||||
/// <summary>
|
||||
/// Error description
|
||||
/// </summary>
|
||||
public string Description { get; }
|
||||
}
|
40
DotBased.AspNet.Authority/Monads/AuthorityResult.cs
Normal file
40
DotBased.AspNet.Authority/Monads/AuthorityResult.cs
Normal file
|
@ -0,0 +1,40 @@
|
|||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Monads;
|
||||
|
||||
public class AuthorityResult<TResult> : Result<TResult>
|
||||
{
|
||||
protected AuthorityResult(TResult result) : base(result)
|
||||
{
|
||||
}
|
||||
|
||||
protected AuthorityResult(Exception exception) : base(exception)
|
||||
{
|
||||
}
|
||||
|
||||
protected AuthorityResult(ResultError error) : base(error)
|
||||
{
|
||||
}
|
||||
|
||||
protected AuthorityResult(List<ValidationError> validationErrors) : base(ResultError.Fail("Validation failed!"))
|
||||
{
|
||||
_validationErrors = validationErrors;
|
||||
}
|
||||
|
||||
private readonly List<ValidationError> _validationErrors = [];
|
||||
public IReadOnlyList<ValidationError> ValidationErrors => _validationErrors;
|
||||
|
||||
public static implicit operator AuthorityResult<TResult>(TResult result) => new(result);
|
||||
public static implicit operator AuthorityResult<TResult>(Exception exception) => new(exception);
|
||||
public static implicit operator AuthorityResult<TResult>(ResultError error) => new(error);
|
||||
public static implicit operator AuthorityResult<TResult>(List<ValidationError> validationErrors) => new(validationErrors);
|
||||
|
||||
public static AuthorityResult<TResult> FromResult(Result<TResult> result)
|
||||
{
|
||||
var authorityResult = result.Match<AuthorityResult<TResult>>(
|
||||
r => new AuthorityResult<TResult>(r),
|
||||
error => new AuthorityResult<TResult>(error));
|
||||
return authorityResult;
|
||||
}
|
||||
}
|
43
DotBased.AspNet.Authority/Monads/ValidationResult.cs
Normal file
43
DotBased.AspNet.Authority/Monads/ValidationResult.cs
Normal file
|
@ -0,0 +1,43 @@
|
|||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Monads;
|
||||
|
||||
public class ValidationResult : Result
|
||||
{
|
||||
private ValidationResult()
|
||||
{
|
||||
}
|
||||
|
||||
private ValidationResult(Exception exception) : base(exception)
|
||||
{
|
||||
}
|
||||
|
||||
private ValidationResult(ResultError error) : base(error)
|
||||
{
|
||||
}
|
||||
|
||||
private ValidationResult(List<ValidationError> validationErrors) : base(ResultError.Fail("Validation failed!"))
|
||||
{
|
||||
_validationErrors = validationErrors;
|
||||
}
|
||||
|
||||
private readonly List<ValidationError> _validationErrors = [];
|
||||
public IReadOnlyList<ValidationError> ValidationErrors => _validationErrors;
|
||||
|
||||
|
||||
public static implicit operator ValidationResult(Exception exception) => new(exception);
|
||||
public static implicit operator ValidationResult(ResultError error) => new(error);
|
||||
public static implicit operator ValidationResult(List<ValidationError> validationErrors) => new(validationErrors);
|
||||
|
||||
public static ValidationResult FromResult(Result result)
|
||||
{
|
||||
var validationResult = result.Match<ValidationResult>(
|
||||
() => new ValidationResult(),
|
||||
error => new ValidationResult(error));
|
||||
return validationResult;
|
||||
}
|
||||
|
||||
public new static ValidationResult Success() => new();
|
||||
public static ValidationResult Fail(List<ValidationError> validationErrors) => new(validationErrors);
|
||||
}
|
13
DotBased.AspNet.Authority/Repositories/IAttributeRepository.cs
Executable file
13
DotBased.AspNet.Authority/Repositories/IAttributeRepository.cs
Executable file
|
@ -0,0 +1,13 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IAttributeRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityAttribute?> GetAttributeByKeyAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
}
|
14
DotBased.AspNet.Authority/Repositories/IGroupRepository.cs
Executable file
14
DotBased.AspNet.Authority/Repositories/IGroupRepository.cs
Executable file
|
@ -0,0 +1,14 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IGroupRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
}
|
25
DotBased.AspNet.Authority/Repositories/IRoleRepository.cs
Executable file
25
DotBased.AspNet.Authority/Repositories/IRoleRepository.cs
Executable file
|
@ -0,0 +1,25 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IRoleRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityRole?> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityRole?> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityRole?> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default);
|
||||
public Task<bool> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
|
||||
public Task<List<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default);
|
||||
public Task<bool> UnlinkRolesAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Return the role ids the linkId has.
|
||||
/// </summary>
|
||||
/// <param name="linkId"></param>
|
||||
/// <param name="roles"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public Task<List<Guid>> GetRolesFromLinkAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default);
|
||||
}
|
18
DotBased.AspNet.Authority/Repositories/IUserRepository.cs
Executable file
18
DotBased.AspNet.Authority/Repositories/IUserRepository.cs
Executable file
|
@ -0,0 +1,18 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IUserRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default);
|
||||
public Task<bool> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default);
|
||||
public Task<long> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<bool> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default);
|
||||
public Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
}
|
10
DotBased.AspNet.Authority/Validators/IPasswordValidator.cs
Executable file
10
DotBased.AspNet.Authority/Validators/IPasswordValidator.cs
Executable file
|
@ -0,0 +1,10 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
public interface IPasswordValidator
|
||||
{
|
||||
public Task<ValidationResult> ValidatePasswordAsync(AuthorityManager manager, AuthorityUser user, string password);
|
||||
}
|
10
DotBased.AspNet.Authority/Validators/IUserValidator.cs
Executable file
10
DotBased.AspNet.Authority/Validators/IUserValidator.cs
Executable file
|
@ -0,0 +1,10 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
public interface IUserValidator
|
||||
{
|
||||
public Task<ValidationResult> ValidateUserAsync(AuthorityManager manager, AuthorityUser user);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user