improvements based on user import testing

This commit is contained in:
sbwalker 2023-09-23 09:04:18 -04:00
parent 30ad442dd1
commit edac046fcd
10 changed files with 184 additions and 116 deletions

View File

@ -17,7 +17,7 @@
<div class="row mb-1 align-items-center">
<Label Class="col-sm-3" For="username" HelpText="A unique username for a user. Note that this field can not be modified once it is saved." ResourceKey="Username"></Label>
<div class="col-sm-9">
<input id="username" class="form-control" @bind="@username" />
<input id="username" class="form-control" @bind="@_username" />
</div>
</div>
<div class="row mb-1 align-items-center">
@ -33,7 +33,7 @@
<Label Class="col-sm-3" For="confirm" HelpText="Please enter the password again to confirm it matches with the value above" ResourceKey="Confirm"></Label>
<div class="col-sm-9">
<div class="input-group">
<input id="confirm" type="@_passwordtype" class="form-control" @bind="@confirm" autocomplete="new-password" required />
<input id="confirm" type="@_passwordtype" class="form-control" @bind="@_confirm" autocomplete="new-password" required />
<button type="button" class="btn btn-secondary" @onclick="@TogglePassword" tabindex="-1">@_togglepassword</button>
</div>
</div>
@ -41,17 +41,25 @@
<div class="row mb-1 align-items-center">
<Label Class="col-sm-3" For="email" HelpText="The email address where the user will receive notifications" ResourceKey="Email"></Label>
<div class="col-sm-9">
<input id="email" class="form-control" @bind="@email" />
<input id="email" class="form-control" @bind="@_email" />
</div>
</div>
<div class="row mb-1 align-items-center">
<Label Class="col-sm-3" For="displayname" HelpText="The full name of the user" ResourceKey="DisplayName"></Label>
<div class="col-sm-9">
<input id="displayname" class="form-control" @bind="@displayname" />
<input id="displayname" class="form-control" @bind="@_displayname" />
</div>
</div>
<div class="row mb-1 align-items-center">
<Label Class="col-sm-3" For="notify" HelpText="Indicate if new users should receive an email notification" ResourceKey="Notify">Notify? </Label>
<div class="col-sm-9">
<select id="notify" class="form-select" @bind="@_notify" required>
<option value="True">@SharedLocalizer["Yes"]</option>
<option value="False">@SharedLocalizer["No"]</option>
</select>
</div>
</div>
</div>
}
</TabPanel>
<TabPanel Name="Profile" ResourceKey="Profile">
@ -96,13 +104,14 @@
@code {
private string _passwordrequirements;
private string username = string.Empty;
private string _username = string.Empty;
private string _password = string.Empty;
private string _passwordtype = "password";
private string _togglepassword = string.Empty;
private string confirm = string.Empty;
private string email = string.Empty;
private string displayname = string.Empty;
private string _confirm = string.Empty;
private string _email = string.Empty;
private string _displayname = string.Empty;
private string _notify = "True";
private List<Profile> profiles;
private Dictionary<string, string> settings;
private string category = string.Empty;
@ -139,17 +148,18 @@
{
try
{
if (username != string.Empty && _password != string.Empty && confirm != string.Empty && email != string.Empty && ValidateProfiles())
if (_username != string.Empty && _password != string.Empty && _confirm != string.Empty && _email != string.Empty && ValidateProfiles())
{
if (_password == confirm)
if (_password == _confirm)
{
var user = new User();
user.SiteId = PageState.Site.SiteId;
user.Username = username;
user.Username = _username;
user.Password = _password;
user.Email = email;
user.DisplayName = string.IsNullOrWhiteSpace(displayname) ? username : displayname;
user.Email = _email;
user.DisplayName = string.IsNullOrWhiteSpace(_displayname) ? _username : _displayname;
user.PhotoFileId = null;
user.SuppressNotification = !bool.Parse(_notify);
user = await UserService.AddUserAsync(user);
@ -161,7 +171,7 @@
}
else
{
await logger.LogError("Error Adding User {Username} {Email}", username, email);
await logger.LogError("Error Adding User {Username} {Email}", _username, _email);
AddModuleMessage(Localizer["Error.User.AddCheckPass"], MessageType.Error);
}
}
@ -177,7 +187,7 @@
}
catch (Exception ex)
{
await logger.LogError(ex, "Error Adding User {Username} {Email} {Error}", username, email, ex.Message);
await logger.LogError(ex, "Error Adding User {Username} {Email} {Error}", _username, _email, ex.Message);
AddModuleMessage(Localizer["Error.User.Add"], MessageType.Error);
}
}

View File

@ -12,6 +12,15 @@
<FileManager Id="importfile" @ref="_filemanager" Filter="txt" />
</div>
</div>
<div class="row mb-1 align-items-center">
<Label Class="col-sm-3" For="notify" HelpText="Indicate if new users should receive an email notification" ResourceKey="Notify">Notify? </Label>
<div class="col-sm-9">
<select id="notify" class="form-select" @bind="@_notify" required>
<option value="True">@SharedLocalizer["Yes"]</option>
<option value="False">@SharedLocalizer["No"]</option>
</select>
</div>
</div>
</div>
<br />
<button type="button" class="btn btn-success" @onclick="ImportUsers">@Localizer["Import"]</button>&nbsp;
@ -25,6 +34,8 @@
public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;
private string _notify = "True";
private async Task ImportUsers()
{
try
@ -33,10 +44,10 @@
if (fileid != -1)
{
ShowProgressIndicator();
var results = await UserService.ImportUsersAsync(PageState.Site.SiteId, fileid);
var results = await UserService.ImportUsersAsync(PageState.Site.SiteId, fileid, bool.Parse(_notify));
if (bool.Parse(results["Success"]))
{
AddModuleMessage(string.Format(Localizer["Message.Import.Success"], results["Rows"], results["Users"]), MessageType.Success);
AddModuleMessage(string.Format(Localizer["Message.Import.Success"], results["Users"]), MessageType.Success);
}
else
{

View File

@ -171,4 +171,10 @@
<data name="Password.Placeholder" xml:space="preserve">
<value>Password</value>
</data>
<data name="Notify.HelpText" xml:space="preserve">
<value>Indicate if new users should receive an email notification</value>
</data>
<data name="Notify.Text" xml:space="preserve">
<value>Notify?</value>
</data>
</root>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
@ -133,7 +133,7 @@
<value>User Import Failed. Please Review Your Event Log For More Detailed Information.</value>
</data>
<data name="Message.Import.Success" xml:space="preserve">
<value>Users Imported Successfully. {0} Rows Processed, {1} Users Imported.</value>
<value>User Import Successful. {0} Users Imported.</value>
</data>
<data name="Message.Import.Validation" xml:space="preserve">
<value>You Must Specify A User File For Import</value>
@ -141,4 +141,10 @@
<data name="Template" xml:space="preserve">
<value>Template</value>
</data>
<data name="Notify.HelpText" xml:space="preserve">
<value>Indicate if new users should receive an email notification</value>
</data>
<data name="Notify.Text" xml:space="preserve">
<value>Notify?</value>
</data>
</root>

View File

@ -146,8 +146,10 @@ namespace Oqtane.Services
/// <summary>
/// Bulk import of users
/// </summary>
/// <param name="siteId">ID of a <see cref="Site"/></param>
/// <param name="fileId">ID of a <see cref="File"/></param>
/// <param name="notify">Indicates if new users should be notified by email</param>
/// <returns></returns>
Task<Dictionary<string, string>> ImportUsersAsync(int siteId, int fileId);
Task<Dictionary<string, string>> ImportUsersAsync(int siteId, int fileId, bool notify);
}
}

View File

@ -127,9 +127,9 @@ namespace Oqtane.Services
return string.Format(passwordValidationCriteriaTemplate, minimumlength, uniquecharacters, digitRequirement, uppercaseRequirement, lowercaseRequirement, punctuationRequirement);
}
public async Task<Dictionary<string, string>> ImportUsersAsync(int siteId, int fileId)
public async Task<Dictionary<string, string>> ImportUsersAsync(int siteId, int fileId, bool notify)
{
return await PostJsonAsync<Dictionary<string, string>>($"{Apiurl}/import?siteid={siteId}&fileid={fileId}", null);
return await PostJsonAsync<Dictionary<string, string>>($"{Apiurl}/import?siteid={siteId}&fileid={fileId}&notify={notify}", null);
}
}
}

View File

@ -372,14 +372,14 @@ namespace Oqtane.Controllers
return requirements;
}
// POST api/<controller>/import?siteid=x&fileid=y
// POST api/<controller>/import?siteid=x&fileid=y&notify=z
[HttpPost("import")]
[Authorize(Roles = RoleNames.Admin)]
public async Task<Dictionary<string, string>> Import(string siteid, string fileid)
public async Task<Dictionary<string, string>> Import(string siteid, string fileid, string notify)
{
if (int.TryParse(siteid, out int SiteId) && SiteId == _tenantManager.GetAlias().SiteId && int.TryParse(fileid, out int FileId))
if (int.TryParse(siteid, out int SiteId) && SiteId == _tenantManager.GetAlias().SiteId && int.TryParse(fileid, out int FileId) && bool.TryParse(notify, out bool Notify))
{
return await _userManager.ImportUsers(SiteId, FileId);
return await _userManager.ImportUsers(SiteId, FileId, Notify);
}
else
{

View File

@ -19,6 +19,6 @@ namespace Oqtane.Managers
User VerifyTwoFactor(User user, string token);
Task<User> LinkExternalAccount(User user, string token, string type, string key, string name);
Task<bool> ValidatePassword(string password);
Task<Dictionary<string, string>> ImportUsers(int siteId, int fileId);
Task<Dictionary<string, string>> ImportUsers(int siteId, int fileId, bool notify);
}
}

View File

@ -157,12 +157,15 @@ namespace Oqtane.Managers
_notifications.AddNotification(notification);
}
else
{
if (!user.SuppressNotification)
{
string url = alias.Protocol + alias.Name;
string body = "Dear " + user.DisplayName + ",\n\nA User Account Has Been Successfully Created For You With The Username " + user.Username + ". Please Visit " + url + " And Use The Login Option To Sign In. If You Do Not Know Your Password, Use The Forgot Password Option On The Login Page To Reset Your Account.\n\nThank You!";
var notification = new Notification(user.SiteId, User, "User Account Notification", body);
_notifications.AddNotification(notification);
}
}
User.Password = ""; // remove sensitive information
_logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", User);
@ -183,7 +186,7 @@ namespace Oqtane.Managers
{
identityuser.Email = user.Email;
var valid = true;
if (user.Password != "")
if (!string.IsNullOrEmpty(user.Password))
{
var validator = new PasswordValidator<IdentityUser>();
var result = await validator.ValidateAsync(_identityUserManager, null, user.Password);
@ -195,7 +198,10 @@ namespace Oqtane.Managers
}
if (valid)
{
await _identityUserManager.UpdateAsync(identityuser);
if (!string.IsNullOrEmpty(user.Password))
{
await _identityUserManager.UpdateAsync(identityuser); // requires password to be provided
}
user = _users.UpdateUser(user);
_syncManager.AddSyncEvent(_tenantManager.GetAlias().TenantId, EntityNames.User, user.UserId, SyncEventActions.Update);
@ -460,7 +466,7 @@ namespace Oqtane.Managers
return result.Succeeded;
}
public async Task<Dictionary<string, string>> ImportUsers(int siteId, int fileId)
public async Task<Dictionary<string, string>> ImportUsers(int siteId, int fileId, bool notify)
{
var success = true;
int rows = 0;
@ -489,7 +495,25 @@ namespace Oqtane.Managers
if (!string.IsNullOrEmpty(row.Trim()))
{
var header = row.Replace("\"", "").Split('\t');
if (header[0].Trim() == "Email")
{
for (int index = 4; index < header.Length - 1; index++)
{
if (!string.IsNullOrEmpty(header[index].Trim()) && !profiles.Any(item => item.Name == header[index].Trim()))
{
_logger.Log(LogLevel.Error, this, LogFunction.Create, "User Import Contains Profile Name {Profile} Which Does Not Exist", header[index]);
success = false;
}
}
}
else
{
_logger.Log(LogLevel.Error, this, LogFunction.Create, "User Import File Is Not In Correct Format. Please Use Template Provided.");
success = false;
}
if (success)
{
// detail rows
while (reader.Peek() > -1)
{
@ -513,10 +537,12 @@ namespace Oqtane.Managers
user.Email = values[0];
user.Username = (!string.IsNullOrEmpty(username)) ? username : user.Email;
user.DisplayName = (!string.IsNullOrEmpty(displayname)) ? displayname : user.Username;
user.EmailConfirmed = true;
user.SuppressNotification = !notify;
user = await AddUser(user);
if (user == null)
{
_logger.Log(LogLevel.Error, this, LogFunction.Create, "Error Importing User {Email} {Username} {DisplayName}", email, username, displayname);
_logger.Log(LogLevel.Error, this, LogFunction.Create, "User Import Error Importing User {Email} {Username} {DisplayName}", email, username, displayname);
success = false;
}
}
@ -525,6 +551,7 @@ namespace Oqtane.Managers
if (!string.IsNullOrEmpty(displayname))
{
user.DisplayName = displayname;
user.Password = "";
user = await UpdateUser(user);
}
}
@ -597,6 +624,7 @@ namespace Oqtane.Managers
}
}
}
}
else
{
success = false;
@ -627,7 +655,6 @@ namespace Oqtane.Managers
// return results
var result = new Dictionary<string, string>();
result.Add("Success", success.ToString());
result.Add("Rows", rows.ToString());
result.Add("Users", users.ToString());
return result;

View File

@ -107,6 +107,12 @@ namespace Oqtane.Models
[NotMapped]
public bool EmailConfirmed { get; set; }
/// <summary>
/// Indicates if new user should be notified by email (set during user creation)
/// </summary>
[NotMapped]
public bool SuppressNotification { get; set; }
/// <summary>
/// Public User Settings
/// </summary>