Skip to content

Commit

Permalink
Merge pull request #42 from HoodDigital/6.0.9-temp
Browse files Browse the repository at this point in the history
6.0.9
  • Loading branch information
JorjeRedemption authored May 24, 2022
2 parents a797b2d + ab8272f commit 8dc7ad3
Show file tree
Hide file tree
Showing 20 changed files with 197 additions and 140 deletions.
2 changes: 1 addition & 1 deletion projects/Hood.Admin/Hood.Admin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<AssemblyName>Hood.Admin</AssemblyName>
<PackageId>Hood.Admin</PackageId>

<Version>6.0.8</Version>
<Version>6.0.9</Version>
<TargetFramework>net5.0</TargetFramework>
<Authors>Hood Digital;George Whysall;</Authors>
<OutputType>Library</OutputType>
Expand Down
2 changes: 1 addition & 1 deletion projects/Hood.Core.Admin/Hood.Core.Admin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<AssemblyName>Hood.Core.Admin</AssemblyName>
<PackageId>Hood.Core.Admin</PackageId>

<Version>6.0.8</Version>
<Version>6.0.9</Version>
<TargetFramework>net5.0</TargetFramework>
<Authors>Hood Digital;George Whysall;</Authors>
<OutputType>Library</OutputType>
Expand Down
2 changes: 1 addition & 1 deletion projects/Hood.Core/Hood.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<AssemblyName>Hood.Core</AssemblyName>
<PackageId>Hood.Core</PackageId>

<Version>6.0.8</Version>
<Version>6.0.9</Version>
<TargetFramework>net5.0</TargetFramework>
<Authors>Hood Digital;George Whysall;</Authors>
<OutputType>Library</OutputType>
Expand Down
137 changes: 84 additions & 53 deletions projects/Hood.Core/Models/HoodDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,24 +95,53 @@ public DbSet<TEntity> Set<TEntity, TKey>() where TEntity : BaseEntity<TKey>
}

public async virtual Task Seed()
{
await CheckDatabaseIsInitialisedAsync();

ApplicationUser siteAdmin = await GetOrUpdateSiteOwnerAsync();

await SetupRequiredRolesAsync();
await SetupHoodMediaDirectoriesAsync(siteAdmin);
await InitialiseHoodSettingsAsync();
await UpdateLegacyMediaDirectoryReferencesAsync();
await SetDatabaseVersionAsync();
}

protected virtual async Task SetupRequiredRolesAsync()
{
try
{
Option option = await Options.FirstOrDefaultAsync();
}
catch (SqlException ex)
{
if (ex.Message.Contains("Login failed for user") || ex.Message.Contains("permission was denied"))
{
throw new StartupException("There was a problem connecting to the database.", ex, StartupError.DatabaseConnectionFailed);
}
else if (ex.Message.Contains("Invalid object name"))
var roleManager = Engine.Services.Resolve<RoleManager<ApplicationRole>>();
var userManager = Engine.Services.Resolve<UserManager<ApplicationUser>>();
if (Engine.AccountManager.SupportsRoles())
{

throw new StartupException("There are migrations missing.", ex, StartupError.MigrationMissing);
// Check all required roles exist locally
foreach (string role in Models.Roles.All)
{
if (!await roleManager.RoleExistsAsync(role))
{
await Engine.AccountManager.CreateRoleAsync(role);
}
else
{
// If it does exist locally, ensure it has a remote id linked to it.
var localRole = await roleManager.FindByNameAsync(role);
if (!localRole.RemoteId.IsSet())
{
await Engine.AccountManager.CreateRoleAsync(role);
}
}
}
}
}
catch (Exception ex)
{
throw new StartupException("An error occurred syncing local roles with Auth0.", ex, StartupError.Auth0Issue);
}
}

protected virtual async Task<ApplicationUser> GetOrUpdateSiteOwnerAsync()
{
try
{
string ownerEmail = Engine.SiteOwnerEmail;
Expand Down Expand Up @@ -150,52 +179,52 @@ public async virtual Task Seed()
}
}

ApplicationUser siteAdmin = await Engine.AccountManager.GetUserByEmailAsync(Engine.SiteOwnerEmail);
var siteOwnerRef = await Options.SingleOrDefaultAsync(o => o.Id == "Hood.Settings.SiteOwner");
if (siteOwnerRef == null)
{
Options.Add(new Option
{
Id = "Hood.Settings.SiteOwner",
Value = siteAdmin.Id
});
}
else
{
siteOwnerRef.Value = siteAdmin.Id;
}
await SaveChangesAsync();

return siteAdmin;

}
catch (Exception ex)
{
throw new StartupException("An error occurred while loading or creating the admin user.", ex, StartupError.AdminUserSetupError);
}
}

ApplicationUser siteAdmin = await Engine.AccountManager.GetUserByEmailAsync(Engine.SiteOwnerEmail);
public virtual async Task CheckDatabaseIsInitialisedAsync()
{
try
{
var roleManager = Engine.Services.Resolve<RoleManager<ApplicationRole>>();
var userManager = Engine.Services.Resolve<UserManager<ApplicationUser>>();
if (Engine.AccountManager.SupportsRoles())
{
// Check all required roles exist locally
foreach (string role in Models.Roles.All)
{
if (!await roleManager.RoleExistsAsync(role))
{
await Engine.AccountManager.CreateRoleAsync(role);
}
else
{
// If it does exist locally, ensure it has a remote id linked to it.
var localRole = await roleManager.FindByNameAsync(role);
if (!localRole.RemoteId.IsSet())
{
await Engine.AccountManager.CreateRoleAsync(role);
}
}
}
}
}
catch (Exception ex)
{
throw new StartupException("An error occurred syncing local roles with Auth0.", ex, StartupError.Auth0Issue);
Option option = await Options.FirstOrDefaultAsync();
}

if (!Options.Any(o => o.Id == "Hood.Settings.SiteOwner"))
catch (SqlException ex)
{
Options.Add(new Option
if (ex.Message.Contains("Login failed for user") || ex.Message.Contains("permission was denied"))
{
Id = "Hood.Settings.SiteOwner",
Value = siteAdmin.Id
});
throw new StartupException("There was a problem connecting to the database.", ex, StartupError.DatabaseConnectionFailed);
}
else if (ex.Message.Contains("Invalid object name"))
{
throw new StartupException("There are migrations missing.", ex, StartupError.MigrationMissing);
}
}
}

protected virtual async Task SetupHoodMediaDirectoriesAsync(ApplicationUser siteAdmin)
{
if (!MediaDirectories.Any(o => o.Slug == MediaManager.SiteDirectorySlug && o.Type == DirectoryType.System))
{
MediaDirectories.Add(new MediaDirectory { DisplayName = "Default", Slug = MediaManager.SiteDirectorySlug, OwnerId = siteAdmin.Id, Type = DirectoryType.System });
Expand All @@ -215,7 +244,11 @@ public async virtual Task Seed()
{
MediaDirectories.Add(new MediaDirectory { DisplayName = "Property", Slug = MediaManager.PropertyDirectorySlug, OwnerId = siteAdmin.Id, Type = DirectoryType.System });
}
await SaveChangesAsync();
}

protected virtual async Task InitialiseHoodSettingsAsync()
{
if (!Options.Any(o => o.Id == "Hood.Settings.Theme"))
{
Options.Add(new Option { Id = "Hood.Settings.Theme", Value = JsonConvert.SerializeObject("default") });
Expand Down Expand Up @@ -355,8 +388,11 @@ public async virtual Task Seed()
Options.Add(new Option { Id = typeof(SeoSettings).ToString(), Value = JsonConvert.SerializeObject(new SeoSettings()) });
}
}
await SaveChangesAsync();
}


protected virtual async Task UpdateLegacyMediaDirectoryReferencesAsync()
{
if (Media.Any(o => o.DirectoryId == null))
{
// Save any existing seeding, in case directories needed creating.
Expand Down Expand Up @@ -405,14 +441,10 @@ public async virtual Task Seed()
}
}
}
}

if (!Options.Any(o => o.Id == "Hood.Api.SystemPrivateKey"))
{
string guid = Guid.NewGuid().ToString();
string key = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(guid));
Options.Add(new Option { Id = "Hood.Api.SystemPrivateKey", Value = JsonConvert.SerializeObject(key) });
}

protected virtual async Task SetDatabaseVersionAsync()
{
// Mark the database with the current version of Hood.
if (!Options.Any(o => o.Id == "Hood.Version"))
{
Expand All @@ -426,6 +458,5 @@ public async virtual Task Seed()

await SaveChangesAsync();
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,10 @@ namespace Hood.Services
public class AccountRepository : IAccountRepository
{
protected readonly HoodDbContext _db;
protected readonly IHttpContextAccessor _contextAccessor;
protected readonly LinkGenerator _linkGenerator;
protected readonly IMailService _mailService;
protected readonly IEmailSender _emailSender;

public AccountRepository()
{
_db = Engine.Services.Resolve<HoodDbContext>();
_contextAccessor = Engine.Services.Resolve<IHttpContextAccessor>();
_linkGenerator = Engine.Services.Resolve<LinkGenerator>();
_mailService = Engine.Services.Resolve<IMailService>();
_emailSender = Engine.Services.Resolve<IEmailSender>();
}

#region Helpers
Expand Down Expand Up @@ -190,16 +182,7 @@ public virtual async Task SetPhoneNumberAsync(ApplicationUser modelToUpdate, str
throw new Exception(setPhoneResult.Errors.FirstOrDefault().Description);
}
}
public virtual async Task SendVerificationEmail(ApplicationUser localUser, string userId, string returnUrl)
{
var code = await UserManager.GenerateEmailConfirmationTokenAsync(localUser);
var callbackUrl = _linkGenerator.GetUriByAction(_contextAccessor.HttpContext, "ConfirmEmail", "Account", new { userId = localUser.Id, code, returnUrl });
var verifyModel = new VerifyEmailModel(localUser, callbackUrl)
{
SendToRecipient = true
};
await _mailService.ProcessAndSend(verifyModel);
}

public virtual async Task<IdentityResult> ChangePassword(ApplicationUser user, string oldPassword, string newPassword)
{
return await UserManager.ChangePasswordAsync(user, oldPassword, newPassword);
Expand All @@ -208,22 +191,7 @@ public virtual async Task<IdentityResult> ResetPasswordAsync(ApplicationUser use
{
return await UserManager.ResetPasswordAsync(user, code, password);
}
public virtual async Task SendPasswordResetToken(ApplicationUser user)
{
string code = await UserManager.GeneratePasswordResetTokenAsync(user);
string callbackUrl = _linkGenerator.GetUriByAction(_contextAccessor.HttpContext, "ResetPassword", "Account", new { userId = user.Id, code });

MailObject message = new MailObject()
{
To = new SendGrid.Helpers.Mail.EmailAddress(user.Email),
PreHeader = "Reset your password.",
Subject = "Reset your password."
};
message.AddParagraph($"Please reset your password by clicking here:");
message.AddCallToAction("Reset your password", callbackUrl);
message.Template = MailSettings.WarningTemplate;
await _emailSender.SendEmailAsync(message);
}
public virtual async Task<IdentityResult> CreateAsync(ApplicationUser user, string password)
{
return await UserManager.CreateAsync(user, password);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,6 @@ public override async Task DeleteUserAsync(string localUserId, System.Security.C
// now delete the user
await base.DeleteUserAsync(localUserId, adminUser);
}
public override async Task SendVerificationEmail(ApplicationUser localUser, string userId, string returnUrl)
{
// get the users' current connected account.
// send a verification email on the whattheolddowntheold.
var authService = new Auth0Service();
var ticket = await authService.GetEmailVerificationTicket(userId, returnUrl);
var verifyModel = new VerifyEmailModel(localUser, ticket.Value)
{
SendToRecipient = true
};
await _mailService.ProcessAndSend(verifyModel);
}
public override Task<IdentityResult> ChangePassword(ApplicationUser user, string oldPassword, string newPassword)
{
throw new ApplicationException("This feature is disabled when using Auth0.");
Expand All @@ -70,10 +58,6 @@ public override Task<IdentityResult> ResetPasswordAsync(ApplicationUser user, st
{
throw new ApplicationException("This feature is disabled when using Auth0.");
}
public override Task SendPasswordResetToken(ApplicationUser user)
{
throw new ApplicationException("This feature is disabled when using Auth0.");
}
public override async Task<IdentityResult> CreateAsync(ApplicationUser user, string password)
{
return await base.CreateAsync(user, password);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public interface IAccountRepository
Task<MediaDirectory> GetDirectoryAsync(string id);
Task SetEmailAsync(ApplicationUser modelToUpdate, string email);
Task SetPhoneNumberAsync(ApplicationUser modelToUpdate, string email);
Task SendVerificationEmail(ApplicationUser localUser, string userId, string returnUrl);
Task<IdentityResult> ChangePassword(ApplicationUser user, string oldPassword, string newPassword);
Task<IdentityResult> ConfirmEmailAsync(ApplicationUser user, string code);
Task<IdentityResult> ResetPasswordAsync(ApplicationUser user, string code, string password);
Expand Down Expand Up @@ -54,7 +53,6 @@ public interface IAccountRepository

#region Statistics
Task<UserStatistics> GetStatisticsAsync();
Task SendPasswordResetToken(ApplicationUser user);
#endregion
}
}
2 changes: 0 additions & 2 deletions projects/Hood.Core/Services/EmailSender/EmailSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ namespace Hood.Services
{
public class EmailSender : IEmailSender
{
protected readonly IHttpContextAccessor _contextAccessor;
protected Models.MailSettings _mail;
protected Models.BasicSettings _info;
protected readonly IRazorViewRenderer _renderer;
Expand All @@ -24,7 +23,6 @@ public class EmailSender : IEmailSender

public EmailSender()
{
_contextAccessor = Engine.Services.Resolve<IHttpContextAccessor>();
_renderer = Engine.Services.Resolve<IRazorViewRenderer>();
}

Expand Down
Loading

0 comments on commit 8dc7ad3

Please sign in to comment.