Skip to content

Commit

Permalink
added migration script
Browse files Browse the repository at this point in the history
  • Loading branch information
snithyanantham committed Jul 16, 2020
1 parent 3c6f1ff commit ec47fb8
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 119 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace MyFamilyManager.Identity.API.Migrations.ApplicationDb
{
public partial class InitialApplicationDbContext : Migration
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

namespace MyFamilyManager.Identity.API.Migrations
namespace MyFamilyManager.Identity.API.Migrations.ConfigurationDb
{
public partial class InitialConfigurationDbContext : Migration
public partial class InitialCreateConfigurationDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace MyFamilyManager.Identity.API.Migrations
namespace MyFamilyManager.Identity.API.Migrations.ConfigurationDb
{
[DbContext(typeof(ConfigurationDbContext))]
partial class ConfigurationDbContextModelSnapshot : ModelSnapshot
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace MyFamilyManager.Identity.API.Migrations.PersistedGrantDb
{
public partial class InititalPersistedGrantDbContext : Migration
public partial class InitialCreatePersistedGrantDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@
<Compile Remove="Migrations\20200424065431_InitialIdentityServerPersistedGrantDbMigration.Designer.cs" />
<Compile Remove="Migrations\20200424065640_InitialIdentityServerConfigurationDbMigration.cs" />
<Compile Remove="Migrations\20200424065640_InitialIdentityServerConfigurationDbMigration.Designer.cs" />
<Compile Remove="Migrations\ApplicationDb\20200424073252_InitialApplicationDbContextMigration.cs" />
<Compile Remove="Migrations\ApplicationDb\20200424073252_InitialApplicationDbContextMigration.Designer.cs" />
<Compile Remove="Migrations\ApplicationDb\20200424074225_InitalAplicaionDbContextMigation.cs" />
<Compile Remove="Migrations\ApplicationDb\20200424074225_InitalAplicaionDbContextMigation.Designer.cs" />
<Compile Remove="Migrations\ApplicationDb\20200424074336_InitialApplicationDbContextMigration.cs" />
<Compile Remove="Migrations\ApplicationDb\20200424074336_InitialApplicationDbContextMigration.Designer.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
128 changes: 78 additions & 50 deletions src/Services/Identity/MyFamilyManager.Identity.API/SeedData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
using System.Linq;
using System.Security.Claims;
using IdentityModel;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -11,39 +14,62 @@ namespace MyFamilyManager.Identity.API
{
public static class SeedData
{
public static void EnsureSeedData(string connectionString)
public static void InitializeDatabase(IApplicationBuilder app)
{
var services = new ServiceCollection();
services.AddLogging();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(connectionString));
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
if (!context.Clients.Any())
{
foreach (var client in Config.Clients)
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}

using (var serviceProvider = services.BuildServiceProvider())
{
using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
if (!context.IdentityResources.Any())
{
foreach (var resource in Config.Ids)
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}

if (!context.ApiResources.Any())
{
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
context.Database.Migrate();
foreach (var resource in Config.Apis)
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}

var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var alice = userMgr.FindByNameAsync("alice").Result;
if (alice == null)
var applicationContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
applicationContext.Database.Migrate();

var userMgr = serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var alice = userMgr.FindByNameAsync("alice").Result;
if (alice == null)
{
alice = new ApplicationUser
{
alice = new ApplicationUser
{
UserName = "alice"
};
var result = userMgr.CreateAsync(alice, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
UserName = "AliceSmith@email.com",
FirstName = "Alice",
LastName = "Smith",
Email = "AliceSmith@email.com"
};
var result = userMgr.CreateAsync(alice, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}

result = userMgr.AddClaimsAsync(alice, new Claim[]{
result = userMgr.AddClaimsAsync(alice, new Claim[]{
new Claim(JwtClaimTypes.Name, "Alice Smith"),
new Claim(JwtClaimTypes.GivenName, "Alice"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
Expand All @@ -52,29 +78,32 @@ public static void EnsureSeedData(string connectionString)
new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json)
}).Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
}
else
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
}
else
{
}

var bob = userMgr.FindByNameAsync("bob").Result;
if (bob == null)
var bob = userMgr.FindByNameAsync("bob").Result;
if (bob == null)
{
bob = new ApplicationUser
{
bob = new ApplicationUser
{
UserName = "bob"
};
var result = userMgr.CreateAsync(bob, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
UserName = "BobSmith@email.com",
Email = "BobSmith@email.com",
FirstName = "Bob",
LastName = "Smith"
};
var result = userMgr.CreateAsync(bob, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}

result = userMgr.AddClaimsAsync(bob, new Claim[]{
result = userMgr.AddClaimsAsync(bob, new Claim[]{
new Claim(JwtClaimTypes.Name, "Bob Smith"),
new Claim(JwtClaimTypes.GivenName, "Bob"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
Expand All @@ -84,15 +113,14 @@ public static void EnsureSeedData(string connectionString)
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json),
new Claim("location", "somewhere")
}).Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
}
else
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
}
else
{
}
}
}
}
Expand Down
69 changes: 18 additions & 51 deletions src/Services/Identity/MyFamilyManager.Identity.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Builder;
Expand Down Expand Up @@ -63,20 +65,20 @@ public void ConfigureServices(IServiceCollection services)
.AddDefaultTokenProviders();

var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
//.AddConfigurationStore(options =>
//{
// options.ConfigureDbContext = b => b.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
// mysql => mysql.MigrationsAssembly(migrationsAssembly));
//})
//.AddOperationalStore(options =>
//{
// options.ConfigureDbContext = b => b.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
// mysql => mysql.MigrationsAssembly(migrationsAssembly));
// options.EnableTokenCleanup = true;
//})
//.AddInMemoryIdentityResources(Config.Ids)
//.AddInMemoryApiResources(Config.Apis)
//.AddInMemoryClients(Config.Clients)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b => b.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
mysql => mysql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b => b.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
mysql => mysql.MigrationsAssembly(migrationsAssembly));
options.EnableTokenCleanup = true;
})
.AddAspNetIdentity<ApplicationUser>();

builder.AddDeveloperSigningCredential();
Expand All @@ -98,7 +100,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// InitializeDatabase(app);
// SeedData.InitializeDatabase(app);
}
else
{
Expand All @@ -121,42 +123,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
});
}

private void InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();

var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
if (!context.Clients.Any())
{
foreach (var client in Config.Clients)
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}

if (!context.IdentityResources.Any())
{
foreach (var resource in Config.Ids)
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}

if (!context.ApiResources.Any())
{
foreach (var resource in Config.Apis)
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
}

}

}

0 comments on commit ec47fb8

Please sign in to comment.