diff --git a/.gitignore b/.gitignore index 8d4a6c0..7f48411 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,403 @@ -bin -obj \ No newline at end of file +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ +docs/ + +# Docker +.env \ No newline at end of file diff --git a/Data/ApplicationDbContext.cs b/Data/ApplicationDbContext.cs index e9f3699..ab14430 100644 --- a/Data/ApplicationDbContext.cs +++ b/Data/ApplicationDbContext.cs @@ -3,38 +3,34 @@ using Microsoft.EntityFrameworkCore; using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Data +namespace UserManagementUiDemo.Data; + +public class ApplicationDbContext(DbContextOptions options) : IdentityDbContext(options) { - public class ApplicationDbContext : IdentityDbContext + protected override void OnModelCreating(ModelBuilder builder) { - public ApplicationDbContext(DbContextOptions options) - : base(options) - { - } + base.OnModelCreating(builder); + + builder + .Entity() + .HasMany(user => user.UserClaims) + .WithOne() + .HasForeignKey(claim => claim.UserId); - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - builder - .Entity() - .HasMany(user => user.UserClaims) - .WithOne() - .HasForeignKey(claim => claim.UserId); - builder - .Entity() - .HasMany(user => user.Roles) - .WithMany(role => role.Users) - .UsingEntity>( - builder => builder.HasOne().WithMany().HasForeignKey(userRole => userRole.RoleId), - builder => builder.HasOne().WithMany().HasForeignKey(userRole => userRole.UserId), - builder => builder.ToTable("AspNetUserRoles") - ); - builder - .Entity() - .HasMany(role => role.RoleClaims) - .WithOne() - .HasForeignKey(claim => claim.RoleId); + builder + .Entity() + .HasMany(user => user.Roles) + .WithMany(role => role.Users) + .UsingEntity>( + builder => builder.HasOne().WithMany().HasForeignKey(userRole => userRole.RoleId), + builder => builder.HasOne().WithMany().HasForeignKey(userRole => userRole.UserId), + builder => builder.ToTable("AspNetUserRoles") + ); - } + builder + .Entity() + .HasMany(role => role.RoleClaims) + .WithOne() + .HasForeignKey(claim => claim.RoleId); } -} +} \ No newline at end of file diff --git a/Data/app.db b/Data/app.db index f381261..0747566 100644 Binary files a/Data/app.db and b/Data/app.db differ diff --git a/Models/Authorization/PermissionAuthorizationHandler.cs b/Models/Authorization/PermissionAuthorizationHandler.cs index b9a9891..4a03119 100644 --- a/Models/Authorization/PermissionAuthorizationHandler.cs +++ b/Models/Authorization/PermissionAuthorizationHandler.cs @@ -1,32 +1,30 @@ -using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using UserManagementUiDemo.Models.Enums; -namespace UserManagementUiDemo.Models.Authorization +namespace UserManagementUiDemo.Models.Authorization; + +// Source: https://codewithmukesh.com/blog/permission-based-authorization-in-aspnet-core +public class PermissionAuthorizationHandler : AuthorizationHandler { - // Source: https://codewithmukesh.com/blog/permission-based-authorization-in-aspnet-core - public class PermissionAuthorizationHandler : AuthorizationHandler + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) + if (context.User?.Identity.IsAuthenticated != true) { - if (context.User?.Identity.IsAuthenticated != true) - { - context.Fail(); - return Task.CompletedTask; - } - - var hasPermission = context.User.HasClaim(nameof(Permission), requirement.Permission); - if (hasPermission) - { - context.Succeed(requirement); - } - else - { - context.Fail(); - } - + context.Fail(); return Task.CompletedTask; } + + var hasPermission = context.User.HasClaim(nameof(Permission), requirement.Permission); + if (hasPermission) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + + return Task.CompletedTask; } } \ No newline at end of file diff --git a/Models/Authorization/PermissionPolicyProvider.cs b/Models/Authorization/PermissionPolicyProvider.cs index 88e711d..0a2c012 100644 --- a/Models/Authorization/PermissionPolicyProvider.cs +++ b/Models/Authorization/PermissionPolicyProvider.cs @@ -5,28 +5,24 @@ using Microsoft.Extensions.Options; using UserManagementUiDemo.Models.Enums; -namespace UserManagementUiDemo.Models.Authorization +namespace UserManagementUiDemo.Models.Authorization; +// Source: https://codewithmukesh.com/blog/permission-based-authorization-in-aspnet-core +public class PermissionPolicyProvider(IOptions options) : IAuthorizationPolicyProvider { - // Source: https://codewithmukesh.com/blog/permission-based-authorization-in-aspnet-core - public class PermissionPolicyProvider : IAuthorizationPolicyProvider + public DefaultAuthorizationPolicyProvider FallbackPolicyProvider { get; } = new DefaultAuthorizationPolicyProvider(options); + + public Task GetDefaultPolicyAsync() => FallbackPolicyProvider.GetDefaultPolicyAsync(); + + public Task GetPolicyAsync(string policyName) { - public DefaultAuthorizationPolicyProvider FallbackPolicyProvider { get; } - public PermissionPolicyProvider(IOptions options) - { - FallbackPolicyProvider = new DefaultAuthorizationPolicyProvider(options); - } - public Task GetDefaultPolicyAsync() => FallbackPolicyProvider.GetDefaultPolicyAsync(); - public Task GetPolicyAsync(string policyName) + if (Enum.GetNames().Contains(policyName)) { - if (Enum.GetNames().Contains(policyName)) - { - AuthorizationPolicyBuilder policy = new(); - policy.AddRequirements(new PermissionRequirement(policyName)); - return Task.FromResult(policy.Build()); - } - return FallbackPolicyProvider.GetPolicyAsync(policyName); + AuthorizationPolicyBuilder policy = new(); + policy.AddRequirements(new PermissionRequirement(policyName)); + return Task.FromResult(policy.Build()); } - public Task GetFallbackPolicyAsync() => FallbackPolicyProvider.GetDefaultPolicyAsync(); + return FallbackPolicyProvider.GetPolicyAsync(policyName); } + public Task GetFallbackPolicyAsync() => FallbackPolicyProvider.GetDefaultPolicyAsync(); } \ No newline at end of file diff --git a/Models/Authorization/PermissionRequirement.cs b/Models/Authorization/PermissionRequirement.cs index d95f54d..9d9a098 100644 --- a/Models/Authorization/PermissionRequirement.cs +++ b/Models/Authorization/PermissionRequirement.cs @@ -1,15 +1,9 @@ using Microsoft.AspNetCore.Authorization; -namespace UserManagementUiDemo.Models.Authorization +namespace UserManagementUiDemo.Models.Authorization; + +// Source: https://codewithmukesh.com/blog/permission-based-authorization-in-aspnet-core +public class PermissionRequirement(string permission) : IAuthorizationRequirement { - // Source: https://codewithmukesh.com/blog/permission-based-authorization-in-aspnet-core - public class PermissionRequirement : IAuthorizationRequirement - { - public PermissionRequirement(string permission) - { - Permission = permission; - } - - public string Permission { get; private set; } - } + public string Permission { get; private set; } = permission; } \ No newline at end of file diff --git a/Models/Entities/ApplicationRole.cs b/Models/Entities/ApplicationRole.cs index 3cc988b..8693819 100644 --- a/Models/Entities/ApplicationRole.cs +++ b/Models/Entities/ApplicationRole.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Identity; -namespace UserManagementUiDemo.Models.Entities +namespace UserManagementUiDemo.Models.Entities; + +public class ApplicationRole : IdentityRole { - public class ApplicationRole : IdentityRole - { - public string Description { get; set; } - public ICollection> RoleClaims { get; set; } - public ICollection Users { get; set; } - } + public string Description { get; set; } + public ICollection> RoleClaims { get; set; } + public ICollection Users { get; set; } } \ No newline at end of file diff --git a/Models/Entities/ApplicationUser.cs b/Models/Entities/ApplicationUser.cs index 9cda6fe..28ef2f5 100644 --- a/Models/Entities/ApplicationUser.cs +++ b/Models/Entities/ApplicationUser.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Identity; -namespace UserManagementUiDemo.Models.Entities +namespace UserManagementUiDemo.Models.Entities; + +public class ApplicationUser : IdentityUser { - public class ApplicationUser : IdentityUser - { - public string FullName { get; set; } - public ICollection> UserClaims { get; set; } - public ICollection Roles { get; set; } - } + public string FullName { get; set; } + public ICollection> UserClaims { get; set; } + public ICollection Roles { get; set; } } \ No newline at end of file diff --git a/Models/Enums/Permission.cs b/Models/Enums/Permission.cs index c4ef55d..0939e74 100644 --- a/Models/Enums/Permission.cs +++ b/Models/Enums/Permission.cs @@ -1,10 +1,9 @@ -namespace UserManagementUiDemo.Models.Enums +namespace UserManagementUiDemo.Models.Enums; + +public enum Permission { - public enum Permission - { - Operation1, - Operation2, - Operation3, - UserManagement - } + Operation1, + Operation2, + Operation3, + UserManagement } \ No newline at end of file diff --git a/Models/InputModels/EditClaimInputModel.cs b/Models/InputModels/EditClaimInputModel.cs index 03b0c4d..fd3a297 100644 --- a/Models/InputModels/EditClaimInputModel.cs +++ b/Models/InputModels/EditClaimInputModel.cs @@ -1,25 +1,22 @@ -using System; using System.ComponentModel.DataAnnotations; using System.Security.Claims; -using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Models.InputModels +namespace UserManagementUiDemo.Models.InputModels; + +public class EditClaimInputModel { - public class EditClaimInputModel - { - [Required(ErrorMessage = "Il claim type è obbligatorio"), - MaxLength(255, ErrorMessage = "Il claim type è troppo lungo"), - Display(Name = "Claim Type")] - public string Type { get; set; } + [Required(ErrorMessage = "Il claim type è obbligatorio"), + MaxLength(255, ErrorMessage = "Il claim type è troppo lungo"), + Display(Name = "Claim Type")] + public string Type { get; set; } - [MaxLength(255, ErrorMessage = "Il claim value è troppo lungo"), - Display(Name = "Claim Value")] - public string Value { get; set; } + [MaxLength(255, ErrorMessage = "Il claim value è troppo lungo"), + Display(Name = "Claim Value")] + public string Value { get; set; } - public Claim ToClaim() - { - return new(Type, Value ?? string.Empty); - } + public Claim ToClaim() + { + return new(Type, Value ?? string.Empty); } -} \ No newline at end of file +} diff --git a/Models/InputModels/EditRoleInputModel.cs b/Models/InputModels/EditRoleInputModel.cs index 438917d..43889de 100644 --- a/Models/InputModels/EditRoleInputModel.cs +++ b/Models/InputModels/EditRoleInputModel.cs @@ -3,14 +3,13 @@ using System.Security.Claims; using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Models.InputModels +namespace UserManagementUiDemo.Models.InputModels; + +public class EditRoleInputModel { - public class EditRoleInputModel - { - [Required(ErrorMessage = "Il nome del ruolo è obbligatorio"), - MaxLength(255, ErrorMessage = "Il nome del ruolo è troppo lungo"), - Display(Name = "Nome del ruolo")] - public string Name { get; set; } - } -} \ No newline at end of file + [Required(ErrorMessage = "Il nome del ruolo è obbligatorio"), + MaxLength(255, ErrorMessage = "Il nome del ruolo è troppo lungo"), + Display(Name = "Nome del ruolo")] + public string Name { get; set; } +} diff --git a/Models/InputModels/RoleCreateInputModel.cs b/Models/InputModels/RoleCreateInputModel.cs index 7d36bb9..9f75eeb 100644 --- a/Models/InputModels/RoleCreateInputModel.cs +++ b/Models/InputModels/RoleCreateInputModel.cs @@ -2,22 +2,21 @@ using Microsoft.AspNetCore.Identity; using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Models.InputModels +namespace UserManagementUiDemo.Models.InputModels; + +public class RoleCreateInputModel { - public class RoleCreateInputModel - { - [Required(ErrorMessage = "Il nome è obbligatorio"), - MaxLength(255, ErrorMessage = "Il nome è troppo lungo"), - Display(Name = "Nome")] - public string Name { get; set; } + [Required(ErrorMessage = "Il nome è obbligatorio"), + MaxLength(255, ErrorMessage = "Il nome è troppo lungo"), + Display(Name = "Nome")] + public string Name { get; set; } - public ApplicationRole ToApplicationRole() + public ApplicationRole ToApplicationRole() + { + ApplicationRole role = new() { - ApplicationRole role = new() - { - Name = Name - }; - return role; - } + Name = Name + }; + return role; } } \ No newline at end of file diff --git a/Models/InputModels/RoleEditInfoInputModel.cs b/Models/InputModels/RoleEditInfoInputModel.cs index 9800cab..06e74d9 100644 --- a/Models/InputModels/RoleEditInfoInputModel.cs +++ b/Models/InputModels/RoleEditInfoInputModel.cs @@ -3,31 +3,30 @@ using Microsoft.AspNetCore.Identity; using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Models.InputModels +namespace UserManagementUiDemo.Models.InputModels; + +public class RoleEditInfoInputModel { - public class RoleEditInfoInputModel - { - [Required(ErrorMessage = "Il nome è obbligatorio"), - MaxLength(255, ErrorMessage = "Il nome è troppo lungo"), - Display(Name = "Nome completo")] - public string Name { get; set; } + [Required(ErrorMessage = "Il nome è obbligatorio"), + MaxLength(255, ErrorMessage = "Il nome è troppo lungo"), + Display(Name = "Nome completo")] + public string Name { get; set; } - [Display(Name = "Descrizione (opzionale)"), - MaxLength(255, ErrorMessage = "La descrizione è troppo lunga")] - public string Description { get; set; } - public void CopyToApplicationRole(ApplicationRole role) - { - role.Name = Name; - role.Description = Description; - } + [Display(Name = "Descrizione (opzionale)"), + MaxLength(255, ErrorMessage = "La descrizione è troppo lunga")] + public string Description { get; set; } + public void CopyToApplicationRole(ApplicationRole role) + { + role.Name = Name; + role.Description = Description; + } - public static RoleEditInfoInputModel FromApplicationRole(ApplicationRole role) + public static RoleEditInfoInputModel FromApplicationRole(ApplicationRole role) + { + return new RoleEditInfoInputModel { - return new RoleEditInfoInputModel - { - Name = role.Name, - Description = role.Description - }; - } + Name = role.Name, + Description = role.Description + }; } } \ No newline at end of file diff --git a/Models/InputModels/UserCreateInputModel.cs b/Models/InputModels/UserCreateInputModel.cs index d466b11..1dfdae6 100644 --- a/Models/InputModels/UserCreateInputModel.cs +++ b/Models/InputModels/UserCreateInputModel.cs @@ -2,51 +2,49 @@ using Microsoft.AspNetCore.Identity; using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Models.InputModels +namespace UserManagementUiDemo.Models.InputModels; + +public class UserCreateInputModel { - public class UserCreateInputModel - { - [Required(ErrorMessage = "Il nome completo è obbligatorio"), - MaxLength(255, ErrorMessage = "Il nome completo è troppo lungo"), - Display(Name = "Nome completo")] - public string FullName { get; set; } + [Required(ErrorMessage = "Il nome completo è obbligatorio"), + MaxLength(255, ErrorMessage = "Il nome completo è troppo lungo"), + Display(Name = "Nome completo")] + public string FullName { get; set; } - [Required(ErrorMessage = "L'email è obbligatoria"), - MaxLength(255, ErrorMessage = "L'email è troppo lunga"), - EmailAddress(ErrorMessage = "L'indirizzo email non è valido"), - Display(Name = "Email")] - public string Email { get; set; } + [Required(ErrorMessage = "L'email è obbligatoria"), + MaxLength(255, ErrorMessage = "L'email è troppo lunga"), + EmailAddress(ErrorMessage = "L'indirizzo email non è valido"), + Display(Name = "Email")] + public string Email { get; set; } - [Required(ErrorMessage = "La password è obbligatoria"), - RegularExpression("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{8,15}$", ErrorMessage = "La password deve essere lunga tra 8 e 15 caratteri e contenere almeno una maiuscola, una minuscola, un numero e un simbolo"), - Display(Name = "Password")] - public string Password { get; set; } + [Required(ErrorMessage = "La password è obbligatoria"), + RegularExpression("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{8,15}$", ErrorMessage = "La password deve essere lunga tra 8 e 15 caratteri e contenere almeno una maiuscola, una minuscola, un numero e un simbolo"), + Display(Name = "Password")] + public string Password { get; set; } - [Required(ErrorMessage = "La conferma password è obbligatoria"), - Compare(nameof(Password), ErrorMessage = "Le password non corrispondono"), - Display(Name = "Conferma password")] - public string ConfirmPassword { get; set; } + [Required(ErrorMessage = "La conferma password è obbligatoria"), + Compare(nameof(Password), ErrorMessage = "Le password non corrispondono"), + Display(Name = "Conferma password")] + public string ConfirmPassword { get; set; } - public ApplicationUser ToApplicationUser(UserManager userManager) + public ApplicationUser ToApplicationUser(UserManager userManager) + { + ApplicationUser user = new() { - ApplicationUser user = new() - { - FullName = FullName, - Email = Email, - UserName = Email, - // In questa demo, gli utenti creati dalle pagine di amministrazione - // si troveranno già con l'email confermata, così che possano subito - // fare il login - EmailConfirmed = true, - // L'account verrà bloccato automaticamente dopo un certo numero di - // tentantivi di login falliti. Puoi configurare i parametri di Lockout - // (es. numero di tentantivi, durata del blocco) nella chiamata a - // AddDefaultIdentity che si trova nella classe Startup. - LockoutEnabled = true - }; + FullName = FullName, + Email = Email, + UserName = Email, + // In questa demo, gli utenti creati dalle pagine di amministrazione si + // troveranno già con l'email confermata, così che possano subito fare il login + EmailConfirmed = true, + // L'account verrà bloccato automaticamente dopo un certo numero di tentantivi + // di login falliti. Puoi configurare i parametri di Lockout (es. numero di + // tentantivi, durata del blocco) nella chiamata a AddDefaultIdentity che si + // trova nella classe Startup. + LockoutEnabled = true + }; - user.PasswordHash = userManager.PasswordHasher.HashPassword(user, Password); - return user; - } + user.PasswordHash = userManager.PasswordHasher.HashPassword(user, Password); + return user; } } \ No newline at end of file diff --git a/Models/InputModels/UserEditProfileInputModel.cs b/Models/InputModels/UserEditProfileInputModel.cs index 2f5799d..02232fc 100644 --- a/Models/InputModels/UserEditProfileInputModel.cs +++ b/Models/InputModels/UserEditProfileInputModel.cs @@ -3,51 +3,50 @@ using Microsoft.AspNetCore.Identity; using UserManagementUiDemo.Models.Entities; -namespace UserManagementUiDemo.Models.InputModels +namespace UserManagementUiDemo.Models.InputModels; + +public class UserEditProfileInputModel { - public class UserEditProfileInputModel - { - [Required(ErrorMessage = "Il nome completo è obbligatorio"), - MaxLength(255, ErrorMessage = "Il nome completo è troppo lungo"), - Display(Name = "Nome completo")] - public string FullName { get; set; } + [Required(ErrorMessage = "Il nome completo è obbligatorio"), + MaxLength(255, ErrorMessage = "Il nome completo è troppo lungo"), + Display(Name = "Nome completo")] + public string FullName { get; set; } - [Required(ErrorMessage = "L'email è obbligatoria"), - MaxLength(255, ErrorMessage = "L'email è troppo lunga"), - EmailAddress(ErrorMessage = "L'indirizzo email non è valido"), - Display(Name = "Email")] - public string Email { get; set; } + [Required(ErrorMessage = "L'email è obbligatoria"), + MaxLength(255, ErrorMessage = "L'email è troppo lunga"), + EmailAddress(ErrorMessage = "L'indirizzo email non è valido"), + Display(Name = "Email")] + public string Email { get; set; } - [RegularExpression("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{8,15}$", ErrorMessage = "La password deve essere lunga tra 8 e 15 caratteri e contenere almeno una maiuscola, una minuscola, un numero e un simbolo"), - Display(Name = "Reimposta password")] - public string Password { get; set; } + [RegularExpression("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{8,15}$", ErrorMessage = "La password deve essere lunga tra 8 e 15 caratteri e contenere almeno una maiuscola, una minuscola, un numero e un simbolo"), + Display(Name = "Reimposta password")] + public string Password { get; set; } - [Compare(nameof(Password), ErrorMessage = "Le password non corrispondono"), - Display(Name = "Conferma password")] - public string ConfirmPassword { get; set; } + [Compare(nameof(Password), ErrorMessage = "Le password non corrispondono"), + Display(Name = "Conferma password")] + public string ConfirmPassword { get; set; } - [Display(Name = "Blocca l'account (non potrà fare il login) fino al")] - public DateTimeOffset? LockoutEnd { get; set; } + [Display(Name = "Blocca l'account (non potrà fare il login) fino al")] + public DateTimeOffset? LockoutEnd { get; set; } - public void CopyToApplicationUser(UserManager userManager, ApplicationUser user) + public void CopyToApplicationUser(UserManager userManager, ApplicationUser user) + { + user.FullName = FullName; + user.Email = Email; + user.LockoutEnd = LockoutEnd; + if (Password is not null and not "") { - user.FullName = FullName; - user.Email = Email; - user.LockoutEnd = LockoutEnd; - if (Password is not null and not "") - { - user.PasswordHash = userManager.PasswordHasher.HashPassword(user, Password); - } + user.PasswordHash = userManager.PasswordHasher.HashPassword(user, Password); } + } - public static UserEditProfileInputModel FromApplicationUser(ApplicationUser user) + public static UserEditProfileInputModel FromApplicationUser(ApplicationUser user) + { + return new UserEditProfileInputModel { - return new UserEditProfileInputModel - { - FullName = user.FullName, - Email = user.Email, - LockoutEnd = user.LockoutEnd - }; - } + FullName = user.FullName, + Email = user.Email, + LockoutEnd = user.LockoutEnd + }; } } \ No newline at end of file diff --git a/Models/ViewModels/UserListViewModel.cs b/Models/ViewModels/UserListViewModel.cs index b1d069e..ddfd2c9 100644 --- a/Models/ViewModels/UserListViewModel.cs +++ b/Models/ViewModels/UserListViewModel.cs @@ -1,7 +1,4 @@ -namespace UserManagementUiDemo.Models.ViewModels -{ - public class UserListViewModel - { - - } -} \ No newline at end of file +namespace UserManagementUiDemo.Models.ViewModels; + +public class UserListViewModel +{ } \ No newline at end of file diff --git a/Program.cs b/Program.cs index 3207367..3063957 100644 --- a/Program.cs +++ b/Program.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -namespace UserManagementUiDemo +namespace UserManagementUiDemo; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + CreateHostBuilder(args).Build().Run(); } -} + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); +} \ No newline at end of file diff --git a/README.md b/README.md index 72ce4de..1a68d41 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # User Management UI Demo -Applicazione ASP.NET Core 5 che dimostra come usare il `RoleManager` per creare ruoli e assegnarli agli utenti. A ciascun ruolo possono essere assegnati dei claim. + +Applicazione ASP.NET Core 8 che dimostra come usare il `RoleManager` per creare ruoli e assegnarli agli utenti. A ciascun ruolo possono essere assegnati dei claim. > Visita anche il ramo GIT `UserManager` per scoprire come assegnare ruoli agli utenti usando semplicemente il servizio `UserManager`. diff --git a/Startup.cs b/Startup.cs index 6108071..79de085 100644 --- a/Startup.cs +++ b/Startup.cs @@ -1,12 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using UserManagementUiDemo.Data; using Microsoft.Extensions.Configuration; @@ -16,70 +11,66 @@ using Microsoft.AspNetCore.Authorization; using UserManagementUiDemo.Models.Authorization; -namespace UserManagementUiDemo +namespace UserManagementUiDemo; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + Configuration = configuration; + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) + public void ConfigureServices(IServiceCollection services) + { + services.AddDbContext(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); + services.AddDatabaseDeveloperPageExceptionFilter(); + services.AddSingleton(); + services.AddScoped(); + + services.AddDefaultIdentity(options => { - services.AddDbContext(options => - options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); - services.AddDatabaseDeveloperPageExceptionFilter(); - services.AddSingleton(); - services.AddScoped(); + options.SignIn.RequireConfirmedAccount = true; + options.Lockout.MaxFailedAccessAttempts = 5; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); + options.Lockout.AllowedForNewUsers = true; + }) + .AddRoles() + .AddRoleManager>() + .AddEntityFrameworkStores(); - services - .AddDefaultIdentity(options => - { - options.SignIn.RequireConfirmedAccount = true; - options.Lockout.MaxFailedAccessAttempts = 5; - options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); - options.Lockout.AllowedForNewUsers = true; - }) - .AddRoles() - .AddRoleManager>() - .AddEntityFrameworkStores(); - services.AddControllersWithViews(); - services.AddRazorPages(); - } + services.AddControllersWithViews(); + services.AddRazorPages(); + } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + app.UseMigrationsEndPoint(); + } + else { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - app.UseMigrationsEndPoint(); - } - else - { - app.UseExceptionHandler("/Home/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - app.UseHttpsRedirection(); - app.UseStaticFiles(); + app.UseExceptionHandler("/Home/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); + } + app.UseHttpsRedirection(); + app.UseStaticFiles(); - app.UseRouting(); + app.UseRouting(); - app.UseAuthentication(); - app.UseAuthorization(); + app.UseAuthentication(); + app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=Index}/{id?}"); - endpoints.MapRazorPages(); - }); - } + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapRazorPages(); + }); } -} +} \ No newline at end of file diff --git a/UserManagementUiDemo.csproj b/UserManagementUiDemo.csproj index 7b7fe82..75fdce5 100644 --- a/UserManagementUiDemo.csproj +++ b/UserManagementUiDemo.csproj @@ -1,7 +1,7 @@ - net5.0 + net8.0 aspnet-UserManagementUiDemo-FEFFD83C-ED76-4F71-9F42-659194570E5E @@ -10,11 +10,14 @@ - - - - - + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all +