Skip to content

Commit

Permalink
Made permssion change code plus some renaming
Browse files Browse the repository at this point in the history
  • Loading branch information
JonPSmith committed Oct 14, 2022
1 parent a5767bf commit 27e9f44
Show file tree
Hide file tree
Showing 10 changed files with 30 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class AddGlobalChangeTimeClaim : IClaimsAdder
/// <returns></returns>
public Task<Claim> AddClaimToUserAsync(string userId)
{
var claim = TenantChangeCookieEvent.EntityChangeClaimType.CreateClaimDateTimeTicks();
var claim = SomethingChangedCookieEvent.EntityChangeClaimType.CreateClaimDateTimeTicks();
return Task.FromResult(claim);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace AuthPermissions.SupportCode.DownStatusCode;
/// If a change is found it will compare the time the significant change against the time when
/// the user's claims were last updated. If the user's claims are "older" that the change happens, then their claims are updated
/// </summary>
public static class TenantChangeCookieEvent
public static class SomethingChangedCookieEvent
{
/// <summary>
/// This is the name of the claim type for a change
Expand Down
2 changes: 1 addition & 1 deletion AuthPermissions/ClaimsCalculator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private async Task<string> CalcPermissionsForUserAsync(string userId)

if (_options.TenantType.IsMultiTenant())
{
//We need to add any RoleTypes.TenantAdminAdd for a tenant user
//We need to add any RoleTypes.TenantAutoAdd for a tenant user

var autoAddPermissions = await _context.AuthUsers
.Where(x => x.UserId == userId && x.TenantId != null)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
// Copyright (c) 2022 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using AuthPermissions;
using AuthPermissions.AdminCode;
using AuthPermissions.BaseCode;
using AuthPermissions.BaseCode.DataLayer;
using AuthPermissions.BaseCode.DataLayer.Classes;
using AuthPermissions.BaseCode.DataLayer.Classes.SupportTypes;
using AuthPermissions.BaseCode.DataLayer.EfCode;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Logging;
using Net.DistributedFileStoreCache;

namespace Example2.WebApiWithToken.IndividualAccounts.ClaimsChangeCode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,39 +80,38 @@ public void RegisterEventHandlers(AuthPermissionsDbContext context)
AddPermissionOverridesToCache((AuthPermissionsDbContext)dbContext, effectedUserIds.Distinct());
effectedUserIds = new List<string>();
};


}

private void AddPermissionOverridesToCache(AuthPermissionsDbContext context, IEnumerable<string> effectedUserIds)
{
foreach (var authUser in context.AuthUsers.Where(x => effectedUserIds.Contains(x.UserId)))
foreach (var userIdAndPackedPermission in context.AuthUsers
.Where(x => effectedUserIds.Contains(x.UserId))
.Select(x => new{ x.UserId, packedPermissions =
x.UserRoles.Select(y => y.Role.PackedPermissionsInRole).ToList()})
)
{
//If not claims, then use empty string
var permissionValue = CalcPermissionsForUser(context, authUser.UserId) ?? "";
_fsCache.Set(authUser.UserId.FormReplacementPermissionsKey(), permissionValue);
_logger?.LogInformation("User {0} has been updated to permission values {1}",
authUser.Email, string.Join(", ", permissionValue.Select(x => (int)x)));
var permissionValue = CalcPermissionsForUser(context, userIdAndPackedPermission.UserId, userIdAndPackedPermission.packedPermissions) ?? "";
_fsCache.Set(userIdAndPackedPermission.UserId.FormReplacementPermissionsKey(), permissionValue);
_logger?.LogInformation("UserId {0} has been updated to permission values {1}",
userIdAndPackedPermission.UserId, string.Join(", ", permissionValue.Select(x => (int)x)));
}
}

/// <summary>
/// This code is taken from the <see cref="ClaimsCalculator"/> and changed to sync.
/// This takes the assigned <see cref="RoleToPermissions.PackedPermissionsInRole"/> for the user
/// and then adds any <see cref="RoleTypes.TenantAutoAdd"/> Roles if provided to create the user's final PackedPermissions
/// This code is taken from the <see cref="ClaimsCalculator"/> and changed
/// </summary>
/// <param name="context"></param>
/// <param name="userId"></param>
/// <param name="permissionsForAllRoles"></param>
/// <returns></returns>
private string CalcPermissionsForUser(AuthPermissionsDbContext context, string userId)
private string CalcPermissionsForUser(AuthPermissionsDbContext context, string userId, List<string> permissionsForAllRoles)
{
//This gets all the permissions, with a distinct to remove duplicates
var permissionsForAllRoles = context.UserToRoles
.Where(x => x.UserId == userId)
.Select(x => x.Role.PackedPermissionsInRole)
.ToList();

if (_options.TenantType.IsMultiTenant())
{
//We need to add any RoleTypes.TenantAdminAdd for a tenant user
//We need to add any RoleTypes.TenantAutoAdd for a tenant user

var autoAddPermissions = context.AuthUsers
.Where(x => x.UserId == userId && x.TenantId != null)
Expand Down
3 changes: 1 addition & 2 deletions Example2.WebApiWithToken.IndividualAccounts/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
// Configure Authentication using JWT token with refresh capability
var jwtData = new JwtSetupData();
builder.Configuration.Bind("JwtData", jwtData);
//The solution to getting the userId claim correct was found in https://stackoverflow.com/a/70315108/1434764
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
//The solution to getting the nameidentifier claim to have the user's Id was found in https://stackoverflow.com/a/70315108/1434764
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
builder.Services.AddAuthentication(auth =>
{
Expand Down
5 changes: 3 additions & 2 deletions Example4.MvcWebApp.IndividualAccounts/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@
.AddRazorRuntimeCompilation();
builder.Services.ConfigureApplicationCookie(options =>
{
//this will cause all the logged-in users to have their claims to be updated if the
options.Events.OnValidatePrincipal = TenantChangeCookieEvent.UpdateClaimsIfSomethingChangesAsync;
//this will cause all the logged-in users to have their claims to be updated if their claims are old
//NOTE: You must register the AddGlobalChangeTimeClaim via RegisterAddClaimToUser
options.Events.OnValidatePrincipal = SomethingChangedCookieEvent.UpdateClaimsIfSomethingChangesAsync;
});


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public AddTenantNameClaim(IAuthUsersAdminService userAdmin)
_userAdmin = userAdmin;
}

public async Task<Claim> AddClaimToUserAsync(string userId)
public async Task<Claim?> AddClaimToUserAsync(string userId)
{
var user = (await _userAdmin.FindAuthUserByUserIdAsync(userId)).Result;

Expand Down
1 change: 1 addition & 0 deletions ReleaseNotes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 3.5.0

- BREAKING CHANGE (small): Changed TenantChangeCookieEvent name to SomethingChangedCookieEvent
- Improved feature: AuthPermissionsDbContext now takes mutiple IDatabaseStateChangeEvent
- Improved feature: No AuthP database event change listeners will be triggered during bulk loading

Expand Down
12 changes: 6 additions & 6 deletions Test/TestData/shardingsettings.Test.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@
"ConnectionName": "PostgreSqlConnection",
"DatabaseType": "Postgres"
},
{
"Name": "Name2",
"DatabaseName": "DatabaseName2",
"ConnectionName": "UnitTestConnection",
"DatabaseType": null
},
{
"Name": "Name1",
"DatabaseName": "DatabaseName1",
Expand All @@ -35,6 +29,12 @@
"DatabaseName": "DatabaseName3",
"ConnectionName": "UnitTestConnection",
"DatabaseType": null
},
{
"Name": "Name2",
"DatabaseName": "DatabaseName2",
"ConnectionName": "UnitTestConnection",
"DatabaseType": null
}
]
}

0 comments on commit 27e9f44

Please sign in to comment.