Files
mixtape/zero.Core/Identity/Security/ZeroBackofficeClaimsPrincipalFactory.cs
T

75 lines
2.5 KiB
C#
Raw Normal View History

2021-11-19 16:11:12 +01:00
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Security.Claims;
2021-11-20 13:52:28 +01:00
namespace zero.Identity;
2021-11-19 16:11:12 +01:00
public class ZeroBackofficeClaimsPrincipalFactory<TUser, TRole> : ZeroClaimsPrinicipalFactory<TUser, TRole>
2021-11-23 22:56:22 +01:00
where TUser : ZeroUser
where TRole : ZeroUserRole
2021-11-19 16:11:12 +01:00
{
public ZeroBackofficeClaimsPrincipalFactory(UserManager<TUser> userManager, RoleManager<TRole> roleManager, IOptions<IdentityOptions> optionsAccessor, IOptions<ZeroAuthOptions<TUser>> authOptions, IZeroContext zero)
: base(userManager, roleManager, optionsAccessor, authOptions, zero)
{ }
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(TUser user)
{
List<Claim> claims = await CreateClaimList(user);
// create the user identity
2021-11-27 16:09:02 +01:00
ClaimsIdentity identity = new(claims, AuthOptions.Scheme, Constants.Auth.Claims.UserName, Constants.Auth.Claims.Role); // "Identity.Application"
2021-11-19 16:11:12 +01:00
if (BackofficeUserIdentity.TryCreate(identity, out BackofficeUserIdentity userIdentity))
{
Claim isZeroClaim = userIdentity.FindFirst(Constants.Auth.Claims.IsZero);
Claim appIdClaim = userIdentity.FindFirst(Constants.Auth.Claims.AppId);
if (appIdClaim is null || isZeroClaim is null or not { Value: PermissionsValue.True })
{
return null;
}
return userIdentity;
}
return null;
}
protected override async Task<List<Claim>> CreateClaimList(TUser user)
{
List<Claim> claims = await base.CreateClaimList(user);
claims.RemoveAll(x => x.Type == Constants.Auth.Claims.IsZero);
claims.Add(new Claim(Constants.Auth.Claims.IsZero, PermissionsValue.True));
if (user.IsSuper)
{
claims.Add(new Claim(Constants.Auth.Claims.IsSuper, PermissionsValue.True));
}
// get all allowed app ids
2021-11-26 12:31:33 +01:00
//string[] appIds = claims
// .Where(x => x.Type == Constants.Auth.Claims.Permission && x.Value.StartsWith(Permissions.Applications))
// .Select(x => Permission.FromClaim(x, Permissions.Applications))
// .Where(x => x.IsTrue)
// .Select(x => x.NormalizedKey)
// .ToArray();
string[] appIds = Array.Empty<string>(); // TODO permissions
2021-11-19 16:11:12 +01:00
string currentAppId = user.CurrentAppId ?? user.AppId;
if (!user.IsSuper && !appIds.Contains(currentAppId))
{
currentAppId = user.AppId;
}
claims.RemoveAll(x => x.Type == Constants.Auth.Claims.AppId);
claims.Add(new Claim(Constants.Auth.Claims.AppId, currentAppId));
claims.Add(new Claim(Constants.Auth.Claims.DefaultAppId, user.AppId));
return claims;
}
}