Skip to content

Commit

Permalink
Renamed SyncAuthUserChange + updated Example1
Browse files Browse the repository at this point in the history
  • Loading branch information
JonPSmith committed Aug 20, 2021
1 parent e749996 commit 2d12725
Show file tree
Hide file tree
Showing 25 changed files with 242 additions and 58 deletions.
2 changes: 1 addition & 1 deletion AuthPermissions/AdminCode/IAuthUsersAdminService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ Task<IStatusGeneric> UpdateUserAsync(string userId, string email,

/// <summary>
/// This receives a list of <see cref="SyncAuthUserWithChange"/> and applies them to the AuthP database.
/// This uses the <see cref="SyncAuthUserWithChange.FoundChange"/> parameter to define what to change
/// This uses the <see cref="SyncAuthUserWithChange.FoundChangeType"/> parameter to define what to change
/// </summary>
/// <param name="changesToApply"></param>
/// <returns>Status</returns>
Expand Down
18 changes: 9 additions & 9 deletions AuthPermissions/AdminCode/Services/AuthUsersAdminService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ public async Task<List<SyncAuthUserWithChange>> SyncAndShowChangesAsync()
{
//check if its a change or not
var syncChange = new SyncAuthUserWithChange(authenticationUser, authUser);
if (syncChange.FoundChange == SyncAuthUserChanges.Update)
if (syncChange.FoundChangeType == SyncAuthUserChangeTypes.Update)
//The two are different so add to the result
result.Add(syncChange);
//Removed the authUser as has been handled
Expand All @@ -325,7 +325,7 @@ public async Task<List<SyncAuthUserWithChange>> SyncAndShowChangesAsync()

/// <summary>
/// This receives a list of <see cref="SyncAuthUserWithChange"/> and applies them to the AuthP database.
/// This uses the <see cref="SyncAuthUserWithChange.FoundChange"/> parameter to define what to change
/// This uses the <see cref="SyncAuthUserWithChange.FoundChangeType"/> parameter to define what to change
/// </summary>
/// <param name="changesToApply"></param>
/// <returns>Status</returns>
Expand All @@ -335,19 +335,19 @@ public async Task<IStatusGeneric> ApplySyncChangesAsync(IEnumerable<SyncAuthUser

foreach (var syncChange in changesToApply)
{
switch (syncChange.FoundChange)
switch (syncChange.FoundChangeType)
{
case SyncAuthUserChanges.NoChange:
case SyncAuthUserChangeTypes.NoChange:
continue;
case SyncAuthUserChanges.Create:
case SyncAuthUserChangeTypes.Create:
status.CombineStatuses(await AddNewUserAsync(syncChange.UserId, syncChange.Email,
syncChange.UserName, syncChange.RoleNames, syncChange.TenantName));
break;
case SyncAuthUserChanges.Update:
case SyncAuthUserChangeTypes.Update:
status.CombineStatuses(await UpdateUserAsync(syncChange.UserId, syncChange.Email,
syncChange.UserName, syncChange.RoleNames, syncChange.TenantName));
break;
case SyncAuthUserChanges.Delete:
case SyncAuthUserChangeTypes.Delete:
var authUserStatus = await FindAuthUserByUserIdAsync(syncChange.UserId);
if (status.CombineStatuses(authUserStatus).HasErrors)
return status;
Expand All @@ -361,8 +361,8 @@ public async Task<IStatusGeneric> ApplySyncChangesAsync(IEnumerable<SyncAuthUser

status.CombineStatuses(await _context.SaveChangesWithChecksAsync());
//Build useful summary
var changeStrings = Enum.GetValues<SyncAuthUserChanges>().ToList()
.Select(x => $"{x} = {changesToApply.Count(y => y.FoundChange == x)}");
var changeStrings = Enum.GetValues<SyncAuthUserChangeTypes>().ToList()
.Select(x => $"{x} = {changesToApply.Count(y => y.FoundChangeType == x)}");
status.Message = $"Sync successful: {(string.Join(", ", changeStrings))}";

return status;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace AuthPermissions.AdminCode
/// The type of changes between the authentication provider's user and the AuthPermission's AuthUser
/// Also used to confirm that the change should be made
/// </summary>
public enum SyncAuthUserChanges
public enum SyncAuthUserChangeTypes
{
/// <summary>
/// Ignore this change - can be set by the user
Expand Down
20 changes: 10 additions & 10 deletions AuthPermissions/AdminCode/SyncAuthUserWithChange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ internal SyncAuthUserWithChange(SyncAuthenticationUser authenticationUser, AuthU

//Now work out what the change is
if (Email == OldEmail && UserName == OldUserName)
FoundChange = SyncAuthUserChanges.NoChange;
FoundChangeType = SyncAuthUserChangeTypes.NoChange;
else if (authenticationUser == null)
{
FoundChange = SyncAuthUserChanges.Delete;
FoundChangeType = SyncAuthUserChangeTypes.Delete;
//Need to set the Email and UserName so that can show the AuthP user's values
Email = authUser.Email;
UserName = authUser.UserName;
Expand All @@ -70,17 +70,17 @@ internal SyncAuthUserWithChange(SyncAuthenticationUser authenticationUser, AuthU
OldUserName = null;
}
else if (authUser == null)
FoundChange = SyncAuthUserChanges.Create;
FoundChangeType = SyncAuthUserChangeTypes.Create;
else
FoundChange = SyncAuthUserChanges.Update;
FoundChangeType = SyncAuthUserChangeTypes.Update;


}

/// <summary>
/// This is set to the difference between authentication provider's user and the AuthPermission's AuthUser
/// </summary>
public SyncAuthUserChanges FoundChange { get; set; }
public SyncAuthUserChangeTypes FoundChangeType { get; set; }

/// <summary>
/// The userId of the user (NOTE: this is not shown)
Expand Down Expand Up @@ -125,15 +125,15 @@ internal SyncAuthUserWithChange(SyncAuthenticationUser authenticationUser, AuthU
/// <returns></returns>
public override string ToString()
{
switch (FoundChange)
switch (FoundChangeType)
{
case SyncAuthUserChanges.NoChange:
case SyncAuthUserChangeTypes.NoChange:
throw new AuthPermissionsException("Shouldn't have this in the list");
case SyncAuthUserChanges.Create:
case SyncAuthUserChangeTypes.Create:
return $"CREATE: Email = {Email}, UserName = {UserName}";
case SyncAuthUserChanges.Update:
case SyncAuthUserChangeTypes.Update:
return $"UPDATE: Email {(EmailChanged ? "CHANGED" : "same")}, UserName {(UserNameChanged ? "CHANGED" : "same")}";
case SyncAuthUserChanges.Delete:
case SyncAuthUserChangeTypes.Delete:
return $"DELETE: Email = {Email}, UserName = {UserName}";
default:
throw new ArgumentOutOfRangeException();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
@page
@model ListUsersModel

<h1>Auth users</h1>

@if (!string.IsNullOrEmpty(Model.Message))
{
<h3 class="text-primary">@Model.Message</h3>
}

<a class="btn btn-primary" asp-area="" asp-page=".\SyncUsers">Sync with authentication provider's users</a>
<p></p>

<table class="table">
<thead>
<tr>
<th>
UserName
</th>
<th>
Email
</th>
<th>
AuthRoles
</th>
<th>
Edit | Delete
</th>
</tr>
</thead>
<tbody>
@foreach (var item in @Model.AuthUserList)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@string.Join(", ", item.RoleNames)
</td>
<td>
<a asp-area="" asp-page="AuthUsers\Edit" asp-route-id="@item.UserId">Edit</a>
|
<a asp-area="" asp-page="AuthUsers\Delete" asp-route-id="@item.UserId">Delete</a>
</td>
</tr>
}
</tbody>
</table>



@section Scripts{


<script type='text/javascript'>
$(function () {
$('[data-toggle="tooltip"]').tooltip();
})
</script>
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AuthPermissions.AdminCode;
using ExamplesCommonCode.CommonAdmin;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace Example1.RazorPages.IndividualAccounts.Pages.AuthUsers
{
public class ListUsersModel : PageModel
{
private readonly IAuthUsersAdminService _authUsersAdmin;

public ListUsersModel(IAuthUsersAdminService authUsersAdmin)
{
_authUsersAdmin = authUsersAdmin;
}

public List<AuthUserDisplay> AuthUserList { get; private set; }
public string Message { get; set; }

public async Task OnGet(string message)
{
Message = message;
var userQuery = _authUsersAdmin.QueryAuthUsers();
AuthUserList = await AuthUserDisplay.SelectQuery(userQuery.OrderBy(x => x.Email)).ToListAsync();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
@page
@using global::AuthPermissions.AdminCode
@model Example1.RazorPages.IndividualAccounts.Pages.AuthUsers.SyncUsersModel

@if (!@Model.Data.Any())
{
<h3>There are no changes to apply to the AuthUsers</h3>
return;
}

<h3>Changes needed based on authentication provider's users</h3>
<form method="post">
<table class="table">
<thead>
<tr>
<th>Change type</th>
<th>Email</th>
<th>UserName</th>
<th>Roles Count</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Data.Count; i++)
{
<tr>
<td>
@Model.Data[i].FoundChangeType
@Html.Hidden($"Data[{i}].{nameof(SyncAuthUserWithChange.UserId)}", Model.Data[i].UserId)
@Html.Hidden($"Data[{i}].{nameof(SyncAuthUserWithChange.FoundChangeType)}", Model.Data[i].FoundChangeType)
</td>

<td @(Model.Data[i].EmailChanged ? "class=bg-warning text-dark" : "")>
@Model.Data[i].Email
@Html.Hidden($"Data[{i}].{nameof(SyncAuthUserWithChange.Email)}", Model.Data[i].Email)
</td>
<td @(Model.Data[i].UserNameChanged ? "class=bg-warning text-dark" : "")>
@Model.Data[i].UserName
@Html.Hidden($"Data[{i}].{nameof(SyncAuthUserWithChange.UserName)}", Model.Data[i].UserName)
</td>
<td>@Model.Data[i].NumRoles</td>
</tr>
}

</tbody>
</table>

<button class="btn btn-primary">Apply Sync Changes</button>

</form>

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using AuthPermissions.AdminCode;
using AuthPermissions.CommonCode;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Example1.RazorPages.IndividualAccounts.Pages.AuthUsers
{
public class SyncUsersModel : PageModel
{
private readonly IAuthUsersAdminService _authUsersAdmin;

public SyncUsersModel(IAuthUsersAdminService authUsersAdmin)
{
_authUsersAdmin = authUsersAdmin;
}

[BindProperty]
public List<SyncAuthUserWithChange> Data { get; set; }

public async Task OnGet()
{
Data = await _authUsersAdmin.SyncAndShowChangesAsync();
}

public async Task<IActionResult> OnPost()
{
var status = await _authUsersAdmin.ApplySyncChangesAsync(Data);
return RedirectToPage("ListUsers", new { message = status.Message });
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,15 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/UserClaims">User's claims</a>
<li class="dropdown nav-link text-dark">
<a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
Users
</a>
<div class="dropdown-menu">
<a class="dropdown-item" asp-area="" asp-page="/AuthUsers/ListUsers">List AuthUsers</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" asp-area="" asp-page="/UserInfo/UserClaims">User's claims</a>
</div>
</li>
</ul>
<partial name="_LoginPartial" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Example1.RazorPages.IndividualAccounts.Pages
namespace Example1.RazorPages.IndividualAccounts.Pages.UserInfo
{
public class UserClaimsModel : PageModel
{
Expand Down
4 changes: 3 additions & 1 deletion Example1.RazorPages.IndividualAccounts/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ public void ConfigureServices(IServiceCollection services)
//These are methods from the ExamplesCommonCode set up some demo users in the individual accounts database
//NOTE: they are run in the order that they are registered
services.AddHostedService<HostedServiceEnsureCreatedDb<ApplicationDbContext>>(); //and create db on startup
services.AddHostedService<HostedServiceAddAspNetUsers>(); //reads a comma delimited list of emails from appsettings.json
//reads a comma delimited list of emails from appsettings.json and creates users in the Individual Account
services.AddHostedService<HostedServiceAddAspNetUsers>();

services.RegisterAuthPermissions<Example1Permissions>()
.UsingInMemoryDatabase()
.AddRolesPermissionsIfEmpty(AppAuthSetupData.ListOfRolesWithPermissions)
.AddAuthUsersIfEmpty(AppAuthSetupData.UsersRolesDefinition)
.RegisterAuthenticationProviderReader<SyncIndividualAccountUsers>()
.RegisterFindUserInfoService<IndividualAccountUserLookup>()
.AddSuperUserToIndividualAccounts()
.SetupAspNetCoreAndDatabase();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,21 +61,21 @@ public async Task<ActionResult> Create(string userId)
/// <returns></returns>
public async Task<ActionResult> EditFromSync(SetupManualUserChange input)
{
switch (input.FoundChange)
switch (input.FoundChangeType)
{
case SyncAuthUserChanges.NoChange:
case SyncAuthUserChangeTypes.NoChange:
return RedirectToAction(nameof(Index),
new { message = "The entry was marked as 'No Change' so it was ignored." });
case SyncAuthUserChanges.Create:
case SyncAuthUserChangeTypes.Create:
var createData = await SetupManualUserChange.PrepareForCreateAsync(input.UserId, _context);
return View(nameof(Create), createData);
case SyncAuthUserChanges.Update:
case SyncAuthUserChangeTypes.Update:
var status = await SetupManualUserChange.PrepareForUpdateAsync(input.UserId, _authUsersAdmin, _context);
if (status.HasErrors)
return RedirectToAction(nameof(ErrorDisplay),
new { errorMessage = status.GetAllErrors() });
return View(nameof(Edit), status.Result);
case SyncAuthUserChanges.Delete:
case SyncAuthUserChangeTypes.Delete:
return View(nameof(Delete), new { userId = input.UserId });
}

Expand All @@ -90,7 +90,7 @@ public async Task<ActionResult> CreateUpdate(SetupManualUserChange input)
if (!ModelState.IsValid)
{
await input.SetupDropDownListsAsync(_context);//refresh dropdown
return View(input.FoundChange);
return View(input.FoundChangeType);
}

var status = await input.ChangeAuthUserFromDataAsync(_authUsersAdmin, _context);
Expand All @@ -113,9 +113,6 @@ public async Task<ActionResult> SyncUsers()
//NOTE: the input be called "data" because we are using JavaScript to send that info back
public async Task<ActionResult> SyncUsers(IEnumerable<SyncAuthUserWithChange> data)
{
return RedirectToAction("Index"); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


var status = await _authUsersAdmin.ApplySyncChangesAsync(data);
if (status.HasErrors)
return RedirectToAction(nameof(ErrorDisplay),
Expand Down
Loading

0 comments on commit 2d12725

Please sign in to comment.