Working state

This commit is contained in:
CodeLiturgy 2022-09-10 23:22:04 +01:00
parent 9dc878c517
commit 4c01d1de52
33 changed files with 303 additions and 344 deletions

View File

@ -1,15 +1,10 @@
using System;
using System.Threading.Tasks;
using BlueWest.Data; using BlueWest.Data;
using BlueWest.WebApi.EF; using BlueWest.WebApi.Context.Users;
using BlueWest.WebApi.EF.Model; using BlueWest.WebApi.EF.Model;
using Duende.IdentityServer.EntityFramework.Entities;
using Duende.IdentityServer.EntityFramework.Interfaces;
using Duende.IdentityServer.Stores.Serialization;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context;
/// <summary> /// <summary>
/// Application User Db Context /// Application User Db Context
@ -24,30 +19,27 @@ public class ApplicationUserDbContext : IdentityDbContext<
ApplicationRoleClaim, ApplicationRoleClaim,
ApplicationUserToken> ApplicationUserToken>
{ {
/// <inheritdoc />
public sealed override DbSet<ApplicationUserClaim> UserClaims { get; set; }
/// <summary> /// <inheritdoc />
/// Configures the schema needed for the identity framework. public sealed override DbSet<ApplicationUserRole> UserRoles { get; set; }
/// </summary>
/// <param name="builder"> /// <inheritdoc />
/// The builder being used to construct the model for this context. public sealed override DbSet<ApplicationRole> Roles { get; set; }
/// </param>
/// <inheritdoc />
/// <summary> public sealed override DbSet<ApplicationRoleClaim> RoleClaims { get; set; }
/// Database for the context of database users
/// </summary>
/// <param name="options"></param> /// <inheritdoc />
public ApplicationUserDbContext(DbContextOptions<ApplicationUserDbContext> options) : base(options) public ApplicationUserDbContext(DbContextOptions<ApplicationUserDbContext> options) : base(options)
{ {
Database.EnsureCreated(); Database.EnsureCreated();
} }
/// <summary>
/// Configures the schema needed for the identity framework. /// <inheritdoc />
/// </summary>
/// <param name="builder">
/// The builder being used to construct the model for this context.
/// </param>
protected override void OnModelCreating(ModelBuilder builder) protected override void OnModelCreating(ModelBuilder builder)
{ {
base.OnModelCreating(builder); base.OnModelCreating(builder);
@ -90,11 +82,15 @@ public class ApplicationUserDbContext : IdentityDbContext<
b.HasKey(r => new { r.UserId, r.RoleId }); b.HasKey(r => new { r.UserId, r.RoleId });
b.ToTable("UserRoles"); b.ToTable("UserRoles");
}); });
builder.Entity<User>(b => b.HasOne<ApplicationUser>() builder.Entity<User>(b => b.HasOne<ApplicationUser>()
.WithMany(x => x.Users) .WithMany(x => x.Users)
.HasForeignKey(x => x.ApplicationUserId)); .HasForeignKey(x => x.ApplicationUserId));
builder.Entity<ApplicationRoleClaim>().ToTable("RoleClaims");
builder.Entity<ApplicationUserRole>().ToTable("UserRole");
builder.ConfigureCurrentDbModel(); builder.ConfigureCurrentDbModel();
} }

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using BlueWest.Tools; using BlueWest.Tools;
using BlueWest.WebApi.Context.Users; using BlueWest.WebApi.Context;
using BlueWest.WebApi.EF; using BlueWest.WebApi.EF;
namespace BlueWest.WebApi.Interfaces namespace BlueWest.WebApi.Interfaces
@ -9,7 +9,7 @@ namespace BlueWest.WebApi.Interfaces
/// <summary> /// <summary>
/// Empty constructor /// Empty constructor
/// </summary> /// </summary>
public struct ExchangeEvent { } public struct ExchangeEvent { }
/// <summary> /// <summary>
/// Interface for getting and storing exchange rates data /// Interface for getting and storing exchange rates data

View File

@ -0,0 +1,26 @@
using BlueWest.WebApi.Context;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class ApplicationUserController : ControllerBase
{
private readonly ApplicationUserDbContext _context;
public ApplicationUserController(ApplicationUserDbContext context)
{
_context = context;
}
}
}

View File

@ -25,7 +25,6 @@ namespace BlueWest.WebApi.Controllers;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="mapper"></param>
/// <param name="authManager"></param> /// <param name="authManager"></param>
/// <param name="userManager"></param> /// <param name="userManager"></param>
public AuthController( IAuthManager authManager, IUserManager userManager) public AuthController( IAuthManager authManager, IUserManager userManager)
@ -48,6 +47,11 @@ namespace BlueWest.WebApi.Controllers;
} }
/// <summary>
/// Gets a bearer token
/// </summary>
/// <param name="loginViewModel"></param>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpPost("login")] [HttpPost("login")]
public async Task<ActionResult<IdentityResult>> GetTokenAsync(LoginViewModel loginViewModel) public async Task<ActionResult<IdentityResult>> GetTokenAsync(LoginViewModel loginViewModel)
@ -63,8 +67,13 @@ namespace BlueWest.WebApi.Controllers;
} }
/// <summary>
/// Do Cookie based login.
/// </summary>
/// <param name="loginDto"></param>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpPost("login2")] [HttpPost("logincookie")]
public async Task<ActionResult<IdentityResult>> DoLoginAsync(LoginViewModel loginDto) public async Task<ActionResult<IdentityResult>> DoLoginAsync(LoginViewModel loginDto)
{ {
var user = await _userManager.FindByEmailAsync(loginDto.Email); var user = await _userManager.FindByEmailAsync(loginDto.Email);
@ -83,6 +92,11 @@ namespace BlueWest.WebApi.Controllers;
return Json(false); return Json(false);
} }
/// <summary>
/// Do Cookie based logout
/// </summary>
/// <param name="loginDto"></param>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpPost("logout")] [HttpPost("logout")]
public async Task<ActionResult<IdentityResult>> DoLogoutAsync(LoginViewModel loginDto) public async Task<ActionResult<IdentityResult>> DoLogoutAsync(LoginViewModel loginDto)
@ -90,13 +104,5 @@ namespace BlueWest.WebApi.Controllers;
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Json(true); return Json(true);
} }
[HttpGet("test")]
public ActionResult TestRequest()
{
return Ok(new {Message = "Test"});
}
} }

View File

@ -19,6 +19,7 @@ namespace BlueWest.WebApi.Controllers
[Route("[controller]")] [Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[Authorize(Roles = "Administrator")]
public class CountryController : ControllerBase public class CountryController : ControllerBase
{ {

View File

@ -17,7 +17,8 @@ namespace BlueWest.WebApi.Controllers
[ApiController] [ApiController]
[Route("[controller]")] [Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[Authorize(Roles = "Administrator")]
public partial class CurrencyController : ControllerBase public partial class CurrencyController : ControllerBase
{ {

View File

@ -16,6 +16,7 @@ namespace BlueWest.WebApi.Controllers;
[Route("[controller]")] [Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[Authorize(Roles = "Administrator")]
public class FinanceController : ControllerBase public class FinanceController : ControllerBase
{ {
private readonly FinanceDbContext _dbContext; private readonly FinanceDbContext _dbContext;

View File

@ -18,7 +18,9 @@ namespace BlueWest.WebApi.Controllers
[ApiController] [ApiController]
[Route("[controller]")] [Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[Authorize(Roles = "Administrator")]
public class UserController : ControllerBase public class UserController : ControllerBase
{ {

View File

@ -3,6 +3,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using BlueWest.Cryptography; using BlueWest.Cryptography;
using BlueWest.Data; using BlueWest.Data;
using BlueWest.WebApi.Context;
using BlueWest.WebApi.Context.Users; using BlueWest.WebApi.Context.Users;
using BlueWest.WebApi.EF; using BlueWest.WebApi.EF;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
@ -104,7 +105,7 @@ namespace BlueWest.WebApi
} }
public static IServiceCollection AddAuthServerServices(this IServiceCollection services, string origins, IConfiguration configuration , IWebHostEnvironment environment) internal static IServiceCollection AddAuthServerServices(this IServiceCollection services, string origins, IConfiguration configuration , IWebHostEnvironment environment)
{ {
services.AddScoped<IJwtTokenHandler, JwtTokenHandler>(); services.AddScoped<IJwtTokenHandler, JwtTokenHandler>();
@ -113,13 +114,13 @@ namespace BlueWest.WebApi
services services
.AddScoped< UserRepository>() .AddScoped< UserRepository>()
.AddScoped<IUserManager, UserManager>() .AddScoped<IUserManager, ApplicationUserManager>()
.AddScoped<IAuthManager, AuthManager>() .AddScoped<IAuthManager, AuthManager>()
.AddScoped<IHasher, Hasher>(); .AddScoped<IHasher, Hasher>();
services services
.AddIdentityCore<ApplicationUser>(opt => { opt.User.RequireUniqueEmail = true; }) .AddIdentityCore<ApplicationUser>(opt => { opt.User.RequireUniqueEmail = true; })
.AddUserManager<UserManager>() .AddUserManager<ApplicationUserManager>()
.AddUserStore<UserRepository>(); .AddUserStore<UserRepository>();
// Database Context and Swagger // Database Context and Swagger

View File

@ -10,11 +10,14 @@ using Microsoft.Extensions.Options;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
public class UserManager : UserManager<ApplicationUser>, IUserManager /// <summary>
/// User Manager Object
/// </summary>
internal class ApplicationUserManager : UserManager<ApplicationUser>, IUserManager
{ {
private readonly IHasher _hasher; private readonly IHasher _hasher;
private readonly UserRepository _usersRepo; private readonly UserRepository _usersRepo;
public UserManager(UserRepository store, IOptions<IdentityOptions> optionsAccessor, public ApplicationUserManager(UserRepository store, IOptions<IdentityOptions> optionsAccessor,
IHasher passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IHasher passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators,
IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store,

View File

@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Identity;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
public class AuthManager : IAuthManager internal class AuthManager : IAuthManager
{ {
private readonly IUserManager _userManager; private readonly IUserManager _userManager;
private readonly UserRepository _usersRepo; private readonly UserRepository _usersRepo;

View File

@ -2,5 +2,8 @@ namespace BlueWest.WebApi.Context.Users;
public class AuthSettings public class AuthSettings
{ {
public string SecretKey { get; set; } /// <summary>
/// SecretKey
/// </summary>
public string SecretKey { get; set; }
} }

View File

@ -27,10 +27,7 @@ internal class SignInManager : SignInManager<ApplicationUser>
{ {
} }
public override async Task<ClaimsPrincipal> CreateUserPrincipalAsync(ApplicationUser user) => await ClaimsFactory.CreateAsync(user);
} }

View File

@ -0,0 +1,8 @@
namespace BlueWest.WebApi.Context.Users
{
internal class ClaimsDbExtensions
{
}
}

View File

@ -2,16 +2,31 @@ namespace BlueWest.WebApi.Context.Users;
public static class Constants public static class Constants
{ {
/// <summary>
/// AdminRoleName
/// </summary>
public const string AdminRoleName = "Admin"; public const string AdminRoleName = "Admin";
/// <summary>
/// UserRoleName
/// </summary>
public const string UserRoleName = "User"; public const string UserRoleName = "User";
public const string ExpectatorRoleName = "Expectator"; public const string ExpectatorRoleName = "Expectator";
/// <summary>
/// JwtClaimIdentifiers
/// </summary>
public static class JwtClaimIdentifiers public static class JwtClaimIdentifiers
{ {
public const string Rol = "rol", Id = "id"; public const string Rol = "rol", Id = "id";
} }
/// <summary>
/// JwtClaims
/// </summary>
public static class JwtClaims public static class JwtClaims
{ {
/// <summary>
/// JwtClaims.ApiAccess
/// </summary>
public const string ApiAccess = "api_access"; public const string ApiAccess = "api_access";
} }
} }

View File

@ -5,7 +5,7 @@ using System.Text;
namespace BlueWest.Cryptography namespace BlueWest.Cryptography
{ {
public abstract class BaseCryptoItem internal abstract class BaseCryptoItem
{ {
public enum HashAlgorithm public enum HashAlgorithm
{ {
@ -19,6 +19,11 @@ namespace BlueWest.Cryptography
SHA3_512 = 3 SHA3_512 = 3
} }
/// <summary>
/// HexStringToByteArray
/// </summary>
/// <param name="stringInHexFormat"></param>
/// <returns></returns>
protected byte[] HexStringToByteArray(string stringInHexFormat) protected byte[] HexStringToByteArray(string stringInHexFormat)
{ {
var converted = Enumerable.Range(0, stringInHexFormat.Length) var converted = Enumerable.Range(0, stringInHexFormat.Length)
@ -29,6 +34,11 @@ namespace BlueWest.Cryptography
return converted; return converted;
} }
/// <summary>
/// ByteArrayToString
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
protected string ByteArrayToString(byte[] bytes) protected string ByteArrayToString(byte[] bytes)
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();

View File

@ -8,20 +8,35 @@ using Microsoft.AspNetCore.Identity;
namespace BlueWest.Cryptography namespace BlueWest.Cryptography
{ {
public class Hasher : BaseCryptoItem, IHasher /// <summary>
/// Hasher
/// </summary>
internal class Hasher : BaseCryptoItem, IHasher
{ {
private const int SaltLength = 64; private const int SaltLength = 64;
/// <summary>
/// CreateHash
/// </summary>
/// <param name="text"></param>
/// <param name="algorithm"></param>
/// <returns></returns>
public string CreateHash(string text, BaseCryptoItem.HashAlgorithm algorithm) public string CreateHash(string text, BaseCryptoItem.HashAlgorithm algorithm)
{ {
var salt = CreateRandomString(SaltLength); var salt = CreateRandomString(SaltLength);
return CreateHash(text, salt, algorithm, true); return CreateHash(text, salt, algorithm, true);
} }
/// <summary>
/// CreateHash
/// </summary>
/// <param name="text"></param>
/// <param name="saltName"></param>
/// <param name="algorithm"></param>
/// <returns></returns>
public string CreateHash(string text, string saltName, BaseCryptoItem.HashAlgorithm algorithm) public string CreateHash(string text, string saltName, BaseCryptoItem.HashAlgorithm algorithm)
{ {
var salt = "TODOFIXME"; return CreateHash(text, saltName, algorithm, false);
return CreateHash(text, salt, algorithm, false);
} }
private string CreateHash(string text, string salt, HashAlgorithm algorithm, bool storeSalt) private string CreateHash(string text, string salt, HashAlgorithm algorithm, bool storeSalt)
@ -45,6 +60,12 @@ namespace BlueWest.Cryptography
return hash; return hash;
} }
/// <summary>
/// Check for a matching hash.
/// </summary>
/// <param name="text"></param>
/// <param name="hash"></param>
/// <returns></returns>
public bool MatchesHash(string text, string hash) public bool MatchesHash(string text, string hash)
{ {
string salt = ""; string salt = "";
@ -58,6 +79,12 @@ namespace BlueWest.Cryptography
return hashed == hash; return hashed == hash;
} }
/// <summary>
/// Hash password
/// </summary>
/// <param name="ApplicationUser"></param>
/// <param name="password"></param>
/// <returns></returns>
public string HashPassword(ApplicationUser ApplicationUser, string password) public string HashPassword(ApplicationUser ApplicationUser, string password)
{ {
return CreateHash(password, HashAlgorithm.SHA3_512); return CreateHash(password, HashAlgorithm.SHA3_512);

View File

@ -4,9 +4,31 @@ using Microsoft.AspNetCore.Identity;
namespace BlueWest.Cryptography; namespace BlueWest.Cryptography;
public interface IHasher : IPasswordHasher<ApplicationUser> /// <summary>
/// IHasher contract
/// </summary>
internal interface IHasher : IPasswordHasher<ApplicationUser>
{ {
/// <summary>
/// Create hash
/// </summary>
/// <param name="text"></param>
/// <param name="algorithm"></param>
/// <returns></returns>
string CreateHash(string text, BaseCryptoItem.HashAlgorithm algorithm); string CreateHash(string text, BaseCryptoItem.HashAlgorithm algorithm);
/// <summary>
/// Create hash
/// </summary>
/// <param name="text"></param>
/// <param name="salt"></param>
/// <param name="algorithm"></param>
/// <returns></returns>
string CreateHash(string text, string salt, BaseCryptoItem.HashAlgorithm algorithm); string CreateHash(string text, string salt, BaseCryptoItem.HashAlgorithm algorithm);
/// <summary>
/// MatchesHash
/// </summary>
/// <param name="text"></param>
/// <param name="hash"></param>
/// <returns></returns>
bool MatchesHash(string text, string hash); bool MatchesHash(string text, string hash);
} }

View File

@ -3,8 +3,18 @@ using System.Text;
using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Cryptography.KeyDerivation;
namespace BlueWest.Cryptography namespace BlueWest.Cryptography
{ {
public class SHA2_512 : BaseCryptoItem /// <summary>
/// SHA2_512 : BaseCryptoItem
/// </summary>
internal class SHA2_512 : BaseCryptoItem
{ {
/// <summary>
/// Hash with the provided salt
/// </summary>
/// <param name="text"></param>
/// <param name="salt"></param>
/// <param name="storeSalt"></param>
/// <returns></returns>
public string Hash(string text, string salt, bool storeSalt) public string Hash(string text, string salt, bool storeSalt)
{ {
var fullText = string.Concat(text, salt); var fullText = string.Concat(text, salt);
@ -25,6 +35,13 @@ namespace BlueWest.Cryptography
} }
/// <summary>
/// Hash_PBKDF2 algorithm.
/// </summary>
/// <param name="plainText"></param>
/// <param name="salt"></param>
/// <param name="saveSaltInResult"></param>
/// <returns></returns>
public string Hash_PBKDF2(string plainText, string salt, bool saveSaltInResult) public string Hash_PBKDF2(string plainText, string salt, bool saveSaltInResult)
{ {
var saltAsBytes = Encoding.ASCII.GetBytes(salt); var saltAsBytes = Encoding.ASCII.GetBytes(salt);

View File

@ -1,6 +1,6 @@
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
public interface ITokenFactory internal interface ITokenFactory
{ {
string GenerateToken(int size= 32); string GenerateToken(int size= 32);
} }

View File

@ -8,7 +8,7 @@ using static BlueWest.WebApi.Context.Users.Constants;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
public class JwtFactory : IJwtFactory internal class JwtFactory : IJwtFactory
{ {
private readonly IJwtTokenHandler _jwtTokenHandler; private readonly IJwtTokenHandler _jwtTokenHandler;
private readonly JwtIssuerOptions _jwtOptions; private readonly JwtIssuerOptions _jwtOptions;

View File

@ -4,7 +4,7 @@ using Microsoft.IdentityModel.Tokens;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
public class JwtIssuerOptions internal class JwtIssuerOptions
{ {
/// <summary> /// <summary>
/// 4.1.1. "iss" (Issuer) Claim - The "iss" (issuer) claim identifies the principal that issued the JWT. /// 4.1.1. "iss" (Issuer) Claim - The "iss" (issuer) claim identifies the principal that issued the JWT.

View File

@ -9,17 +9,31 @@ public class JwtTokenHandler : IJwtTokenHandler
{ {
private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler; private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler;
/// <summary>
/// JwtTokenHandler
/// </summary>
public JwtTokenHandler() public JwtTokenHandler()
{ {
if (_jwtSecurityTokenHandler == null) _jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
_jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
} }
/// <summary>
/// Write token
/// </summary>
/// <param name="jwt"></param>
/// <returns></returns>
public string WriteToken(JwtSecurityToken jwt) public string WriteToken(JwtSecurityToken jwt)
{ {
return _jwtSecurityTokenHandler.WriteToken(jwt); return _jwtSecurityTokenHandler.WriteToken(jwt);
} }
/// <summary>
/// Validate Token
/// </summary>
/// <param name="token"></param>
/// <param name="tokenValidationParameters"></param>
/// <returns></returns>
/// <exception cref="SecurityTokenException"></exception>
public ClaimsPrincipal ValidateToken(string token, TokenValidationParameters tokenValidationParameters) public ClaimsPrincipal ValidateToken(string token, TokenValidationParameters tokenValidationParameters)
{ {
try try

View File

@ -23,6 +23,9 @@ public class RegisterViewModel
[DataType(DataType.Password)] [DataType(DataType.Password)]
[Display(Name = "Password")] [Display(Name = "Password")]
public string Password { get; set; } public string Password { get; set; }
/// <summary>
/// Username
/// </summary>
public string Username { get; set; } public string Username { get; set; }
/// <summary> /// <summary>
@ -33,6 +36,10 @@ public class RegisterViewModel
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; } public string ConfirmPassword { get; set; }
/// <summary>
/// Convert RegisterViewModel to ApplicationUser
/// </summary>
/// <returns></returns>
public ApplicationUser ToUser() public ApplicationUser ToUser()
{ {
var newUser = new ApplicationUser(); var newUser = new ApplicationUser();

View File

@ -2,21 +2,36 @@ using System.ComponentModel.DataAnnotations;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
/// <summary>
/// Reset password view model
/// </summary>
public class ResetPasswordViewModel public class ResetPasswordViewModel
{ {
/// <summary>
/// Email address from which the password needs to be reset.
/// </summary>
[Required] [Required]
[EmailAddress] [EmailAddress]
public string Email { get; set; } public string Email { get; set; }
/// <summary>
/// Password
/// </summary>
[Required] [Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)] [DataType(DataType.Password)]
public string Password { get; set; } public string Password { get; set; }
/// <summary>
/// Password confirmation
/// </summary>
[DataType(DataType.Password)] [DataType(DataType.Password)]
[Display(Name = "Confirm password")] [Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; } public string ConfirmPassword { get; set; }
/// <summary>
/// The code to reset password.
/// </summary>
public string Code { get; set; } public string Code { get; set; }
} }

View File

@ -4,6 +4,16 @@ namespace BlueWest.WebApi.Context.Users
{ {
/// <inheritdoc /> /// <inheritdoc />
public class ApplicationRole : IdentityRole<string> public class ApplicationRole : IdentityRole<string>
{ } {
/// <inheritdoc />
public sealed override string Id { get; set; }
/// <inheritdoc />
public sealed override string Name { get; set; }
/// <inheritdoc />
public sealed override string NormalizedName { get; set; }
}
} }

View File

@ -6,5 +6,12 @@ namespace BlueWest.WebApi.Context.Users;
/// <inheritdoc /> /// <inheritdoc />
public class ApplicationRoleClaim : IdentityRoleClaim<string> public class ApplicationRoleClaim : IdentityRoleClaim<string>
{ {
public sealed override int Id { get; set; }
public sealed override string RoleId { get; set; }
public sealed override string ClaimType { get; set; }
public sealed override string ClaimValue { get; set; }
} }

View File

@ -5,5 +5,27 @@ namespace BlueWest.WebApi.Context.Users;
/// <inheritdoc /> /// <inheritdoc />
public class ApplicationUserClaim : IdentityUserClaim<string> public class ApplicationUserClaim : IdentityUserClaim<string>
{ {
/// <inheritdoc />
public sealed override int Id { get; set; }
/// <inheritdoc />
public sealed override string UserId { get; set; }
/// <inheritdoc />
public sealed override string ClaimType { get; set; }
/// <inheritdoc />
public sealed override string ClaimValue { get; set; }
public ApplicationUserClaim(ApplicationUserClaim applicationUserClaim)
{
Id = applicationUserClaim.Id;
UserId = applicationUserClaim.UserId;
ClaimType = applicationUserClaim.ClaimType;
ClaimValue = applicationUserClaim.ClaimValue;
}
public ApplicationUserClaim()
{
}
} }

View File

@ -4,4 +4,11 @@ using Microsoft.AspNetCore.Identity;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
/// <inheritdoc /> /// <inheritdoc />
public class ApplicationUserRole : IdentityUserRole<string> { } public class ApplicationUserRole : IdentityUserRole<string>
{
/// <inheritdoc />
public sealed override string UserId { get; set; }
/// <inheritdoc />
public sealed override string RoleId { get; set; }
}

View File

@ -3,6 +3,7 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace BlueWest.WebApi.Context.Users; namespace BlueWest.WebApi.Context.Users;
@ -10,104 +11,7 @@ namespace BlueWest.WebApi.Context.Users;
/// <summary> /// <summary>
/// Role storage management /// Role storage management
/// </summary> /// </summary>
public class RoleStore : IRoleStore<ApplicationRole> /*public class RoleStore : RoleStore<ApplicationRole>
{ {
private ApplicationUserDbContext _dbContext;
}*/
/// <summary>
/// Role Store constructor
/// </summary>
/// <param name="dbContext"></param>
public RoleStore(ApplicationUserDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
///
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void Dispose()
{
_dbContext = null;
}
/// <summary>
/// Get role name
/// </summary>
/// <param name="role"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<string> GetRoleNameAsync(ApplicationUserRole role, CancellationToken cancellationToken)
{
var foundRole = await _dbContext.Roles
.FirstOrDefaultAsync(x => x.Id == role.RoleId, cancellationToken: cancellationToken);
if (foundRole != null)
{
return foundRole.Name;
}
return string.Empty;
}
public async Task<IdentityResult> CreateAsync(ApplicationRole role, CancellationToken cancellationToken)
{
_dbContext.Roles.Add(role);
return await _dbContext.SaveChangesAsync(cancellationToken) >= 0 ? IdentityResult.Success : IdentityResult.Failed();
}
public async Task<IdentityResult> UpdateAsync(ApplicationRole role, CancellationToken cancellationToken)
{
_dbContext.Roles.Update(role);
return await _dbContext.SaveChangesAsync(cancellationToken) >= 0 ? IdentityResult.Success : IdentityResult.Failed();
}
public async Task<IdentityResult> DeleteAsync(ApplicationRole role, CancellationToken cancellationToken)
{
_dbContext.Roles.Remove(role);
return await _dbContext.SaveChangesAsync(cancellationToken) >= 0 ? IdentityResult.Success : IdentityResult.Failed();
}
public async Task<string> GetRoleIdAsync(ApplicationRole role, CancellationToken cancellationToken)
{
var x = await _dbContext.Roles.FirstOrDefaultAsync(x => x.Id == role.Id, cancellationToken: cancellationToken);
if (x != null)
{
return x.Id;
}
return string.Empty;
}
public Task<string> GetRoleNameAsync(ApplicationRole role, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task SetRoleNameAsync(ApplicationRole role, string roleName, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<string> GetNormalizedRoleNameAsync(ApplicationRole role, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task SetNormalizedRoleNameAsync(ApplicationRole role, string normalizedName, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<ApplicationRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<ApplicationRole> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}

View File

@ -13,10 +13,23 @@ namespace BlueWest.WebApi.Context.Users;
/// <summary> /// <summary>
/// Users Repository /// Users Repository
/// </summary> /// </summary>
public class UserRepository : UserStore<ApplicationUser, ApplicationRole, ApplicationUserDbContext> public class UserRepository : UserStore<ApplicationUser,
ApplicationRole,
ApplicationUserDbContext,
string,
ApplicationUserClaim,
ApplicationUserRole,
ApplicationUserLogin,
ApplicationUserToken,
ApplicationRoleClaim>
{ {
private readonly ApplicationUserDbContext _context; private readonly ApplicationUserDbContext _context;
/// <summary>
/// User repository
/// </summary>
/// <param name="context"></param>
/// <param name="describer"></param>
public UserRepository(ApplicationUserDbContext context, IdentityErrorDescriber describer = null) : base(context, describer) public UserRepository(ApplicationUserDbContext context, IdentityErrorDescriber describer = null) : base(context, describer)
{ {
_context = context; _context = context;
@ -32,137 +45,6 @@ public class UserRepository : UserStore<ApplicationUser, ApplicationRole, Applic
return users; return users;
} }
/// <summary>
/// Create Application User
/// </summary>
/// <param name="user"></param>
/*public override async Task<IdentityResult> CreateAsync(ApplicationUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
await _context.AddAsync(user, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}*/
/// <summary>
/// Save Changes
/// </summary>
/*
public async Task SaveChanges()
{
await _context.SaveChangesAsync();
}
*/
/*
private async Task<bool> SaveChanges(ApplicationUser user)
{
_context.Users.Update(user);
return await _context.SaveChangesAsync() > 0;
}
*/
/// <summary>
/// Dispose repository
/// </summary>
/*
public void Dispose()
{
_context.Dispose();
}
*/
/*
/// <inheritdoc />
public override Task<string> GetUserIdAsync(ApplicationUser user, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
return Task.FromResult(user.Id.ToString());
}
/// <inheritdoc />
public override Task<string> GetUserNameAsync(ApplicationUser user, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
return Task.FromResult(user.UserName);
}
*/
/// <inheritdoc />
/*
public override async Task SetUserNameAsync(ApplicationUser user, string userName, CancellationToken cancellationToken)
{
var foundUser = await _context.Users.FirstOrDefaultAsync(x => x.Id == user.Id, cancellationToken: cancellationToken);
if (foundUser == null) return;
foundUser.UserName = userName;
await SaveChanges(user);
}
*/
/*
/// <inheritdoc />
public override Task<string> GetNormalizedUserNameAsync(ApplicationUser user, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
return Task.FromResult(user.NormalizedUserName);
}
/// <inheritdoc />
public override async Task<IdentityResult> UpdateAsync(ApplicationUser user, CancellationToken cancellationToken)
{
_context.Users.Update(user);
var success = await _context.SaveChangesAsync(cancellationToken) > 0;
if (success) return IdentityResult.Success;
return IdentityResult.Failed();
}
/// <inheritdoc />
public override async Task<IdentityResult> DeleteAsync(ApplicationUser user, CancellationToken cancellationToken)
{
var foundUser = await _context.Users.FirstOrDefaultAsync(x=> x.Id == user.Id, cancellationToken: cancellationToken);
var error = new IdentityError {Description = "ApplicationUser Not found"};
if (foundUser == null) return IdentityResult.Failed(error);
_context.Users.Remove(foundUser);
return IdentityResult.Success;
}
/// <inheritdoc />
public async Task<ApplicationUser> GetUserById(string id)
{
var db = _context.Users;
var user = await db.FirstOrDefaultAsync(u => u.Id.ToString() == id);
return user;
}
*/
/// <inheritdoc /> /// <inheritdoc />
public override Task<string> GetPasswordHashAsync(ApplicationUser user, CancellationToken cancellationToken = default) public override Task<string> GetPasswordHashAsync(ApplicationUser user, CancellationToken cancellationToken = default)
{ {
@ -185,49 +67,4 @@ public class UserRepository : UserStore<ApplicationUser, ApplicationRole, Applic
return Task.FromResult(!string.IsNullOrEmpty(user.PasswordHash)); return Task.FromResult(!string.IsNullOrEmpty(user.PasswordHash));
} }
/*
/// <inheritdoc />
public override Task<string> GetEmailAsync(ApplicationUser user, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
return Task.FromResult(user.Email);
}
/// <inheritdoc />
public override Task<bool> GetEmailConfirmedAsync(ApplicationUser user, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
return Task.FromResult(user.EmailConfirmed);
}
/// <inheritdoc />
public override async Task<ApplicationUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default)
{
ApplicationUser user = null;
var db = _context.Users;
user = await db.FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, cancellationToken: cancellationToken);
return user;
}
/// <inheritdoc />
public override Task<string> GetNormalizedEmailAsync(ApplicationUser user, CancellationToken cancellationToken = default)
{
base.GetNormalizedEmailAsync(user, cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
return Task.FromResult(user.NormalizedEmail);
}*/
} }

@ -1 +1 @@
Subproject commit f7249c3bb1ac4fd12a6bdd83f902733530d04bc7 Subproject commit b6750d7128057b72e5ab97ee9ff602abe80d334b

@ -1 +1 @@
Subproject commit 2ac7524e8bc6c5f8430e944958e0890b090a4a55 Subproject commit 6fd065fc4798699394837e770d087ef110aa8e55