AspNetRoles ...
Some checks failed
Dotnet build and test / log-the-inputs (push) Successful in 48s
Dotnet build and test / build (push) Failing after 1m29s

This commit is contained in:
Paul Schneider
2025-07-31 11:44:02 +01:00
parent 27a55a1cc4
commit ac319f9994
16 changed files with 53 additions and 38 deletions

7
.vscode/tasks.json vendored
View File

@ -8,14 +8,11 @@
"type": "process", "type": "process",
"args": [ "args": [
"build", "build",
"/property:GenerateFullPaths=true", "/property:GenerateFullPaths=true"
"/consoleloggerparameters:NoSummary;ForceNoAlign",
], ],
"group": "build", "group": "build",
"isBuildCommand": true, "isBuildCommand": true,
"isTestCommand": false, "isTestCommand": false
"problemMatcher": "$msCompile"
}, },
{ {
"label": "build-web", "label": "build-web",

View File

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Chat; using Yavsc.Models.Chat;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
@ -45,7 +46,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != chatRoomAccess.UserId && uid != chatRoomAccess.Room.OwnerId if (uid != chatRoomAccess.UserId && uid != chatRoomAccess.Room.OwnerId
&& ! User.IsInRole(Constants.AdminGroupName)) && ! User.IsInMsRole(Constants.AdminGroupName))
{ {
ModelState.AddModelError("UserId","get refused"); ModelState.AddModelError("UserId","get refused");
@ -71,7 +72,7 @@ namespace Yavsc.Controllers
} }
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName ); var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName)) if (uid != room.OwnerId && ! User.IsInMsRole(Constants.AdminGroupName))
{ {
ModelState.AddModelError("ChannelName", "access put refused"); ModelState.AddModelError("ChannelName", "access put refused");
return BadRequest(ModelState); return BadRequest(ModelState);
@ -109,7 +110,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName ); var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (room == null || (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName))) if (room == null || (uid != room.OwnerId && ! User.IsInMsRole(Constants.AdminGroupName)))
{ {
ModelState.AddModelError("ChannelName", "access post refused"); ModelState.AddModelError("ChannelName", "access post refused");
return BadRequest(ModelState); return BadRequest(ModelState);
@ -153,7 +154,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName ); var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInRole(Constants.AdminGroupName))) if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInMsRole(Constants.AdminGroupName)))
{ {
ModelState.AddModelError("UserId", "access drop refused"); ModelState.AddModelError("UserId", "access drop refused");
return BadRequest(ModelState); return BadRequest(ModelState);

View File

@ -137,7 +137,7 @@ namespace Yavsc.Controllers
if (User.GetUserId() != chatRoom.OwnerId ) if (User.GetUserId() != chatRoom.OwnerId )
{ {
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInMsRole(Constants.AdminGroupName))
return BadRequest(new {error = "OwnerId"}); return BadRequest(new {error = "OwnerId"});
} }

View File

@ -19,5 +19,10 @@ namespace Yavsc.Server.Helpers
return user.Identity.IsAuthenticated; return user.Identity.IsAuthenticated;
} }
public static bool IsInMsRole(this ClaimsPrincipal user, string roleName)
{
return user.HasClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", roleName);
}
} }
} }

View File

@ -86,7 +86,7 @@ namespace Yavsc
var userId = _dbContext.Users.First(u => u.UserName == Context.User.Identity.Name).Id; var userId = _dbContext.Users.First(u => u.UserName == Context.User.Identity.Name).Id;
await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.Connected, userName, null); await Clients.Group(ChatHubConstants.HubGroupFollowingPrefix + userId).SendAsync("notifyUser", NotificationTypes.Connected, userName, null);
isCop = Context.User.IsInRole(Constants.AdminGroupName) ; isCop = Context.User.IsInMsRole(Constants.AdminGroupName) ;
if (isCop) if (isCop)
{ {
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.HubGroupCops); await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.HubGroupCops);
@ -353,7 +353,7 @@ namespace Yavsc
var identityUserName = Context.User.GetUserName(); var identityUserName = Context.User.GetUserName();
if (userName[0] != '?' && Context.User!=null) if (userName[0] != '?' && Context.User!=null)
if (!Context.User.IsInRole(Constants.AdminGroupName)) if (!Context.User.IsInMsRole(Constants.AdminGroupName))
{ {
var bl = _dbContext.BlackListed var bl = _dbContext.BlackListed

View File

@ -625,7 +625,7 @@ namespace Yavsc.Controllers
else _dbContext.Performers.Add(model); else _dbContext.Performers.Add(model);
_dbContext.SaveChanges(User.GetUserId()); _dbContext.SaveChanges(User.GetUserId());
// Give this user the Performer role // Give this user the Performer role
if (!User.IsInRole("Performer")) if (!User.IsInMsRole("Performer"))
await _userManager.AddToRoleAsync(user, "Performer"); await _userManager.AddToRoleAsync(user, "Performer");
var message = ManageMessageId.SetActivitySuccess; var message = ManageMessageId.SetActivitySuccess;

View File

@ -68,7 +68,7 @@ namespace Yavsc.Controllers
if (admins != null && admins.Count > 0) if (admins != null && admins.Count > 0)
{ {
// All is ok, nothing to do here. // All is ok, nothing to do here.
if (User.IsInRole(Constants.AdminGroupName)) if (User.IsInMsRole(Constants.AdminGroupName))
{ {
return Ok(new { message = "you already got it." }); return Ok(new { message = "you already got it." });

View File

@ -8,6 +8,7 @@ using Microsoft.Extensions.Localization;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
@ -58,8 +59,8 @@ namespace Yavsc.Controllers
} }
private async Task SetupView(Announce announce) private async Task SetupView(Announce announce)
{ {
ViewBag.IsAdmin = User.IsInRole(Constants.AdminGroupName); ViewBag.IsAdmin = User.IsInMsRole(Constants.AdminGroupName);
ViewBag.IsPerformer = User.IsInRole(Constants.PerformerGroupName); ViewBag.IsPerformer = User.IsInMsRole(Constants.PerformerGroupName);
ViewBag.AllowEdit = announce==null || announce.Id<=0 || !_authorizationService.AuthorizeAsync(User,announce,new EditPermission()).IsFaulted; ViewBag.AllowEdit = announce==null || announce.Id<=0 || !_authorizationService.AuthorizeAsync(User,announce,new EditPermission()).IsFaulted;
List<SelectListItem> dl = new List<SelectListItem>(); List<SelectListItem> dl = new List<SelectListItem>();
var rnames = System.Enum.GetNames(typeof(Reason)); var rnames = System.Enum.GetNames(typeof(Reason));
@ -78,7 +79,6 @@ namespace Yavsc.Controllers
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Announce announce) public async Task<IActionResult> Create(Announce announce)
{ {
await SetupView(announce);
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
// Only allow admin to create corporate annonces // Only allow admin to create corporate annonces
@ -99,6 +99,7 @@ namespace Yavsc.Controllers
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
await SetupView(announce);
return View(announce); return View(announce);
} }

View File

@ -74,7 +74,7 @@ namespace Yavsc.Controllers
{ {
var blog = await blogSpotService.Details(User, id.Value); var blog = await blogSpotService.Details(User, id.Value);
ViewData["apicmtctlr"] = "/api/blogcomments"; ViewData["apicmtctlr"] = "/api/blogcomments";
ViewData["moderatoFlag"] = User.IsInRole(Constants.BlogModeratorGroupName); ViewData["moderatoFlag"] = User.IsInMsRole(Constants.BlogModeratorGroupName);
return View(blog); return View(blog);

View File

@ -90,7 +90,7 @@ namespace Yavsc.Controllers
public IActionResult Create(UserActivity userActivity) public IActionResult Create(UserActivity userActivity)
{ {
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator")) if (!User.IsInMsRole("Administrator"))
if (uid != userActivity.UserId) if (uid != userActivity.UserId)
ModelState.AddModelError("User","You're not admin."); ModelState.AddModelError("User","You're not admin.");
if (userActivity.UserId == null) userActivity.UserId = uid; if (userActivity.UserId == null) userActivity.UserId = uid;
@ -133,7 +133,7 @@ namespace Yavsc.Controllers
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public IActionResult Edit(UserActivity userActivity) public IActionResult Edit(UserActivity userActivity)
{ {
if (!User.IsInRole("Administrator")) if (!User.IsInMsRole("Administrator"))
if (User.GetUserId() != userActivity.UserId) if (User.GetUserId() != userActivity.UserId)
ModelState.AddModelError("User","You're not admin."); ModelState.AddModelError("User","You're not admin.");
if (ModelState.IsValid) if (ModelState.IsValid)
@ -162,7 +162,7 @@ namespace Yavsc.Controllers
{ {
return NotFound(); return NotFound();
} }
if (!User.IsInRole("Administrator")) if (!User.IsInMsRole("Administrator"))
if (User.GetUserId() != userActivity.UserId) if (User.GetUserId() != userActivity.UserId)
ModelState.AddModelError("User","You're not admin."); ModelState.AddModelError("User","You're not admin.");
return View(userActivity); return View(userActivity);
@ -175,7 +175,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return new BadRequestObjectResult(ModelState); return new BadRequestObjectResult(ModelState);
if (!User.IsInRole("Administrator")) if (!User.IsInMsRole("Administrator"))
if (User.GetUserId() != userActivity.UserId) { if (User.GetUserId() != userActivity.UserId) {
ModelState.AddModelError("User","You're not admin."); ModelState.AddModelError("User","You're not admin.");
return RedirectToAction("Index"); return RedirectToAction("Index");

View File

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Musical; using Yavsc.Models.Musical;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
@ -60,7 +61,7 @@ namespace Yavsc.Controllers
ViewBag.YetAvailableInstruments = _context.Instrument.Select(k=>new SelectListItem ViewBag.YetAvailableInstruments = _context.Instrument.Select(k=>new SelectListItem
{ Text = k.Name, Value = k.Id.ToString(), Disabled = actual.Contains(k.Id) }); { Text = k.Name, Value = k.Id.ToString(), Disabled = actual.Contains(k.Id) });
if (User.IsInRole("Administrator")) if (User.IsInMsRole("Administrator"))
ViewBag.OwnerIds = new SelectList(_context.Performers, "PerformerId", "Profile"); ViewBag.OwnerIds = new SelectList(_context.Performers, "PerformerId", "Profile");
return View(); return View();
} }

View File

@ -64,7 +64,7 @@ namespace Yavsc.Controllers
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
if (model.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName)) if (model.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult(); return new ChallengeResult();
_context.Instrumentation.Add(model); _context.Instrumentation.Add(model);
@ -82,7 +82,7 @@ namespace Yavsc.Controllers
{ {
return NotFound(); return NotFound();
} }
if (id != uid) if (!User.IsInRole(Constants.AdminGroupName)) if (id != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult(); return new ChallengeResult();
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id); Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null) if (musicianSettings == null)
@ -98,7 +98,7 @@ namespace Yavsc.Controllers
public async Task<IActionResult> Edit(Instrumentation musicianSettings) public async Task<IActionResult> Edit(Instrumentation musicianSettings)
{ {
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (musicianSettings.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName)) if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult(); return new ChallengeResult();
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
@ -124,7 +124,7 @@ namespace Yavsc.Controllers
return NotFound(); return NotFound();
} }
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (musicianSettings.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName)) if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult(); return new ChallengeResult();
return View(musicianSettings); return View(musicianSettings);
} }
@ -137,7 +137,7 @@ namespace Yavsc.Controllers
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id); Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (musicianSettings.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName)) if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult(); return new ChallengeResult();

View File

@ -27,6 +27,7 @@ using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Protocols.Configuration; using Microsoft.IdentityModel.Protocols.Configuration;
using IdentityModel; using IdentityModel;
using Yavsc.Interfaces; using Yavsc.Interfaces;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Yavsc.Extensions; namespace Yavsc.Extensions;
@ -48,8 +49,9 @@ public static class HostingExtensions
_ = services.AddSingleton<IConnexionManager, HubConnectionManager>(); _ = services.AddSingleton<IConnexionManager, HubConnectionManager>();
_ = services.AddSingleton<ILiveProcessor, LiveProcessor>(); _ = services.AddSingleton<ILiveProcessor, LiveProcessor>();
_ = services.AddTransient<IFileSystemAuthManager, FileSystemAuthManager>(); _ = services.AddTransient<IFileSystemAuthManager, FileSystemAuthManager>();
AddIdentityDBAndStores(builder).AddDefaultTokenProviders(); AddIdentityDBAndStores(builder)
.AddDefaultTokenProviders();
AddIdentityServer(builder); AddIdentityServer(builder);
services.AddSignalR(o => services.AddSignalR(o =>
@ -107,7 +109,9 @@ public static class HostingExtensions
AddAuthentication(builder); AddAuthentication(builder);
// accepts any access token issued by identity server
services.AddTransient<RoleManager<IdentityRole>>();
services.AddTransient<IRoleStore<IdentityRole>, RoleStore<IdentityRole, ApplicationDbContext>>();
return builder.Build(); return builder.Build();
} }
@ -118,13 +122,15 @@ public static class HostingExtensions
services.AddDbContext<ApplicationDbContext>(options => services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))); options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
return services.AddIdentity<ApplicationUser, IdentityRole>( return services.AddIdentity<ApplicationUser,IdentityRole>(
options => options =>
{ {
options.SignIn.RequireConfirmedAccount = true; options.SignIn.RequireConfirmedAccount = true;
options.ClaimsIdentity.UserNameClaimType = JwtClaimTypes.PreferredUserName;
options.ClaimsIdentity.RoleClaimType = JwtClaimTypes.Role;
} }
) )
.AddEntityFrameworkStores<ApplicationDbContext>(); .AddEntityFrameworkStores<ApplicationDbContext>();
} }
@ -226,13 +232,16 @@ public static class HostingExtensions
// see https://IdentityServer8.readthedocs.io/en/latest/topics/resources.html // see https://IdentityServer8.readthedocs.io/en/latest/topics/resources.html
options.EmitStaticAudienceClaim = true; options.EmitStaticAudienceClaim = true;
}) })
.AddInMemoryIdentityResources(Config.IdentityResources) .AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryClients(Config.TestingClients) .AddInMemoryClients(Config.TestingClients)
.AddClientStore<ClientStore>() .AddClientStore<ClientStore>()
.AddInMemoryApiScopes(Config.TestingApiScopes) .AddInMemoryApiScopes(Config.TestingApiScopes)
.AddAspNetIdentity<ApplicationUser>() .AddAspNetIdentity<ApplicationUser>();
;
if (builder.Environment.IsDevelopment()) if (builder.Environment.IsDevelopment())
{ {
identityServerBuilder.AddDeveloperSigningCredential(); identityServerBuilder.AddDeveloperSigningCredential();

View File

@ -35,7 +35,7 @@ public class PermissionHandler : IAuthorizationHandler
{ {
context.Succeed(requirement); context.Succeed(requirement);
} }
else if (context.User.IsInRole("Administrator")) else if (context.User.IsInMsRole("Administrator"))
{ {
context.Succeed(requirement); context.Succeed(requirement);
} }

View File

@ -10,7 +10,7 @@
<div class="form-horizontal"> <div class="form-horizontal">
<h4>Announce</h4> <h4>Announce</h4>
<hr /> <hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div> <div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group"> <div class="form-group">
<label asp-for="For" class="col-md-2 control-label"></label> <label asp-for="For" class="col-md-2 control-label"></label>

View File

@ -14,13 +14,14 @@
<li><a class="dropdown-item" asp-controller="Feature" asp-action="Index">Features</a></li> <li><a class="dropdown-item" asp-controller="Feature" asp-action="Index">Features</a></li>
</ul> </ul>
</li> </li>
@if (User.IsInRole(Constants.AdminGroupName)) { @if (User.IsInMsRole(Constants.AdminGroupName)) {
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdown05" data-bs-toggle="dropdown" aria-expanded="false"> <a class="nav-link dropdown-toggle" href="#" id="dropdown05" data-bs-toggle="dropdown" aria-expanded="false">
Administration Administration
</a> </a>
<ul class="dropdown-menu" aria-labelledby="dropdown05"> <ul class="dropdown-menu" aria-labelledby="dropdown05">
<li><a class="dropdown-item" asp-controller="Administration" asp-action="Index">Index</a></li> <li><a class="dropdown-item" asp-controller="Administration" asp-action="Index">Index</a></li>
<li><a class="dropdown-item" asp-controller="Announces" asp-action="Index">Announces</a></li>
<li><a class="dropdown-item" asp-controller="Activity" asp-action="Index">Activités</a></li> <li><a class="dropdown-item" asp-controller="Activity" asp-action="Index">Activités</a></li>
<li><a class="dropdown-item" asp-controller="CommandForms" asp-action="Index">Formulaires</a></li> <li><a class="dropdown-item" asp-controller="CommandForms" asp-action="Index">Formulaires</a></li>
<li><a class="dropdown-item" asp-controller="Notifications" asp-action="Index">Notifications</a></li> <li><a class="dropdown-item" asp-controller="Notifications" asp-action="Index">Notifications</a></li>