diff --git a/BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs b/BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs index 4f1aa0d..83ece0d 100644 --- a/BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs +++ b/BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs @@ -1,4 +1,5 @@ using BlueWest.Data; +using BlueWest.WebApi.Context.Users; using Microsoft.EntityFrameworkCore; namespace BlueWest.WebApi.EF.Model @@ -24,6 +25,7 @@ namespace BlueWest.WebApi.EF.Model .ConfigureDatabaseKeys() .CurrencyModel() .ConfigureUserModel(); + //.ConfigureIdentityModel(); } #endregion @@ -122,6 +124,40 @@ namespace BlueWest.WebApi.EF.Model } #endregion + + public static void ConfigureIdentityModel(this ModelBuilder builder) + { + builder.Entity(b => + { + b.HasMany().WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); + }); + + builder.Entity(b => + { + b.HasKey(r => r.Id); + b.HasIndex(r => r.NormalizedName).HasDatabaseName("RoleNameIndex").IsUnique(); + b.ToTable("Roles"); + b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken(); + + b.Property(u => u.Name).HasMaxLength(256); + b.Property(u => u.NormalizedName).HasMaxLength(256); + + b.HasMany().WithOne().HasForeignKey(ur => ur.RoleId).IsRequired(); + b.HasMany().WithOne().HasForeignKey(rc => rc.RoleId).IsRequired(); + }); + + builder.Entity(b => + { + b.HasKey(rc => rc.Id); + b.ToTable("RoleClaims"); + }); + + builder.Entity(b => + { + b.HasKey(r => new { r.UserId, r.RoleId }); + b.ToTable("UserRoles"); + }); + } } } diff --git a/BlueWest.Api/Context/Templates/GetManyTemplate.csx b/BlueWest.Api/Context/Templates/GetManyTemplate.csx index 008d2ca..c5ae4ff 100644 --- a/BlueWest.Api/Context/Templates/GetManyTemplate.csx +++ b/BlueWest.Api/Context/Templates/GetManyTemplate.csx @@ -8,25 +8,18 @@ /// Optional where predicate. /// Optional order by predicate. /// A bool if the result is successful and a projection of the first occurrence of {propertyName}. -public static (bool, {returnTypeFullName}[]) Get{propertyName}(this {contextFullName} dbContext, int skip = 0, int take = 50, int orderDir = 1, - Expression > where = null, - Expression > orderBy = null) +public static (bool, System.Collections.Generic.List<{returnTypeFullName}>) Get{propertyName}(this {contextFullName} dbContext, int skip = 0, int take = 50, int orderDir = 1) { if (take > 200) take = 200; var query = dbContext .{propertyName} - .Select(x => new {returnTypeFullName}(x)) .Skip(skip) - .Take(take); + .Take(take) + .Select(x => new {returnTypeFullName}(x)); + - if (where != null) query = query.Where(where); + var result = query.ToList(); - if(orderBy != null) - { - if (orderDir == 1) query = query.OrderBy(orderBy); - else query = query.OrderByDescending(orderBy); - } - - return (query.Any(), query.ToArray()); + return (result.Any(), result); } \ No newline at end of file diff --git a/BlueWest.Api/Controllers/AuthController.cs b/BlueWest.Api/Controllers/AuthController.cs index c4b1f36..27a1df4 100644 --- a/BlueWest.Api/Controllers/AuthController.cs +++ b/BlueWest.Api/Controllers/AuthController.cs @@ -1,6 +1,5 @@ using System.Security.Claims; using System.Threading.Tasks; -using AutoMapper; using BlueWest.WebApi.Context.Users; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; @@ -11,24 +10,36 @@ using Microsoft.AspNetCore.Mvc; namespace BlueWest.WebApi.Controllers; +/// +/// Auth controller +/// [Route("api/[controller]")] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [ApiController] public class AuthController : Controller { - private readonly IMapper _mapper; private readonly IAuthManager _authManager; private readonly IUserManager _userManager; - public AuthController( IMapper mapper, IAuthManager authManager, IUserManager userManager) + /// + /// + /// + /// + /// + /// + public AuthController( IAuthManager authManager, IUserManager userManager) { - _mapper = mapper; _authManager = authManager; _userManager = userManager; } + /// + /// Signup user + /// + /// + /// [AllowAnonymous] [HttpPost("register")] public async Task> SignupUserAsync(RegisterViewModel registerViewModel) @@ -45,7 +56,7 @@ namespace BlueWest.WebApi.Controllers; if (loginResultSucceded != null) { - return Ok(_mapper.Map(loginResultSucceded)); + return Ok(loginResultSucceded); } return Problem(); @@ -57,8 +68,7 @@ namespace BlueWest.WebApi.Controllers; public async Task> DoLoginAsync(LoginViewModel loginDto) { var user = await _userManager.FindByEmailAsync(loginDto.Email); - - + if (user != null) { if(await _userManager.CheckPasswordAsync(user, loginDto.Password)) @@ -78,8 +88,6 @@ namespace BlueWest.WebApi.Controllers; public async Task> DoLogoutAsync(LoginViewModel loginDto) { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - - return Json(true); } diff --git a/BlueWest.Api/Controllers/CountryController.cs b/BlueWest.Api/Controllers/CountryController.cs index 620ac5c..0133a96 100644 --- a/BlueWest.Api/Controllers/CountryController.cs +++ b/BlueWest.Api/Controllers/CountryController.cs @@ -4,6 +4,9 @@ using System.Linq; using System.Linq.Expressions; using BlueWest.Data; using BlueWest.WebApi.EF; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -14,6 +17,8 @@ namespace BlueWest.WebApi.Controllers /// [ApiController] [Route("[controller]")] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] + [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] public class CountryController : ControllerBase { diff --git a/BlueWest.Api/Controllers/CurrencyController.cs b/BlueWest.Api/Controllers/CurrencyController.cs index a759f3e..3d4ec82 100644 --- a/BlueWest.Api/Controllers/CurrencyController.cs +++ b/BlueWest.Api/Controllers/CurrencyController.cs @@ -3,6 +3,9 @@ using System.Linq; using System.Linq.Expressions; using BlueWest.Data; using BlueWest.WebApi.EF; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -13,6 +16,8 @@ namespace BlueWest.WebApi.Controllers /// [ApiController] [Route("[controller]")] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] + [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] public partial class CurrencyController : ControllerBase { @@ -40,7 +45,7 @@ namespace BlueWest.WebApi.Controllers [HttpGet] public ActionResult GetCurrencies(int skip = 0, int take = 50, int orderDir = 1) { - var (success, result) = _dbContext.GetCurrencies(skip, take, orderDir, null, x => x.Id); + var (success, result) = _dbContext.GetCurrencies(skip, take, orderDir); if (success) { diff --git a/BlueWest.Api/Controllers/FinanceController.cs b/BlueWest.Api/Controllers/FinanceController.cs index ba1cab4..d10c57d 100644 --- a/BlueWest.Api/Controllers/FinanceController.cs +++ b/BlueWest.Api/Controllers/FinanceController.cs @@ -1,6 +1,9 @@ using System; using BlueWest.Data; using BlueWest.WebApi.EF; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -11,6 +14,8 @@ namespace BlueWest.WebApi.Controllers; /// [ApiController] [Route("[controller]")] +[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] +[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] public class FinanceController : ControllerBase { private readonly FinanceDbContext _dbContext; diff --git a/BlueWest.Api/Controllers/UserController.cs b/BlueWest.Api/Controllers/UserController.cs index f0828f5..e91d349 100644 --- a/BlueWest.Api/Controllers/UserController.cs +++ b/BlueWest.Api/Controllers/UserController.cs @@ -4,6 +4,9 @@ using System.Collections.Immutable; using System.Linq; using BlueWest.Data; using BlueWest.WebApi.EF; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -14,6 +17,8 @@ namespace BlueWest.WebApi.Controllers /// [ApiController] [Route("[controller]")] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] + [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] public class UserController : ControllerBase { diff --git a/BlueWest.Api/Startup.cs b/BlueWest.Api/Startup.cs index 2fb17a7..6e52315 100644 --- a/BlueWest.Api/Startup.cs +++ b/BlueWest.Api/Startup.cs @@ -66,45 +66,47 @@ namespace BlueWest.WebApi Title = "BlueWest.Api.App", Version = "v1" }); - + // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); + + options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = + "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.ApiKey, + Scheme = "Bearer" + }); + + options.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + Array.Empty() + } + }); + }); - - - services.Configure(options => - { - // Password settings. - options.Password.RequireDigit = true; - options.Password.RequireLowercase = true; - options.Password.RequireNonAlphanumeric = true; - options.Password.RequireUppercase = true; - options.Password.RequiredLength = 6; - options.Password.RequiredUniqueChars = 1; - - // Lockout settings. - options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); - options.Lockout.MaxFailedAccessAttempts = 5; - options.Lockout.AllowedForNewUsers = true; - - // User settings. - options.User.AllowedUserNameCharacters = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; - options.User.RequireUniqueEmail = false; - }); - - services.AddScoped(); - - services.AddScoped(); - - + + /* services.AddSingleton( new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ImageFiles") ) ); + */ + IConfigurationRoot configuration = new ConfigurationBuilder() .AddJsonFile("config.json") @@ -115,6 +117,7 @@ namespace BlueWest.WebApi services .AddSingleton(); + switch (allowedDatabase) { case "mysql": @@ -128,6 +131,9 @@ namespace BlueWest.WebApi default: throw new InvalidOperationException("config.json doesn't specify a valid database. Use mysql or sqlite."); } + + services.AddAuthServerServices(MyAllowSpecificOrigins, _configuration, _environment); + services.AddScoped(); @@ -154,8 +160,10 @@ namespace BlueWest.WebApi c.RoutePrefix = "swagger"; c.SwaggerEndpoint("/swagger/v1/swagger.json", "BlueWest.Api v1"); }); - app.UseStaticFiles(); + //app.UseStaticFiles(); //app.UseHttpsRedirection(); + + app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); diff --git a/BlueWest.Api/StartupExtensions.cs b/BlueWest.Api/StartupExtensions.cs index 469e8b6..590e84e 100644 --- a/BlueWest.Api/StartupExtensions.cs +++ b/BlueWest.Api/StartupExtensions.cs @@ -79,7 +79,8 @@ namespace BlueWest.WebApi .AddDbContextPool(options => options.GetMySqlSettings(configuration, environment)) .AddDbContextPool(options => options.GetMySqlSettings(configuration, environment)) .AddDbContextPool(options => options.GetMySqlSettings(configuration, environment)) - .AddDbContextPool(options => options.GetMySqlSettings(configuration, environment)); + .AddDbContextPool(options => options.GetMySqlSettings(configuration, environment)) + .AddDbContextPool(options => options.GetMySqlSettings(configuration, environment)); } /// @@ -93,45 +94,47 @@ namespace BlueWest.WebApi IConfiguration configuration, IWebHostEnvironment environment) { var sqliteConString = "Data Source=BlueWest.Api.db"; - + return serviceCollection .AddDbContextPool(options => options.UseSqlite(sqliteConString)) .AddDbContextPool(options => options.UseSqlite(sqliteConString)) .AddDbContextPool(options => options.UseSqlite(sqliteConString)) .AddDbContextPool(options => options.UseSqlite(sqliteConString)); + } - public static void AddAuthServerServices(this IServiceCollection services, string origins, IConfiguration _configuration) + public static IServiceCollection AddAuthServerServices(this IServiceCollection services, string origins, IConfiguration configuration , IWebHostEnvironment environment) { - services.AddScoped(); - services.AddScoped(); + var sqliteConString = "Data Source=BlueWest.Api.db"; + + services.AddDbContext(options => options.UseSqlite(sqliteConString)); - // User management + services.AddScoped(); + services.AddScoped(); + + + services + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped(); + services .AddIdentityCore(opt => { opt.User.RequireUniqueEmail = true; }) - .AddEntityFrameworkStores() .AddUserManager() .AddUserStore(); // Database Context and Swagger - services.TryAddSingleton(); - // Registering 'services' and Authentication, Cookies, JWT - services - .AddScoped() - .AddScoped() // So it gets successfully registered in UserManager - .AddScoped() - .AddScoped(); - // Register the ConfigurationBuilder instance of AuthSettings - var authSettings = _configuration.GetSection(nameof(AuthSettings)); + var authSettings = configuration.GetSection(nameof(AuthSettings)); services.Configure(authSettings); var signingKey = new SymmetricSecurityKey (Encoding.ASCII.GetBytes(authSettings[nameof(AuthSettings.SecretKey)])); // jwt wire up // Get options from app settings - var jwtAppSettingOptions = _configuration + var jwtAppSettingOptions = configuration .GetSection(nameof(JwtIssuerOptions)); // Configure JwtIssuerOptions @@ -169,7 +172,7 @@ namespace BlueWest.WebApi }) .AddCookie(options => { - options.LoginPath = "/api/auth/login2"; + options.LoginPath = "/api/auth/login"; options.LogoutPath = "/api/auth/logout"; }) .AddJwtBearer(configureOptions => @@ -202,7 +205,7 @@ namespace BlueWest.WebApi }); // add identity - var identityBuilder = services.AddIdentityCore(o => + var identityBuilder = services.AddIdentityCore(o => { // configure identity options o.Password.RequireDigit = false; @@ -212,28 +215,14 @@ namespace BlueWest.WebApi o.Password.RequiredLength = 6; }); - identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services); - identityBuilder.AddEntityFrameworkStores().AddDefaultTokenProviders(); - } - public static void ConfigureApiWithUsers(this IApplicationBuilder app, IWebHostEnvironment env, string origins) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseHsts(); - } + identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(ApplicationRole), identityBuilder.Services); + identityBuilder + .AddEntityFrameworkStores() + .AddDefaultTokenProviders(); - app.UseSwagger() - .UseSwaggerUI(config => { config.SwaggerEndpoint("/swagger/v1/swagger.json", "Commands And Snippets API"); }) - .UseRouting() - .UseAuthentication() - .UseAuthorization() - .UseCors(origins) - .UseEndpoints(endpoints => endpoints.MapControllers()); + return services; } + } } \ No newline at end of file diff --git a/BlueWest.Api/UpdateContexts.bash b/BlueWest.Api/UpdateContexts.bash new file mode 100644 index 0000000..e106552 --- /dev/null +++ b/BlueWest.Api/UpdateContexts.bash @@ -0,0 +1,6 @@ +dotnet ef database update -c ApplicationUserDbContext +dotnet ef database update -c CountryDbContext +dotnet ef database update -c CompanyDbContext +dotnet ef database update -c UserDbContext + + diff --git a/BlueWest.Api/Users/ApplicationUser.cs b/BlueWest.Api/Users/ApplicationUser.cs index c04d44e..dfe9d1b 100644 --- a/BlueWest.Api/Users/ApplicationUser.cs +++ b/BlueWest.Api/Users/ApplicationUser.cs @@ -1,4 +1,6 @@ using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; using Microsoft.AspNetCore.Identity; namespace BlueWest.WebApi.Context.Users; @@ -12,8 +14,9 @@ public class ApplicationUser : IdentityUser /// /// Gets or sets the primary key for this user. /// - [PersonalData] - public new Guid Id { get; set; } +[DatabaseGenerated(DatabaseGeneratedOption.Identity)] +[PersonalData] + public new string Id { get; set; } /// /// Gets or sets the user name for this user. diff --git a/BlueWest.Api/Users/ApplicationUserDbContext.cs b/BlueWest.Api/Users/ApplicationUserDbContext.cs index cfaaa93..54459e3 100644 --- a/BlueWest.Api/Users/ApplicationUserDbContext.cs +++ b/BlueWest.Api/Users/ApplicationUserDbContext.cs @@ -22,22 +22,8 @@ public class ApplicationUserDbContext : IdentityDbContext< ApplicationUserRole, ApplicationUserLogin, ApplicationRoleClaim, - ApplicationUserToken>, IPersistedGrantDbContext + ApplicationUserToken> { - /// - /// Gets or sets the of User roles. - /// - public override DbSet UserRoles { get; set; } - - /// - /// Gets or sets the of roles. - /// - public override DbSet Roles { get; set; } - - /// - /// Gets or sets the of role claims. - /// - public override DbSet RoleClaims { get; set; } /// /// Configures the schema needed for the identity framework. @@ -50,9 +36,10 @@ public class ApplicationUserDbContext : IdentityDbContext< /// Database for the context of database users /// /// - public ApplicationUserDbContext(DbContextOptions options) : base(options) + public ApplicationUserDbContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); + } /// @@ -64,13 +51,19 @@ public class ApplicationUserDbContext : IdentityDbContext< protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); - builder.ConfigureCurrentDbModel(); - base.OnModelCreating(builder); + builder.Entity(b => { - b.HasMany().WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); + b.HasMany() + .WithOne() + .HasForeignKey(ur => ur.UserId).IsRequired(); }); + builder.Entity().ToTable("ApplicationUser") + .HasKey(x => x.Id); + + + builder.Entity(b => { b.HasKey(r => r.Id); @@ -96,14 +89,8 @@ public class ApplicationUserDbContext : IdentityDbContext< b.HasKey(r => new { r.UserId, r.RoleId }); b.ToTable("UserRoles"); }); + + builder.ConfigureCurrentDbModel(); } - public Task SaveChangesAsync() - { - return SaveChangesAsync(); - } - - public DbSet PersistedGrants { get; set; } - public DbSet DeviceFlowCodes { get; set; } - public DbSet Keys { get; set; } } \ No newline at end of file diff --git a/BlueWest.Api/Users/Auth/AuthManager.cs b/BlueWest.Api/Users/Auth/AuthManager.cs index e40f03b..2bd44e3 100644 --- a/BlueWest.Api/Users/Auth/AuthManager.cs +++ b/BlueWest.Api/Users/Auth/AuthManager.cs @@ -1,6 +1,5 @@ using System.Threading; using System.Threading.Tasks; -using AutoMapper; using BlueWest.Cryptography; using BlueWest.Data; using Microsoft.AspNetCore.Identity; @@ -9,22 +8,27 @@ namespace BlueWest.WebApi.Context.Users; public class AuthManager : IAuthManager { - private readonly IUserManager _userManager; - private readonly IUsersRepo _usersRepo; + private readonly IUserManager _userManager; + private readonly UserRepository _usersRepo; private readonly IHasher _hasher; - private readonly IMapper _mapper; private readonly IJwtFactory _jwtFactory; - public AuthManager(IUserManager userManager, IHasher hasher, IMapper mapper - , IUsersRepo usersRepo, IJwtFactory jwtFactory) + /// + /// Auth manager constructor + /// + /// + /// + /// + /// + public AuthManager(IUserManager userManager, IHasher hasher, UserRepository usersRepo, IJwtFactory jwtFactory) { _userManager = userManager; _hasher = hasher; - _mapper = mapper; _usersRepo = usersRepo; _jwtFactory = jwtFactory; } + /// public async Task GetToken(LoginViewModel loginViewModel) { if (!string.IsNullOrEmpty(loginViewModel.Email) && !string.IsNullOrEmpty(loginViewModel.Password)) @@ -48,6 +52,7 @@ public class AuthManager : IAuthManager return null; } + /// public async Task VerifyLoginAsync(string email, string password) { var user = await _userManager.FindByEmailAsync(email); @@ -71,10 +76,11 @@ public class AuthManager : IAuthManager return signupDto; } - + public async Task CreateUserAsync(RegisterViewModel userSignupDto) { - - return await _userManager.CreateAsync(userSignupDto.ToUser()); + RegisterViewModel userToCreate = FromSignupToUser(userSignupDto); + return await _userManager.CreateAsync(userToCreate.ToUser()); } + } \ No newline at end of file diff --git a/BlueWest.Api/Users/Auth/IAuthManager.cs b/BlueWest.Api/Users/Auth/IAuthManager.cs index 1429ffc..32ca9b9 100644 --- a/BlueWest.Api/Users/Auth/IAuthManager.cs +++ b/BlueWest.Api/Users/Auth/IAuthManager.cs @@ -4,12 +4,31 @@ using Microsoft.AspNetCore.Identity; namespace BlueWest.WebApi.Context.Users; +/// +/// Auth manager contract interface. +/// public interface IAuthManager { + /// + /// CreateUserAsync + /// + /// + /// Task CreateUserAsync(RegisterViewModel registerViewModel); + /// + /// VerifyLoginAsync + /// + /// + /// + /// Task VerifyLoginAsync(string email, string password); + /// + /// GetToken + /// + /// + /// Task GetToken(LoginViewModel loginViewModel); } \ No newline at end of file diff --git a/BlueWest.Api/Users/IUsersRepo.cs b/BlueWest.Api/Users/IUsersRepo.cs deleted file mode 100644 index d941c2e..0000000 --- a/BlueWest.Api/Users/IUsersRepo.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using BlueWest.Data; -using Microsoft.AspNetCore.Identity; - -namespace BlueWest.WebApi.Context.Users; -/// -/// This is our Users repository. -/// Since this is a simple app we'll have the following roles -/// Admin and APIClient -/// -public interface IUsersRepo : IUserStore -{ - public Task> GetUsers(); - public Task CreateUser(ApplicationUser user); - public Task SaveChanges(); - - public Task GetUserById(string id); - - Task FindByEmailAsync(string email, CancellationToken cancellationToken); - -} \ No newline at end of file diff --git a/BlueWest.Api/Users/Models/RegisterViewModel.cs b/BlueWest.Api/Users/Models/RegisterViewModel.cs index a05518f..1fafc3a 100644 --- a/BlueWest.Api/Users/Models/RegisterViewModel.cs +++ b/BlueWest.Api/Users/Models/RegisterViewModel.cs @@ -23,6 +23,7 @@ public class RegisterViewModel [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } + public string Username { get; set; } /// /// ConfirmPassword @@ -37,6 +38,7 @@ public class RegisterViewModel var newUser = new ApplicationUser(); newUser.Email = Email; newUser.PasswordHash = Password; + newUser.UserName = Username; return newUser; } } \ No newline at end of file diff --git a/BlueWest.Api/Users/UserManager.cs b/BlueWest.Api/Users/UserManager.cs index 622a930..a7d0617 100644 --- a/BlueWest.Api/Users/UserManager.cs +++ b/BlueWest.Api/Users/UserManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using BlueWest.Cryptography; using BlueWest.Data; @@ -12,8 +13,8 @@ namespace BlueWest.WebApi.Context.Users; public class UserManager : UserManager, IUserManager { private readonly IHasher _hasher; - private readonly IUsersRepo _usersRepo; - public UserManager(IUsersRepo store, IOptions optionsAccessor, + private readonly UserRepository _usersRepo; + public UserManager(UserRepository store, IOptions optionsAccessor, IHasher passwordHasher, IEnumerable> userValidators, IEnumerable> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger> logger) : base(store, @@ -24,24 +25,6 @@ public class UserManager : UserManager, IUserManager _usersRepo = store; } - public override async Task CreateAsync(ApplicationUser user) - { - ThrowIfDisposed(); - var result = await ValidateUserAsync(user); - if (!result.Succeeded) - { - return result; - } - if (Options.Lockout.AllowedForNewUsers && SupportsUserLockout) - { - // await GetUserLockoutStore().SetLockoutEnabledAsync(user, true, CancellationToken); - } - await UpdateNormalizedUserNameAsync(user); - await UpdateNormalizedEmailAsync(user); - - return await _usersRepo.CreateAsync(user, CancellationToken); - } - public override async Task CheckPasswordAsync(ApplicationUser user, string password) { ThrowIfDisposed(); @@ -80,28 +63,7 @@ public class UserManager : UserManager, IUserManager return PasswordHasher.VerifyHashedPassword(user, existingHash, password); } - public override async Task FindByNameAsync(string userName) - { - if (userName == null) - { - throw new ArgumentNullException(nameof(userName)); - } - - ApplicationUser user; - - if (Store is IUsersRepo repo) - { - user = await repo.FindByNameAsync(userName, CancellationToken); - } - else - { - userName = NormalizeName(userName); - user = await Store.FindByNameAsync(userName, CancellationToken); - } - - return user; - } - + public override async Task ChangePasswordAsync(ApplicationUser user, string currentPassword, string newPassword) { @@ -137,19 +99,4 @@ public class UserManager : UserManager, IUserManager return null; } - public override async Task FindByEmailAsync(string email) - { - ApplicationUser user = null; - - if (Store is IUsersRepo repo) - { - user = await repo.FindByEmailAsync(email, CancellationToken); - } - else - { - user = await Store.FindByNameAsync(email, CancellationToken); - } - - return user; - } } \ No newline at end of file diff --git a/BlueWest.Api/Users/UserRepository.cs b/BlueWest.Api/Users/UserRepository.cs index 322e28b..e6aaf4c 100644 --- a/BlueWest.Api/Users/UserRepository.cs +++ b/BlueWest.Api/Users/UserRepository.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -12,7 +13,7 @@ namespace BlueWest.WebApi.Context.Users; /// /// Users Repository /// -public class UserRepository : UserStore, IUsersRepo +public class UserRepository : UserStore { private readonly ApplicationUserDbContext _context; @@ -35,34 +36,48 @@ public class UserRepository : UserStore /// - public async Task CreateUser(ApplicationUser user) + /*public override async Task CreateAsync(ApplicationUser user, CancellationToken cancellationToken = default(CancellationToken)) { - await CreateAsync(user, CancellationToken.None); - } - + cancellationToken.ThrowIfCancellationRequested(); + ThrowIfDisposed(); + if (user == null) + { + throw new ArgumentNullException(nameof(user)); + } + await _context.AddAsync(user, cancellationToken); + await _context.SaveChangesAsync(cancellationToken); + return IdentityResult.Success; + }*/ /// /// Save Changes /// + /* public async Task SaveChanges() { await _context.SaveChangesAsync(); } + */ + /* private async Task SaveChanges(ApplicationUser user) { _context.Users.Update(user); return await _context.SaveChangesAsync() > 0; } + */ /// /// Dispose repository /// + /* public void Dispose() { _context.Dispose(); } + */ + /* /// public override Task GetUserIdAsync(ApplicationUser user, CancellationToken cancellationToken = default) { @@ -85,8 +100,10 @@ public class UserRepository : UserStore + /* public override async Task SetUserNameAsync(ApplicationUser user, string userName, CancellationToken cancellationToken) { var foundUser = await _context.Users.FirstOrDefaultAsync(x => x.Id == user.Id, cancellationToken: cancellationToken); @@ -94,7 +111,9 @@ public class UserRepository : UserStore public override Task GetNormalizedUserNameAsync(ApplicationUser user, CancellationToken cancellationToken) { @@ -106,20 +125,7 @@ public class UserRepository : UserStore - public override async Task CreateAsync(ApplicationUser user, CancellationToken cancellationToken) - { - var u = await _context.AddAsync(user, cancellationToken); - if(u.State == EntityState.Added) - { - await SaveChanges(); - return IdentityResult.Success; - } - - return IdentityResult.Failed(); - } /// public override async Task UpdateAsync(ApplicationUser user, CancellationToken cancellationToken) @@ -154,6 +160,7 @@ public class UserRepository : UserStore u.Id.ToString() == id); return user; } + */ /// @@ -178,6 +185,7 @@ public class UserRepository : UserStore public override Task GetEmailAsync(ApplicationUser user, CancellationToken cancellationToken = default) { @@ -220,6 +228,6 @@ public class UserRepository : UserStore Industry { get; set; } + public DateTime CreationDate { get; set; } + } } diff --git a/BlueWest.Data.Capital/Company/CompanyCreate.cs b/BlueWest.Data.Capital/Company/CompanyCreate.cs index 1ac00a3..c65085a 100644 --- a/BlueWest.Data.Capital/Company/CompanyCreate.cs +++ b/BlueWest.Data.Capital/Company/CompanyCreate.cs @@ -15,6 +15,8 @@ namespace BlueWest.Data public Country OriginCountry { get; set; } public DateTime FoundingDate { get; set; } + + public DateTime CreateTime { get; } = DateTime.Now; } } diff --git a/BlueWest.Data.Capital/Country/Country.cs b/BlueWest.Data.Capital/Country/Country.cs index e0b7181..1da4fbb 100644 --- a/BlueWest.Data.Capital/Country/Country.cs +++ b/BlueWest.Data.Capital/Country/Country.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; @@ -33,6 +34,8 @@ namespace BlueWest.Data public List Currencies { get; set; } public List Users { get; set; } + public DateTime CreationDate { get; set; } + } } diff --git a/BlueWest.Data.Capital/Country/CountryCreate.cs b/BlueWest.Data.Capital/Country/CountryCreate.cs index 16823c2..c414af2 100644 --- a/BlueWest.Data.Capital/Country/CountryCreate.cs +++ b/BlueWest.Data.Capital/Country/CountryCreate.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MapTo; @@ -18,7 +19,8 @@ namespace BlueWest.Data public string Alpha2Code { get; set; } public string TLD { get; set; } - + public DateTime CreateTime { get; } = DateTime.Now; + } } diff --git a/BlueWest.Data.Capital/Currency/Currency.cs b/BlueWest.Data.Capital/Currency/Currency.cs index 66b2db2..4987321 100644 --- a/BlueWest.Data.Capital/Currency/Currency.cs +++ b/BlueWest.Data.Capital/Currency/Currency.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MapTo; @@ -16,6 +17,8 @@ namespace BlueWest.Data public int Num { get; set; } [MaxLength(3)] public string Code { get; set; } public List Countries { get; set; } + + public DateTime CreateDate { get; set; } } } diff --git a/BlueWest.Data.Capital/Currency/CurrencyUnique.cs b/BlueWest.Data.Capital/Currency/CurrencyUnique.cs index a8a9bfc..2024523 100644 --- a/BlueWest.Data.Capital/Currency/CurrencyUnique.cs +++ b/BlueWest.Data.Capital/Currency/CurrencyUnique.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MapTo; @@ -11,7 +12,8 @@ namespace BlueWest.Data public int Num { get; set; } // Primary key [MaxLength(3)] public string Code { get; set; } - + public DateTime CreateDate { get; set; } + } } diff --git a/BlueWest.Data.Capital/Industry/Industry.cs b/BlueWest.Data.Capital/Industry/Industry.cs index fe50b9d..546e1ba 100644 --- a/BlueWest.Data.Capital/Industry/Industry.cs +++ b/BlueWest.Data.Capital/Industry/Industry.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using MapTo; @@ -10,6 +11,9 @@ namespace BlueWest.Data public string IndustryName { get; set; } public Industry IndustryParent { get; set; } public List IndustryChilds { get; set; } + + public DateTime CreateDate { get; set; } + } } diff --git a/BlueWest.Data.Capital/Industry/IndustryUnique.cs b/BlueWest.Data.Capital/Industry/IndustryUnique.cs index 3cc9216..a1a8d21 100644 --- a/BlueWest.Data.Capital/Industry/IndustryUnique.cs +++ b/BlueWest.Data.Capital/Industry/IndustryUnique.cs @@ -1,3 +1,4 @@ +using System; using MapTo; namespace BlueWest.Data @@ -8,6 +9,9 @@ namespace BlueWest.Data public int Id { get; set; } public string IndustryName { get; set; } public Industry IndustryParent { get; set; } + + public DateTime CreateDate { get; set; } + } } diff --git a/BlueWest.Data.Capital/User/User.cs b/BlueWest.Data.Capital/User/User.cs index 9ab2d22..ceec788 100644 --- a/BlueWest.Data.Capital/User/User.cs +++ b/BlueWest.Data.Capital/User/User.cs @@ -10,6 +10,7 @@ namespace BlueWest.Data [UseUpdate] public partial class User { + public string ApplicationUserId { get; set; } public int Id { get; set; } public string Name { get; set; }