Skip to content

Commit

Permalink
Section 8 - Register User with Roles
Browse files Browse the repository at this point in the history
  • Loading branch information
bhrugen committed Sep 24, 2021
1 parent 5b5ed88 commit 50faa91
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions BulkyBookWeb/Areas/Identity/Pages/Account/Register.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@
<label asp-for="Input.ConfirmPassword"></label>
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-floating py-2 col-6">
<select asp-for="Input.Role" asp-items="@Model.Input.RoleList" class=form-select>
<option disabled selected>-Select Role-</option>
</select>

</div>
<button id="registerSubmit" type="submit" class="w-100 btn btn-primary">Register</button>
</form>
</div>
Expand Down
21 changes: 21 additions & 0 deletions BulkyBookWeb/Areas/Identity/Pages/Account/Register.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;

Expand Down Expand Up @@ -108,6 +110,9 @@ public class InputModel
public string? State { get; set; }
public string? PostalCode { get; set; }
public string? PhoneNumber { get; set; }
public string? Role { get; set; }
[ValidateNever]
public IEnumerable<SelectListItem> RoleList { get; set; }
}


Expand All @@ -122,6 +127,14 @@ public async Task OnGetAsync(string returnUrl = null)
}
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
Input = new InputModel()
{
RoleList = _roleManager.Roles.Select(x => x.Name).Select(i => new SelectListItem
{
Text = i,
Value = i
})
};
}

public async Task<IActionResult> OnPostAsync(string? returnUrl = null)
Expand All @@ -147,6 +160,14 @@ public async Task<IActionResult> OnPostAsync(string? returnUrl = null)
{
_logger.LogInformation("User created a new account with password.");

if (Input.Role == null) {
await _userManager.AddToRoleAsync(user, SD.Role_User_Indi);
}
else
{
await _userManager.AddToRoleAsync(user, Input.Role);
}

var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
Expand Down

0 comments on commit 50faa91

Please sign in to comment.