Merge pull request #381 from sbwalker/master

fixed user registration, and updated module creator templates to use new Service approach
This commit is contained in:
Shaun Walker 2020-04-16 10:20:57 -04:00 committed by GitHub
commit 5fb8cd5cec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 223 additions and 151 deletions

View File

@ -14,7 +14,7 @@
<text>...</text>
</Authorizing>
<Authorized>
You are already logged in
<ModuleMessage Message="You Are Already Logged In" Type="MessageType.Info" />
</Authorized>
<NotAuthorized>
<div class="container">

View File

@ -12,13 +12,11 @@ namespace [Owner].[Module]s.Services
{
public class [Module]Service : ServiceBase, I[Module]Service, IService
{
private readonly HttpClient _http;
private readonly NavigationManager _navigationManager;
private readonly SiteState _siteState;
public [Module]Service(HttpClient http, SiteState siteState, NavigationManager navigationManager)
public [Module]Service(HttpClient http, SiteState siteState, NavigationManager navigationManager) : base(http)
{
_http = http;
_siteState = siteState;
_navigationManager = navigationManager;
}
@ -30,28 +28,28 @@ namespace [Owner].[Module]s.Services
public async Task<List<[Module]>> Get[Module]sAsync(int ModuleId)
{
List<[Module]> [Module]s = await _http.GetJsonAsync<List<[Module]>>(Apiurl + "?moduleid=" + ModuleId.ToString());
List<[Module]> [Module]s = await GetJsonAsync<List<[Module]>>(Apiurl + "?moduleid=" + ModuleId.ToString());
return [Module]s.OrderBy(item => item.Name).ToList();
}
public async Task<[Module]> Get[Module]Async(int [Module]Id)
{
return await _http.GetJsonAsync<[Module]>(Apiurl + "/" + [Module]Id.ToString());
return await GetJsonAsync<[Module]>(Apiurl + "/" + [Module]Id.ToString());
}
public async Task<[Module]> Add[Module]Async([Module] [Module])
{
return await _http.PostJsonAsync<[Module]>(Apiurl + "?entityid=" + [Module].ModuleId, [Module]);
return await PostJsonAsync<[Module]>(Apiurl + "?entityid=" + [Module].ModuleId, [Module]);
}
public async Task<[Module]> Update[Module]Async([Module] [Module])
{
return await _http.PutJsonAsync<[Module]>(Apiurl + "/" + [Module].[Module]Id + "?entityid=" + [Module].ModuleId, [Module]);
return await PutJsonAsync<[Module]>(Apiurl + "/" + [Module].[Module]Id + "?entityid=" + [Module].ModuleId, [Module]);
}
public async Task Delete[Module]Async(int [Module]Id)
{
await _http.DeleteAsync(Apiurl + "/" + [Module]Id.ToString());
await DeleteAsync(Apiurl + "/" + [Module]Id.ToString());
}
}
}

View File

@ -14,7 +14,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-preview3.20168.3" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0-preview3.20168.3" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview3.20168.3" />
<PackageReference Include="System.Net.Http.Json" Version="3.2.0-preview3.20175.8" />
</ItemGroup>
<ItemGroup>

View File

@ -12,13 +12,11 @@ namespace [Owner].[Module]s.Services
{
public class [Module]Service : ServiceBase, I[Module]Service, IService
{
private readonly HttpClient _http;
private readonly NavigationManager _navigationManager;
private readonly SiteState _siteState;
public [Module]Service(HttpClient http, SiteState siteState, NavigationManager navigationManager)
public [Module]Service(HttpClient http, SiteState siteState, NavigationManager navigationManager) : base(http)
{
_http = http;
_siteState = siteState;
_navigationManager = navigationManager;
}
@ -30,28 +28,28 @@ namespace [Owner].[Module]s.Services
public async Task<List<[Module]>> Get[Module]sAsync(int ModuleId)
{
List<[Module]> [Module]s = await _http.GetJsonAsync<List<[Module]>>(Apiurl + "?moduleid=" + ModuleId.ToString());
List<[Module]> [Module]s = await GetJsonAsync<List<[Module]>>(Apiurl + "?moduleid=" + ModuleId.ToString());
return [Module]s.OrderBy(item => item.Name).ToList();
}
public async Task<[Module]> Get[Module]Async(int [Module]Id)
{
return await _http.GetJsonAsync<[Module]>(Apiurl + "/" + [Module]Id.ToString());
return await GetJsonAsync<[Module]>(Apiurl + "/" + [Module]Id.ToString());
}
public async Task<[Module]> Add[Module]Async([Module] [Module])
{
return await _http.PostJsonAsync<[Module]>(Apiurl + "?entityid=" + [Module].ModuleId, [Module]);
return await PostJsonAsync<[Module]>(Apiurl + "?entityid=" + [Module].ModuleId, [Module]);
}
public async Task<[Module]> Update[Module]Async([Module] [Module])
{
return await _http.PutJsonAsync<[Module]>(Apiurl + "/" + [Module].[Module]Id + "?entityid=" + [Module].ModuleId, [Module]);
return await PutJsonAsync<[Module]>(Apiurl + "/" + [Module].[Module]Id + "?entityid=" + [Module].ModuleId, [Module]);
}
public async Task Delete[Module]Async(int [Module]Id)
{
await _http.DeleteAsync(Apiurl + "/" + [Module]Id.ToString());
await DeleteAsync(Apiurl + "/" + [Module]Id.ToString());
}
}
}

View File

@ -3,64 +3,63 @@
@inject NavigationManager NavigationManager
@inject IUserService UserService
@if (_message != string.Empty)
@if (PageState.Site.AllowRegistration)
{
<ModuleMessage Message="@_message" Type="MessageType.Info" />
<AuthorizeView>
<Authorizing>
<text>...</text>
</Authorizing>
<Authorized>
<ModuleMessage Message="You Are Already Registered" Type="MessageType.Info" />
</Authorized>
<NotAuthorized>
<ModuleMessage Message="Please Note That Registration Requires A Valid Email Address In Order To Verify Your Identity" Type="MessageType.Info" />
<div class="container">
<div class="form-group">
<label for="Username" class="control-label">Username: </label>
<input type="text" class="form-control" placeholder="Username" @bind="@_username" id="Username" />
</div>
<div class="form-group">
<label for="Password" class="control-label">Password: </label>
<input type="password" class="form-control" placeholder="Password" @bind="@_password" id="Password" />
</div>
<div class="form-group">
<label for="Confirm" class="control-label">Confirm Password: </label>
<input type="password" class="form-control" placeholder="Password" @bind="@_confirm" id="Confirm" />
</div>
<div class="form-group">
<label for="Email" class="control-label">Email: </label>
<input type="text" class="form-control" placeholder="Email" @bind="@_email" id="Email" />
</div>
<div class="form-group">
<label for="DisplayName" class="control-label">Full Name: </label>
<input type="text" class="form-control" placeholder="Full Name" @bind="@_displayName" id="DisplayName" />
</div>
<button type="button" class="btn btn-primary" @onclick="Register">Register</button>
<button type="button" class="btn btn-secondary" @onclick="Cancel">Cancel</button>
</div>
</NotAuthorized>
</AuthorizeView>
}
else
{
<ModuleMessage Message="Registration is Disabled For This Site" Type="MessageType.Info" />
}
<div class="container @_css">
<div class="form-group">
<label for="Username" class="control-label">Username: </label>
<input type="text" class="form-control" placeholder="Username" @bind="@_username" id="Username"/>
</div>
<div class="form-group">
<label for="Password" class="control-label">Password: </label>
<input type="password" class="form-control" placeholder="Password" @bind="@_password" id="Password"/>
</div>
<div class="form-group">
<label for="Confirm" class="control-label">Confirm Password: </label>
<input type="password" class="form-control" placeholder="Password" @bind="@_confirm"id="Confirm" />
</div>
<div class="form-group">
<label for="Email" class="control-label">Email: </label>
<input type="text" class="form-control" placeholder="Email" @bind="@_email" id="Email"/>
</div>
<div class="form-group">
<label for="DisplayName" class="control-label">Full Name: </label>
<input type="text" class="form-control" placeholder="Full Name" @bind="@_displayName" id="DisplayName"/>
</div>
<button type="button" class="btn btn-primary" @onclick="Register">Register</button>
<button type="button" class="btn btn-secondary" @onclick="Cancel">Cancel</button>
</div>
@code {
private string _message = "Please Note That Registration Requires A Valid Email Address In Order To Verify Your Identity";
private string _username = string.Empty;
private string _password = string.Empty;
private string _confirm = string.Empty;
private string _email = string.Empty;
private string _displayName = string.Empty;
private string _css = string.Empty;
private const string displayNone = "d-none";
public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Anonymous;
protected override void OnInitialized()
{
if (!PageState.Site.AllowRegistration)
{
_message = "Registration is Disabled";
_css = displayNone;
}
}
private async Task Register()
{
try
{
_message = string.Empty;
bool _isEmailValid = Utilities.IsValidEmail(_email);
if (_username != "" && _password != "" && _confirm != "" && _isEmailValid)

View File

@ -0,0 +1,64 @@
@namespace Oqtane.Modules.Admin.SystemInfo
@inherits ModuleBase
<table class="table table-borderless">
<tr>
<td>
<Label For="version" HelpText="qtane Version">Oqtane Version: </Label>
</td>
<td>
@_version
</td>
</tr>
<tr>
<td>
<Label For="runtime" HelpText="Blazor Runtime">Blazor Runtime: </Label>
</td>
<td>
@_runtime
</td>
</tr>
<tr>
<td>
<Label For="netcore" HelpText=".NET Core">.NET Core: </Label>
</td>
<td>
@_netcore
</td>
</tr>
<tr>
<td>
<Label For="serverpath" HelpText="Server Path">Server Path: </Label>
</td>
<td>
@_serverpath
</td>
</tr>
<tr>
<td>
<Label For="servertime" HelpText="Server Time">Server Time: </Label>
</td>
<td>
@_servertime
</td>
</tr>
</table>
@code {
public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;
private string _version = string.Empty;
private string _runtime = string.Empty;
private string _netcore = string.Empty;
private string _serverpath = string.Empty;
private string _servertime = string.Empty;
protected override void OnInitialized()
{
_version = Constants.Version;
_runtime = PageState.Runtime.ToString();
_netcore = string.Empty;
_serverpath = string.Empty;
_servertime = string.Empty;
}
}

View File

@ -10,13 +10,11 @@ namespace Oqtane.Services
{
private readonly SiteState _siteState;
private readonly NavigationManager _navigationManager;
private readonly ISiteService _siteService;
public UserService(HttpClient http, SiteState siteState, NavigationManager navigationManager, ISiteService siteService) : base(http)
public UserService(HttpClient http, SiteState siteState, NavigationManager navigationManager) : base(http)
{
_siteState = siteState;
_navigationManager = navigationManager;
_siteService = siteService;
}
private string Apiurl
@ -26,26 +24,16 @@ namespace Oqtane.Services
public async Task<User> GetUserAsync(int userId, int siteId)
{
return await GetJsonAsync<User>($"{Apiurl}/{userId.ToString()}?siteid={siteId.ToString()}");
return await GetJsonAsync<User>($"{Apiurl}/{userId}?siteid={siteId}");
}
public async Task<User> GetUserAsync(string username, int siteId)
{
return await GetJsonAsync<User>($"{Apiurl}/name/{username}?siteid={siteId.ToString()}");
return await GetJsonAsync<User>($"{Apiurl}/name/{username}?siteid={siteId}");
}
public async Task<User> AddUserAsync(User user)
{
// On initial site creation alias is null and we always want to create host user
if (user.Username != Constants.HostUser && _siteState.Alias != null)
{
Site site = await _siteService.GetSiteAsync(_siteState.Alias.SiteId, _siteState.Alias);
if (!site.AllowRegistration)
{
return null;
}
}
return await PostJsonAsync<User>(Apiurl, user);
}
@ -56,17 +44,17 @@ namespace Oqtane.Services
public async Task<User> UpdateUserAsync(User user)
{
return await PutJsonAsync<User>($"{Apiurl}/{user.UserId.ToString()}", user);
return await PutJsonAsync<User>($"{Apiurl}/{user.UserId}", user);
}
public async Task DeleteUserAsync(int userId)
{
await DeleteAsync($"{Apiurl}/{userId.ToString()}");
await DeleteAsync($"{Apiurl}/{userId}");
}
public async Task<User> LoginUserAsync(User user, bool setCookie, bool isPersistent)
{
return await PostJsonAsync<User>($"{Apiurl}/login?setcookie={setCookie.ToString()}&persistent={isPersistent.ToString()}", user);
return await PostJsonAsync<User>($"{Apiurl}/login?setcookie={setCookie}&persistent={isPersistent}", user);
}
public async Task LogoutUserAsync(User user)

View File

@ -28,9 +28,10 @@ namespace Oqtane.Controllers
private readonly INotificationRepository _notifications;
private readonly IFolderRepository _folders;
private readonly ISyncManager _syncManager;
private readonly ISiteRepository _sites;
private readonly ILogManager _logger;
public UserController(IUserRepository users, IRoleRepository roles, IUserRoleRepository userRoles, UserManager<IdentityUser> identityUserManager, SignInManager<IdentityUser> identitySignInManager, ITenantResolver tenants, INotificationRepository notifications, IFolderRepository folders, ISyncManager syncManager, ILogManager logger)
public UserController(IUserRepository users, IRoleRepository roles, IUserRoleRepository userRoles, UserManager<IdentityUser> identityUserManager, SignInManager<IdentityUser> identitySignInManager, ITenantResolver tenants, INotificationRepository notifications, IFolderRepository folders, ISyncManager syncManager, ISiteRepository sites, ILogManager logger)
{
_users = users;
_roles = roles;
@ -41,6 +42,7 @@ namespace Oqtane.Controllers
_folders = folders;
_notifications = notifications;
_syncManager = syncManager;
_sites = sites;
_logger = logger;
}
@ -88,93 +90,116 @@ namespace Oqtane.Controllers
private async Task<User> CreateUser(User user)
{
User newUser = null;
// users created by non-administrators must be verified
bool verified = !(!User.IsInRole(Constants.AdminRole) && user.Username != Constants.HostUser);
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
if (identityuser == null)
bool verified;
bool allowregistration;
if (user.Username == Constants.HostUser)
{
identityuser = new IdentityUser();
identityuser.UserName = user.Username;
identityuser.Email = user.Email;
identityuser.EmailConfirmed = verified;
var result = await _identityUserManager.CreateAsync(identityuser, user.Password);
if (result.Succeeded)
{
user.LastLoginOn = null;
user.LastIPAddress = "";
newUser = _users.AddUser(user);
if (!verified)
{
Notification notification = new Notification();
notification.SiteId = user.SiteId;
notification.FromUserId = null;
notification.ToUserId = newUser.UserId;
notification.ToEmail = "";
notification.Subject = "User Account Verification";
string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser);
string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
notification.Body = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
notification.ParentId = null;
notification.CreatedOn = DateTime.UtcNow;
notification.IsDelivered = false;
notification.DeliveredOn = null;
_notifications.AddNotification(notification);
}
verified = true;
allowregistration = true;
}
else
{
verified = User.IsInRole(Constants.AdminRole); // only users created by administrators are verified
allowregistration = _sites.GetSite(user.SiteId).AllowRegistration;
}
// assign to host role if this is the host user ( initial installation )
if (user.Username == Constants.HostUser)
if (allowregistration)
{
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
if (identityuser == null)
{
identityuser = new IdentityUser();
identityuser.UserName = user.Username;
identityuser.Email = user.Email;
identityuser.EmailConfirmed = verified;
var result = await _identityUserManager.CreateAsync(identityuser, user.Password);
if (result.Succeeded)
{
user.LastLoginOn = null;
user.LastIPAddress = "";
newUser = _users.AddUser(user);
if (!verified)
{
Notification notification = new Notification();
notification.SiteId = user.SiteId;
notification.FromUserId = null;
notification.ToUserId = newUser.UserId;
notification.ToEmail = "";
notification.Subject = "User Account Verification";
string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser);
string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
notification.Body = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
notification.ParentId = null;
notification.CreatedOn = DateTime.UtcNow;
notification.IsDelivered = false;
notification.DeliveredOn = null;
_notifications.AddNotification(notification);
}
// assign to host role if this is the host user ( initial installation )
if (user.Username == Constants.HostUser)
{
int hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId;
UserRole userrole = new UserRole();
userrole.UserId = newUser.UserId;
userrole.RoleId = hostroleid;
userrole.EffectiveDate = null;
userrole.ExpiryDate = null;
_userRoles.AddUserRole(userrole);
}
// add folder for user
Folder folder = _folders.GetFolder(user.SiteId, "Users\\");
if (folder != null)
{
_folders.AddFolder(new Folder
{
SiteId = folder.SiteId,
ParentId = folder.FolderId,
Name = "My Folder",
Path = folder.Path + newUser.UserId.ToString() + "\\",
Order = 1,
IsSystem = true,
Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"[" + newUser.UserId.ToString() + "]\"},{\"PermissionName\":\"View\",\"Permissions\":\"All Users\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"[" +
newUser.UserId.ToString() + "]\"}]"
});
}
}
}
else
{
var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false);
if (result.Succeeded)
{
newUser = _users.GetUser(user.Username);
}
}
if (newUser != null && user.Username != Constants.HostUser)
{
// add auto assigned roles to user for site
List<Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList();
foreach (Role role in roles)
{
int hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId;
UserRole userrole = new UserRole();
userrole.UserId = newUser.UserId;
userrole.RoleId = hostroleid;
userrole.RoleId = role.RoleId;
userrole.EffectiveDate = null;
userrole.ExpiryDate = null;
_userRoles.AddUserRole(userrole);
}
}
// add folder for user
Folder folder = _folders.GetFolder(user.SiteId, "Users\\");
if (folder != null)
{
_folders.AddFolder(new Folder
{
SiteId = folder.SiteId, ParentId = folder.FolderId, Name = "My Folder", Path = folder.Path + newUser.UserId.ToString() + "\\", Order = 1, IsSystem = true,
Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"[" + newUser.UserId.ToString() + "]\"},{\"PermissionName\":\"View\",\"Permissions\":\"All Users\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"[" +
newUser.UserId.ToString() + "]\"}]"
});
}
if (newUser != null)
{
newUser.Password = ""; // remove sensitive information
_logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
}
}
else
{
var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false);
if (result.Succeeded)
{
newUser = _users.GetUser(user.Username);
}
}
if (newUser != null && user.Username != Constants.HostUser)
{
// add auto assigned roles to user for site
List<Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList();
foreach (Role role in roles)
{
UserRole userrole = new UserRole();
userrole.UserId = newUser.UserId;
userrole.RoleId = role.RoleId;
userrole.EffectiveDate = null;
userrole.ExpiryDate = null;
_userRoles.AddUserRole(userrole);
}
}
if (newUser != null)
{
newUser.Password = ""; // remove sensitive information
_logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
_logger.Log(user.SiteId, LogLevel.Error, this, LogFunction.Create, "User Registration Is Not Enabled For Site. User Was Not Added {User}", user);
}
return newUser;