merge: feature-add-identity

commit 47c8a3e8e27fb8a71e702232c681d588fa152bc0
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 14:58:07 2021 +0100

    chore: register and login on the right

commit 3e32cd61c2436123887d78f4ae396577b378e53c
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 14:43:07 2021 +0100

    chore: add {Login,Register}ViewModel

commit f82f12a5328f1500c3a58dccb3728dc86d1cc92c
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 14:30:36 2021 +0100

    chore: libs and pkgs version bump

commit 202b06505c94817c7bc60b432a9320efce80afac
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 14:29:40 2021 +0100

    chore: local post-kaniko convenience chown

    * [skip ci]

commit 7e4c4ccbbf4f7290d47c4c682f09ee508b34ae1e
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 14:29:15 2021 +0100

    chore: add Manager on app start

commit 62e9d567c07794b821eb86e7dcff4ecbb6bbd47e
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 14:12:24 2021 +0100

    chore: add Login page

    * include FontAwesome (atm from CDN, will fetch it later and bundle it
      here)

commit 3c899a2d024d8b74c7e28dfd4b86e1332d964129
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 13:33:32 2021 +0100

    fix: use proper service provider

commit 88a6e0f45eae7d71cf352d01a693429246effd98
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 12:26:41 2021 +0100

    chore: do creation async + s/FirstName/Name/

commit eaed0ec13c0dd3824802a698ac9ed30bffc52de9
Author: surtur <a_mirre@utb.cz>
Date:   Thu Jan 28 10:55:23 2021 +0100

    fix: err creating admin

    * cause of silly passwd requirements - require {upper,lower}case and
      non-alphanumeric characters is implicitly set to true

commit f55f8517f8f8516192b5d156c71596e7fcc55ad2
Author: surtur <a_mirre@utb.cz>
Date:   Wed Jan 27 23:11:06 2021 +0100

    feat: table renames+call role-creating methods

    * no "AspNet" prefix
    * actually call Ensure{Admin,Roles}Created on app start

commit 20d3458f281ec9478dc9b0fab3795556dcd0a78f
Author: surtur <a_mirre@utb.cz>
Date:   Wed Jan 27 22:05:11 2021 +0100

    fix typo: DbContext --> DBContext

commit f972ac83e7197813bf4c9b4d9bb44d640b5dd071
Author: surtur <a_mirre@utb.cz>
Date:   Wed Jan 27 20:55:22 2021 +0100

    chore: add login and usr mgmt logic

    * add login and registration views
    * add methods to create admin user on app start

commit b65a6d21f8dc5227a8da2d5040348e269c2f3711
Author: surtur <a_mirre@utb.cz>
Date:   Wed Jan 27 16:02:33 2021 +0100

    chore: add auth options

    * FIXME dev fun settings need to be replaced with proper settings

commit 8f84939c22ec96e0a143350b9b9ba3d738dfc149
Author: surtur <a_mirre@utb.cz>
Date:   Wed Jan 27 14:54:57 2021 +0100

    chore: adding identity roles (batch 1)

    * preparing Startup and DBContext to work with roles and auth
    * added Roles enum
    * added User model
    * added Microsoft.AspNetCore.Identity.EntityFrameworkCore v3.1.10 nuget

    * note: auth is not ready and working yet, this is batch one of the
      preparations
This commit is contained in:
surtur 2021-01-28 15:27:25 +01:00
parent d2353d3851
commit 24a830b523
Signed by: wanderer
GPG Key ID: 19CE1EC1D9E0486D
16 changed files with 318 additions and 9 deletions

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace pwt_0x01_ng.Areas.Security.Controllers
{
[Area("Security")]
[AllowAnonymous]
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
public IActionResult Logout()
{
return View();
}
public IActionResult Register()
{
return View();
}
}
}

View File

@ -0,0 +1,52 @@
@{
ViewData["Title"] = "Login";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
<div class="container">
<div class="login">
<h3>Login or <a href="/Security/Account/Register">Sign up</a></h3>
<div class="row row-xs-offset-1 row-sm-offset-2">
<div class="col-xs-2 col-sm-2">
<a href="#" class="btn btn-lg btn-block btn-facebook" style="background: #172d5e;color: #fff;" data-toggle="tooltip" data-placement="top" title="Facebook">
<i class="fa fa-facebook fa-1x"></i>
</a>
</div>
<div class="col-xs-2 col-sm-2">
<a href="#" class="btn btn-lg btn-block btn-twitter" style="background: #043d52;color: #fff;" data-toggle="tooltip" data-placement="top" title="Twitter">
<i class="fa fa-twitter fa-1x"></i>
</a>
</div>
<div class="col-xs-2 col-sm-2">
<a href="#" class="btn btn-lg btn-block btn-github" style="background: #666666;color: #fff;" data-toggle="tooltip" data-placement="top" title="GitHub">
<i class="fa fa-github fa-1x"></i>
</a>
</div>
</div>
<br>
<div class="row row-sm-offset-3">
<div class="col-xs-12 col-sm-6">
<hr>
<span>or</span>
</div>
</div>
<div class="row row-sm-offset-3">
<div class="col-xs-12 col-sm-6">
<form class="loginForm" action="" autocomplete="off" method="POST">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
<hr />
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-key"></span></span>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<hr />
<button class="btn btn-lg btn-outline-primary" type="submit"><i class="fa fa-sign-in"></i> Login</button>
</form>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,7 @@
@{
ViewData["Title"] = "Register";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
<p>Register</p>

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -14,6 +14,7 @@ dargskaniko = -w=$(wdir) -v $$(pwd):$(wdir) $(kanikoimg)
kanikoargs = -c=$(wdir) --use-new-run --snapshotMode=redo --no-push
krelease = $(dcmdrun) $(dargskaniko) -f=$(dfile) $(kanikoargs)
kdebug = $(dcmdrun) $(dargskaniko) -f=$(dfiledev) $(kanikoargs)
postkanikochown = sudo chown -R $$USER:$$USER ./
pgdbcapdrop = --cap-drop NET_ADMIN --cap-drop SYS_ADMIN
pgdbenv = -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=679968312e029a806c1905c40ec331aa199a1eb86bd0b9eb04057933e449bdc9ef8ef292a39b68cafa5689c901a17266 -e POSTGRES_INITDB_ARGS="--data-checksums"
pgdbname = pgdb
@ -74,7 +75,9 @@ dcdevup:
kaniko:
$(krelease)
$(postkanikochown)
$(kdebug)
$(postkanikochown)
dockerdev: dockerdevbuild dockerdevrun

View File

@ -1,13 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Npgsql.EntityFrameworkCore;
using pwt_0x01_ng.Models;
using pwt_0x01_ng.Models.Identity;
using pwt_0x01_ng.Models.Database.Conf;
namespace pwt_0x01_ng.Models.Database
{
public class DBContext : DbContext
public class DBContext : IdentityDbContext<User, Role, int>
{
public DBContext(DbContextOptions<DBContext> options) : base(options)
{
@ -21,8 +25,13 @@ namespace pwt_0x01_ng.Models.Database
protected override void OnModelCreating(ModelBuilder model_builder)
{
base.OnModelCreating(model_builder);
this.ApplyConfiguration(model_builder);
foreach(var entity_type in model_builder.Model.GetEntityTypes()){
entity_type.SetTableName(entity_type.GetTableName().Replace("AspNet", string.Empty));
}
}
protected virtual void ApplyConfiguration(ModelBuilder model_builder)

View File

@ -1,8 +1,13 @@
using System;
using System.Linq;
using pwt_0x01_ng.Models.Database;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using pwt_0x01_ng.Models.Database;
using pwt_0x01_ng.Models;
using pwt_0x01_ng.Models.Identity;
namespace pwt_0x01_ng.Models.Database
{
@ -29,5 +34,90 @@ namespace pwt_0x01_ng.Models.Database
dbContext.SaveChanges();
}
}
public static async Task EnsureRolesCreated(IServiceProvider sp){
using (var services = sp.CreateScope()){
RoleManager<Role> role_manager = services.ServiceProvider.GetRequiredService<RoleManager<Role>>();
string[] rolespls = Enum.GetNames(typeof(Roles));
foreach (var role in rolespls){
// Console.WriteLine(role + " => " + role.GetType());
await role_manager.CreateAsync(new Role(role));
}
}
}
public static async Task EnsureManagerCreated(IServiceProvider sp){
using (var services = sp.CreateScope()){
UserManager<User> usr_manager = services.ServiceProvider.GetRequiredService<UserManager<User>>();
User manager = new User(){
UserName = "manager",
Email = "manager@manager.com",
Name = "manager",
LastName = "",
EmailConfirmed = true
};
var super_secure_password = "123"; /* TODO - rm this */
User manager_in_db = await usr_manager.FindByNameAsync(manager.UserName);
if (manager_in_db == null){
IdentityResult ir = new IdentityResult();
try {
ir = await usr_manager.CreateAsync(manager, super_secure_password);
} catch (Exception e){
Debug.WriteLine(e);
}
if(ir.Succeeded){
string[] rolespls = Enum.GetNames(typeof(Roles));
foreach (var role in rolespls){
if(role != Roles.Admin.ToString()){
await usr_manager.AddToRoleAsync(manager, role);
}
}
} else if (ir.Errors != null && ir.Errors.Count() >0){
foreach (var err in ir.Errors){
Debug.WriteLine("Error during manager role creation" + err.Code + " => " + err.Description);
}
}
}
}
}
public static async Task EnsureAdminCreated(IServiceProvider sp){
using (var services = sp.CreateScope()){
UserManager<User> usr_manager = services.ServiceProvider.GetRequiredService<UserManager<User>>();
User admin = new User(){
UserName = "admin",
Email = "admin@admin.com",
Name = "admin",
LastName = "",
EmailConfirmed = true
};
var super_secure_password = "123"; /* TODO - rm this */
User admin_in_db = await usr_manager.FindByNameAsync(admin.UserName);
if (admin_in_db == null){
IdentityResult ir = new IdentityResult();
try {
ir = await usr_manager.CreateAsync(admin, super_secure_password);
} catch (Exception e){
Debug.WriteLine(e);
}
if(ir.Succeeded){
string[] rolespls = Enum.GetNames(typeof(Roles));
foreach (var role in rolespls){
await usr_manager.AddToRoleAsync(admin, role);
}
} else if (ir.Errors != null && ir.Errors.Count() >0){
foreach (var err in ir.Errors){
Debug.WriteLine("Error during admin role creation" + err.Code + " => " + err.Description);
}
}
}
}
}
}
}

11
Models/Identity/Role.cs Normal file
View File

@ -0,0 +1,11 @@
using System;
using System.Security.Principal;
using Microsoft.AspNetCore.Identity;
namespace pwt_0x01_ng.Models.Identity
{
public class Role : IdentityRole<int>
{
public Role(string name) : base(){}
}
}

10
Models/Identity/Roles.cs Normal file
View File

@ -0,0 +1,10 @@
namespace pwt_0x01_ng.Models.Identity
{
public enum Roles
{
Admin,
Manager,
Customer
}
}

12
Models/Identity/User.cs Normal file
View File

@ -0,0 +1,12 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Identity;
namespace pwt_0x01_ng.Models.Identity
{
public class User : IdentityUser<int>
{
public virtual string Name {get; set;}
public virtual string LastName {get; set;}
}
}

12
Models/LoginViewModel.cs Normal file
View File

@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace pwt_0x01_ng.Models
{
public class LoginViewModel
{
[Required]
public string username {get; set;}
[Required]
public string password {get; set;}
public bool login_failed {get; set;}
}
}

View File

@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations;
using System.Runtime.InteropServices;
namespace pwt_0x01_ng.Models
{
public class RegisterViewModel
{
[Required]
public string username {get; set;}
[Required]
public string password {get; set;}
[Required]
[Compare(nameof(password), ErrorMessage = "Passwords don't match.")]
public string repeated_password {get; set;}
[Required]
public string email {get; set;}
}
}

View File

@ -14,7 +14,7 @@ namespace pwt_0x01_ng
{
public class Program
{
public static void Main(string[] args)
public static async Task Main(string[] args)
{
IWebHost webHost = CreateWebHostBuilder(args).Build();
@ -23,6 +23,9 @@ namespace pwt_0x01_ng
var serviceProvider = scope.ServiceProvider;
var dbctx = serviceProvider.GetRequiredService<DBContext>();
DBInit.Init(dbctx);
await DBInit.EnsureRolesCreated(serviceProvider);
await DBInit.EnsureManagerCreated(serviceProvider);
await DBInit.EnsureAdminCreated(serviceProvider);
}
webHost.Run();

View File

@ -7,9 +7,12 @@ using Microsoft.AspNetCore.CookiePolicy;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using pwt_0x01_ng.Models.Identity;
using pwt_0x01_ng.Models.Database;
using Microsoft.EntityFrameworkCore;
@ -47,6 +50,37 @@ namespace pwt_0x01_ng
);
services.AddIdentity<User, Role>().AddEntityFrameworkStores<DBContext>().AddDefaultTokenProviders();
services.Configure<IdentityOptions>(o =>
{
/* dev fun settings */
o.Password.RequireDigit = false;
o.Password.RequireUppercase = false;
o.Password.RequireLowercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequiredLength = 2;
o.Password.RequiredUniqueChars = 1;
o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1);
o.Lockout.MaxFailedAccessAttempts = 3;
o.Lockout.AllowedForNewUsers = false;
o.User.RequireUniqueEmail = true;
/* FIXME
* o.Password.RequireDigit = true;
* o.Password.RequiredLength = 18;
* o.Password.RequiredUniqueChars = 10;
* o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
* o.Lockout.MaxFailedAccessAttempts = 3;
* o.Lockout.AllowedForNewUsers = true;
* o.User.RequireUniqueEmail = true;
*/
});
services.ConfigureApplicationCookie(o => {
o.Cookie.HttpOnly = true;
o.ExpireTimeSpan = TimeSpan.FromDays(2);
o.SlidingExpiration = true;
o.LoginPath = "/Security/Account/Login";
o.LogoutPath = "/Security/Account/Logout";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddResponseCompression();
}
@ -66,6 +100,8 @@ namespace pwt_0x01_ng
app.UseStatusCodePagesWithReExecute("/Home/HandleError/{0}");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();

View File

@ -9,6 +9,7 @@
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css"/>
<link rel="stylesheet" href="~/css/site.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"/>
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
@ -53,6 +54,14 @@
<a asp-area="Admin" asp-controller="OrderItem" asp-action="Index">OrderItems</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="Security" asp-controller="Account" asp-action="Login">Login</a>
</li>
<li>
<a asp-area="Security" asp-controller="Account" asp-action="Register">Register</a>
</li>
</ul>
</div>
</div>
</nav>

View File

@ -13,21 +13,26 @@
<LaunchBrowser>false</LaunchBrowser>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.11" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.11" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.11" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.11" />
</ItemGroup>
<ItemGroup>
<Folder Include="Areas\Admin\Data" />
<Folder Include="Areas\Admin\Models" />
<Folder Include="Areas\Admin\Views" />
<Folder Include="Areas\Security\Data" />
<Folder Include="Areas\Security\Models" />
<Folder Include="Areas\Security\Views" />
<Folder Include="Migrations\pgsql" />
<Folder Include="Models\Database" />
<Folder Include="Models\Database\Conf" />
<Folder Include="Models\Identity" />
<Folder Include="Models\Validation" />
<Folder Include="wwwroot\images\carousels" />
<Folder Include="wwwroot\images\products" />