Aliendreamer

extensionMiddleware

Nov 17th, 2018
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. namespace Eventures.WebApp.Extentions
  2. {
  3.     using System.Linq;
  4.     using System.Threading.Tasks;
  5.     using Microsoft.AspNetCore.Http;
  6.     using Microsoft.AspNetCore.Identity;
  7.     using Models;
  8.  
  9.     public class SeedRolesMiddleware
  10.     {
  11.         private readonly RequestDelegate _next;
  12.  
  13.         public SeedRolesMiddleware(RequestDelegate next)
  14.         {
  15.             _next = next;
  16.         }
  17.  
  18.         public async Task InvokeAsync(HttpContext context,
  19.             UserManager<EventureUser> userManager
  20.             , RoleManager<IdentityRole> roleManager)
  21.         {
  22.             if (!roleManager.Roles.Any())
  23.             {
  24.                 await SeedRoles(userManager, roleManager);
  25.             }
  26.  
  27.             // Call the next delegate/middleware in the pipeline
  28.             await _next(context);
  29.         }
  30.  
  31.         private async Task SeedRoles(
  32.             UserManager<EventureUser> userManager,
  33.             RoleManager<IdentityRole> roleManager)
  34.         {
  35.             await roleManager.CreateAsync(new IdentityRole
  36.             {
  37.                 Name = "admin"
  38.             });
  39.  
  40.             var user = new EventureUser
  41.             {
  42.                 UserName = "AppAdmin",
  43.                 FirstName = "Admin",
  44.                 LastName = "Admin",
  45.                 Email = "[email protected]",
  46.             };
  47.             await userManager.CreateAsync(user, "admin");
  48.  
  49.             await userManager.AddToRoleAsync(user, "admin");
  50.         }
  51.     }
  52. }
  53.  
  54. namespace Eventures.WebApp.Extentions
  55. {
  56.     using Microsoft.AspNetCore.Builder;
  57.  
  58.     public static class SeedRolesMiddlewareExtensions
  59.     {
  60.         public static IApplicationBuilder UseSeedRolesMiddleware(
  61.             this IApplicationBuilder builder)
  62.         {
  63.             return builder.UseMiddleware<SeedRolesMiddleware>();
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment