Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extended Account Management #69

Draft
wants to merge 5 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions FactorioWebInterface/Pages/Admin/CreateAccount.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
@page
@model FactorioWebInterface.Pages.Admin.CreateAccountModel
@{
ViewData["Title"] = "Create New Account";
}

@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}

<div class="container">

<h2 class="title is-2">Create New Account</h2>

<div class="columns">
<div class="column is-4">
<form method="post">
<h4 class="title is-4">Create User</h4>
<hr />
<div asp-validation-summary="All" class="has-text-danger"></div>
<div class="field">
<label asp-for="Input.UserName" class="label"></label>
<div class="control">
<input asp-for="Input.UserName" class="input" />
</div>
<span asp-validation-for="Input.UserName" class="help is-danger"></span>
</div>
<div class="field">
<label asp-for="Input.Password" class="label"></label>
<div class="control">
<input asp-for="Input.Password" class="input" />
</div>
<span asp-validation-for="Input.Password" class="help is-danger"></span>
</div>
<div class="field">
<label asp-for="Input.ConfirmPassword" class="label"></label>
<div class="control">
<input asp-for="Input.ConfirmPassword" class="input" />
</div>
<span asp-validation-for="Input.ConfirmPassword" class="help is-danger"></span>
</div>
<div class="field">
<label asp-for="Input.Role" class="label"></label>
<div class="control">
@foreach (var item in Model.Roles)
{
<input asp-for="Input.Role" type="radio" value="@item" /> @item
}
</div>
<span asp-validation-for="Input.Role" class="help is-danger"></span>
</div>
<button type="submit" asp-page-handler="CreateAccount" class="button is-link">Create new account</button>
</form>

@if (Model.AccountCreated)
{
<hr />
<p>Account created</p>
}
</div>
</div>
</div>


106 changes: 106 additions & 0 deletions FactorioWebInterface/Pages/Admin/CreateAccount.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using FactorioWebInterface.Data;
using FactorioWebInterface.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace FactorioWebInterface.Pages.Admin
{
[Authorize(Roles = Constants.RootRole)]
SimonFlapse marked this conversation as resolved.
Show resolved Hide resolved
public class CreateAccountModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IWebAccountManager _accountManager;
private readonly ILogger<CreateAccountModel> _logger;

public CreateAccountModel(
IWebAccountManager accountManager,
SignInManager<ApplicationUser> signInManager,
ILogger<CreateAccountModel> logger
)
{
_accountManager = accountManager;
_signInManager = signInManager;
_logger = logger;
}

public bool AccountCreated { get; set; }

[BindProperty]
public InputModel Input { get; set; } = default!;

public string[] Roles { get; set; } = { Constants.AdminRole, Constants.RootRole };

public class InputModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Username")]
public string UserName { get; set; } = default!;

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; } = default!;

[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; } = default!;

[Display(Name = "Select role")]
public string Role { get; set; } = Constants.AdminRole;
}

public async Task<IActionResult> OnGetAsync(bool accountCreated)
{
var user = await _accountManager.GetUserAsync(User);

if (user == null || user.Suspended)
{
HttpContext.Session.SetString("returnUrl", "account");
SimonFlapse marked this conversation as resolved.
Show resolved Hide resolved
return RedirectToPage("signIn");
}

AccountCreated = accountCreated;

return Page();
}

public async Task<IActionResult> OnPostCreateAccountAsync()
{
var user = await _accountManager.GetUserAsync(User);

if (user == null || user.Suspended)
{
HttpContext.Session.SetString("returnUrl", "account");
return RedirectToPage("signIn");
}

await _accountManager.CreateAccountAsync(Input.UserName, Input.Password, new string[]{Input.Role});

/*if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}

return Page();
}*/

//await _signInManager.SignInAsync(user, isPersistent: false);

//_logger.LogInformation($"User {user.UserName} created password");
SimonFlapse marked this conversation as resolved.
Show resolved Hide resolved

return RedirectToPage(new { AccountCreated = true });
}
}
}
9 changes: 7 additions & 2 deletions FactorioWebInterface/Pages/Admin/_AdminNavBarPartial.cshtml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
@using Microsoft.AspNetCore.Identity;
@using FactorioWebInterface.Data;
@inject UserManager<ApplicationUser> userManger;
@inject UserManager<ApplicationUser> userManager;

@{
var user = await userManger.GetUserAsync(User);
var user = await userManager.GetUserAsync(User);
}

<nav class="navbar is-fixed-top has-shadow" role="navigation" aria-label="main navigation">
Expand Down Expand Up @@ -45,6 +45,11 @@
else
{
<a class="navbar-item @(page == "/admin/account" ? "has-text-info" : "")" asp-page="/Admin/Account" title="Account">@user.UserName</a>
if (await userManager.IsInRoleAsync(user, Constants.RootRole))
{
<a class="navbar-item @(page == "/admin/account" ? "has-text-info" : "")" asp-page="/Admin/CreateAccount" title="Create New Account">New Account</a>
}

<a class="navbar-item @(page == "/admin/signout" ? "has-text-info" : "")" asp-page="/Admin/SignOut" title="Sign out">Sign out</a>
}
}
Expand Down
97 changes: 97 additions & 0 deletions FactorioWebInterface/Services/WebAccountManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using FactorioWebInterface.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace FactorioWebInterface.Services
{
public interface IWebAccountManager
{
Task<ApplicationUser> FindByNameAsync(string username);
Task<ApplicationUser> FindByIdAsync(string id);
Task<ApplicationUser> GetUserAsync(ClaimsPrincipal user);
Task CreateAccountAsync(string username, string password, string[] roles);
Task ChangePasswordAsync(ApplicationUser user, string oldPassword, string newPassword);
Task AddRoleAsync(ApplicationUser user, string role);
Task RemoveRoleAsync(ApplicationUser user, string role);
Task SuspendAccountAsync(ApplicationUser user, bool suspended = true);
}

public class WebAccountManager : IWebAccountManager
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<WebAccountManager> _logger;

public WebAccountManager(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<WebAccountManager> logger)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
}

public async Task AddRoleAsync(ApplicationUser user, string role)
{
await _userManager.AddToRoleAsync(user, role);
SimonFlapse marked this conversation as resolved.
Show resolved Hide resolved
_logger.LogInformation("The user: " + user.UserName + " has been added to the role: " + role);
}

public async Task ChangePasswordAsync(ApplicationUser user, string oldPassword, string newPassword)
{
await _userManager.ChangePasswordAsync(user, oldPassword, newPassword);
_logger.LogInformation("The user: " + user.UserName + " has changed their password");
}

public async Task CreateAccountAsync(string username, string password, string[] roles)
{
var id = Guid.NewGuid().ToString();
var user = new ApplicationUser()
{
Id = id,
UserName = username
};

var result = await _userManager.CreateAsync(user, password);
if (!result.Succeeded)
{
_logger.LogError("User account couldn't be created");
}
foreach (string role in roles) {
await AddRoleAsync(user, role);
}
_logger.LogInformation("User account created with username: " + username + " and id: " + id);
}

public async Task<ApplicationUser> FindByIdAsync(string id)
{
return await _userManager.FindByIdAsync(id);
}

public async Task<ApplicationUser> FindByNameAsync(string username)
{
return await _userManager.FindByIdAsync(username);
}

public async Task<ApplicationUser> GetUserAsync(ClaimsPrincipal user)
{
return await _userManager.GetUserAsync(user);
}

public async Task RemoveRoleAsync(ApplicationUser user, string role)
{
await _userManager.RemoveFromRoleAsync(user, role);
_logger.LogInformation("The user: " + user.UserName + " has been removed from the role: " + role);
SimonFlapse marked this conversation as resolved.
Show resolved Hide resolved
}

public async Task SuspendAccountAsync(ApplicationUser user, bool suspended = true)
{
user.Suspended = suspended;
await _userManager.UpdateAsync(user);
_logger.LogInformation("The user: " + user.UserName + " has been suspended");
}
}
}
1 change: 1 addition & 0 deletions FactorioWebInterface/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddSingleton<BanHubEventHandlerService, BanHubEventHandlerService>();
services.AddSingleton<FactorioAdminServiceEventHandlerService, FactorioAdminServiceEventHandlerService>();
services.AddSingleton<IFactorioModPortalService, FactorioModPortalService>();
services.AddScoped<IWebAccountManager, WebAccountManager>();

services.AddRouting(o => o.LowercaseUrls = true);

Expand Down