public void Configuration(IAppBuilder app) { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); MappingConfig.RegisterMapping(); ConfigureOAuth(app); app.UseCors(CorsOptions.AllowAll); UserManagerFactory = () => { var usermanager = new UserManager<IdentityEmployee>(new UserStore<IdentityEmployee>(new IdentityContext())); usermanager.UserValidator = new UserValidator<IdentityEmployee>(usermanager) { AllowOnlyAlphanumericUserNames = false }; return usermanager; }; RoleManagerFactory = () => { var rolemanager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new IdentityContext())); return rolemanager; }; }
public ActionResult Menu() { ApplicationDbContext userscontext = new ApplicationDbContext(); var userStore = new UserStore<ApplicationUser>(userscontext); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(userscontext); var roleManager = new RoleManager<IdentityRole>(roleStore); if (User.Identity.IsAuthenticated) { if (userManager.IsInRole(this.User.Identity.GetUserId(), "Admin")) { return PartialView("_AdminMenuView"); } else if (userManager.IsInRole(this.User.Identity.GetUserId(), "Principal")) { return PartialView("_PrincipalenuView"); } else { return PartialView("_Student"); } } return PartialView("_Empty"); }
public DevelopmentDefaultData(IOptions<DevelopmentSettings> options, IDataContext dataContext, UserManager<User> userManager, RoleManager<Role> roleManager) { this.settings = options.Value; this.dataContext = dataContext; this.userManager = userManager; this.roleManager = roleManager; }
public EmployeeAdminRepository() { AspContext = new IdentityDbContext(); _db = new GtrackDbContext(); UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>()); RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>()); }
public AccountController( UserManager userManager, IMultiTenancyConfig multiTenancyConfig, IUserEmailer userEmailer, RoleManager roleManager, TenantManager tenantManager, IUnitOfWorkManager unitOfWorkManager, ITenancyNameFinder tenancyNameFinder, ICacheManager cacheManager, IAppNotifier appNotifier, IWebUrlService webUrlService, AbpLoginResultTypeHelper abpLoginResultTypeHelper, IUserLinkManager userLinkManager, INotificationSubscriptionManager notificationSubscriptionManager) { _userManager = userManager; _multiTenancyConfig = multiTenancyConfig; _userEmailer = userEmailer; _roleManager = roleManager; _tenantManager = tenantManager; _unitOfWorkManager = unitOfWorkManager; _tenancyNameFinder = tenancyNameFinder; _cacheManager = cacheManager; _webUrlService = webUrlService; _appNotifier = appNotifier; _abpLoginResultTypeHelper = abpLoginResultTypeHelper; _userLinkManager = userLinkManager; _notificationSubscriptionManager = notificationSubscriptionManager; }
internal void AddUserAndRole() { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("administrator")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "******", }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { //userMgr.RemoveFromRoles(user.Id, "read", "edit"); IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
public static void Initialize(MacheteContext DB) { IdentityResult ir; var rm = new RoleManager<IdentityRole> (new RoleStore<IdentityRole>(DB)); ir = rm.Create(new IdentityRole("Administrator")); ir = rm.Create(new IdentityRole("Manager")); ir = rm.Create(new IdentityRole("Check-in")); ir = rm.Create(new IdentityRole("PhoneDesk")); ir = rm.Create(new IdentityRole("Teacher")); ir = rm.Create(new IdentityRole("User")); ir = rm.Create(new IdentityRole("Hirer")); // This role is used exclusively for the online hiring interface var um = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(DB)); var user = new ApplicationUser() { UserName = "******", IsApproved = true, Email = "*****@*****.**" }; ir = um.Create(user, "ChangeMe"); ir = um.AddToRole(user.Id, "Administrator"); //Default Administrator, edit to change ir = um.AddToRole(user.Id, "Teacher"); //Required to make tests work DB.Commit(); }
public ActionResult Index() { var users = UserManager.Users.ToArray(); var context = new ApplicationDbContext(); var db = new AromaContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var roles = roleManager.Roles.ToArray(); var userRoles = new List<UserRoleViewModel>(); ViewBag.Roles = roles.Select(m=>m.Name).ToArray(); foreach (var user in users) { var userClient = db.UserClients.FirstOrDefault(m => m.UserId.ToString() ==user.Id); var data = new UserRoleViewModel() { Id = user.Id, Username = user.UserName, Roles = user.Roles.Select(m=>roles.First(r=>r.Id== m.RoleId).Name).ToList() }; if (userClient != null) { data.ClientId = userClient.ClientId.ToString(); } userRoles.Add(data); } return View(userRoles.OrderBy(m=>m.Username).ToList()); }
internal void AddUserAndRole() { // access the application context and create result variables. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object. var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); // create admin role if it doesn't already exist if (!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } // create a UserManager object based on the UserStore object and the ApplicationDbContext object. // defines admin email account var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new admin user was successfully created, add the new user to the "admin" role. if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin"); } }
public JsonData Insert(IdentityRole entity, string userId) { try { using (var db = new DataContext()) { if (entity == null) throw new ArgumentNullException("The new" + " record is null"); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); //Create Roles if they do not exist if (!roleManager.RoleExists(entity.Name)) { roleManager.Create(new IdentityRole(entity.Name)); } db.SaveChanges(); return DataHelpers.ReturnJsonData(entity, true, "Saved successfully", 1); } } catch (Exception e) { return DataHelpers.ExceptionProcessor(e); } }
public ActionResult Users() { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); if (!roleManager.RoleExists("user")) { var nRole = new IdentityRole("user"); roleManager.Create(nRole); } if (!roleManager.RoleExists("admin")) { var nRole = new IdentityRole("admin"); roleManager.Create(nRole); } if (!roleManager.RoleExists("moderator")) { var nRole = new IdentityRole("moderator"); roleManager.Create(nRole); } if (!roleManager.RoleExists("journalist")) { var nRole = new IdentityRole("journalist"); roleManager.Create(nRole); } var vm = new AdminUsersViewModel(); vm.Users = db.Users.OrderBy(x => x.UserName).ToList(); vm.Roles = db.Roles.ToList(); return View(vm); }
public int GetUsersCountInRole(string role) { var roleStore = new RoleStore<IdentityRole>(this.dbContext); var roleManager = new RoleManager<IdentityRole>(roleStore); int count = roleManager.FindByName(role).Users.Count; return count; }
public ActionResult ChangeRoleOfUserInGroup(string mail) { //SKapa VM instans UserChangeRoleViewModel changeVM = new UserChangeRoleViewModel(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); //Välj en user till Viewmodell //ViewBag.Name = changeVM.Name; changeVM.Users = repo.ApplicationUsers().Select(u => new SelectListItem { Text = u.UserName, Value = u.Id, }); //ApplicationUser usr = repo.ApplicationUsers().First(); //Välj vilken av users roll som skall ändras //List<IdentityRole> cVM = new List<IdentityRole>(); changeVM.SelectedUser = repo.ApplicationUsers().Single(m => m.Email == mail).Id; changeVM.OldRoles = userManager.GetRoles(changeVM.SelectedUser).Select(o => new SelectListItem { Text = o, Value = o }); //Välj en ny roll till Viewmodell changeVM.Roles = repo.RolesList().Select(r => new SelectListItem { Text = r.Name, Value = r.Name }); //Returna View med VM return View(changeVM); }
public ActionResult Create(ClientViewModel client) { if (!ModelState.IsValid) return View(); //Register user and SingIn var accountController = new AccountController {ControllerContext = this.ControllerContext}; var user = accountController.RegisterAccount(new RegisterViewModel() { Email = client.Email, Password = client.Password }); accountController.SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false); //Add user to client role var userStore = new UserStore<ApplicationUser>(_context); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(_context); var roleManager = new RoleManager<IdentityRole>(roleStore); if (!roleManager.RoleExists("Client")) roleManager.Create(new IdentityRole("Client")); userManager.AddToRole(user.Id, "Client"); //Register client if (string.IsNullOrWhiteSpace(user.Id)) return View(); _context.Clients.Add(new Client() { Id = user.Id, Name = client.Name, Age = client.Age }); _context.SaveChanges(); return RedirectToAction("Index", "Home"); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Tạo role sẵn var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); List<string> roleNameList = new List<string> { "Admin" , "Designer" , "Mod" , "Uploader" , "Subteam" , "Subber" , "VIP" , "Member" }; foreach (string roleName in roleNameList) { if (!roleManager.RoleExists(roleName)) { var newRole = new IdentityRole(); newRole.Name = roleName; roleManager.Create(newRole); } } }
private async Task CreateAdminUser() { var username = "******";//ConfigurationManager.AppSettings["DefaultAdminUsername"]; var password = "******";//ConfigurationManager.AppSettings["DefaultAdminPassword"]; using (var context = new ApplicationDbContext()) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var role = new IdentityRole(RoleName); var result = await roleManager.RoleExistsAsync(RoleName); if (!result) { await roleManager.CreateAsync(role); } var user = await userManager.FindByNameAsync(username); if (user == null) { user = new ApplicationUser { UserName = username, Email = "*****@*****.**", First = "Big", Last="Admin Person" }; await userManager.CreateAsync(user, password); await userManager.AddToRoleAsync(user.Id, RoleName); } } }
internal static void AssignCustomerToRoles(UserManager userManager, RoleManager roleManager, CatalogManager catalogManager, Guid userId, Order order) { using (new ElevatedModeRegion(roleManager)) { bool associationsFound = false; foreach (OrderDetail detail in order.Details) { var product = catalogManager.GetProduct(detail.ProductId); if (product.AssociateBuyerWithRole != Guid.Empty) { var user = userManager.GetUser(userId); try { var role = roleManager.GetRole(product.AssociateBuyerWithRole); roleManager.AddUserToRole(user, role); associationsFound = true; } catch (ItemNotFoundException) { // skip over the role if it no longer exists } } } if (associationsFound) { roleManager.SaveChanges(); } } }
public UserController(IUserService service, IRedService redService, RoleManager<IdentityRole> roleManager) { Service = service; RedService = redService; RoleManager = roleManager; UserManager = new UserManager<ApplicationUserEntity>(new UserStore<ApplicationUserEntity>(new SearchContext())); }
public UserService(DbContext context, IRepository<User> users, IRepository<Message, int> messages) { this.users = users; this.messages = messages; this.userManager = new UserManager<User>(new UserStore<User>(context)); this.roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); }
public UserController(IEmployeeDataService employeeDataService, ITeamDataService teamDataService) { this.employeeDataService = employeeDataService; this.teamDataService = teamDataService; roleManager = Startup.RoleManagerFactory(); userManager = Startup.UserManagerFactory(); }
public async Task<ActionResult> Create(UserRoles role) { if (ModelState.IsValid) { // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); // Create a RoleManager object that is only allowed to contain IdentityRole objects. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. var roleMgr = new RoleManager<IdentityRole>(roleStore); // Then, you create the "Administrator" role if it doesn't already exist. if (!roleMgr.RoleExists(role.RoleName)) { IdRoleResult = roleMgr.Create(new IdentityRole(role.RoleName)); if (IdRoleResult.Succeeded) { // Handle the error condition if there's a problem creating the RoleManager object. ViewBag.StatusMessage = "Role has been added Successfully"; } else { ViewBag.StatusMessage = "The Role Already Exists"; } } } // If we got this far, something failed, redisplay form return View(); }
public UserRepository() { UserManager = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(ApplicationDbContext.Create())); RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ApplicationDbContext.Create())); }
public AdminController( IAuthorizationService authorizationService, ITypeFeatureProvider typeFeatureProvider, ISession session, IStringLocalizer<AdminController> stringLocalizer, IHtmlLocalizer<AdminController> htmlLocalizer, ISiteService siteService, IShapeFactory shapeFactory, RoleManager<Role> roleManager, IRoleProvider roleProvider, INotifier notifier, IEnumerable<IPermissionProvider> permissionProviders ) { TH = htmlLocalizer; _notifier = notifier; _roleProvider = roleProvider; _typeFeatureProvider = typeFeatureProvider; _permissionProviders = permissionProviders; _roleManager = roleManager; _shapeFactory = shapeFactory; _siteService = siteService; T = stringLocalizer; _authorizationService = authorizationService; _session = session; }
private void SeedRolesAndUsers(ETCCanadaContext context) { RoleManager<ApplicationRole> roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(context)); if (!roleManager.RoleExists("Administrator")) { roleManager.Create(new ApplicationRole("Administrator")); } if (!roleManager.RoleExists("User")) { roleManager.Create(new ApplicationRole("User")); } List<ApplicationUser> users = new List<ApplicationUser>(); ApplicationUser user1 = new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Administrator", LastName = "Administrator", IsApproved = true }; ApplicationUser user2 = new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "User", LastName = "User", IsApproved = true }; users.Add(user1); users.Add(user2); SeedDefaultUser(context, user1, "Administrator"); SeedDefaultUser(context, user2, "User"); //http://stackoverflow.com/questions/20470623/asp-net-mvc-asp-net-identity-seeding-roles-and-users //http://stackoverflow.com/questions/19280527/mvc5-seed-users-and-roles //http://stackoverflow.com/questions/19745286/asp-net-identity-db-seed }
//public StudentManager studentManager; //public RopeManager ropeManager; void Awake() { webSocketManager = FindObjectOfType<WebSocketManager>(); messageManager = FindObjectOfType<MessageManager>(); roleManager = FindObjectOfType<RoleManager>(); studentManager = FindObjectOfType<StudentManager>(); }
public IHttpActionResult addRole(RoleAddModel role) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); if (roleManager.RoleExists(role.roleName) == false) { try { var sa = roleManager.Create(new IdentityRole(role.roleName)); if (sa.Succeeded == true) { return Ok(sa); } else { return BadRequest(); } } catch (Exception) { return BadRequest(); } } return Conflict(); }
public UserController(IUserService service, RoleManager<IdentityRole> roleManager, IClanService clanService) { Service = service; RoleManager = roleManager; UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); ClanService = clanService; }
public bool CreateRole(string name) { var rm = new RoleManager<IdentityRole>( new RoleStore<IdentityRole>(new ApplicationContext())); IdentityResult idResult = rm.Create(new IdentityRole(name)); return idResult.Succeeded; }
public AuthRepository() { _ctx = new NotificacionesContext(); var store = new UserStore<ApplicationUser>(_ctx); _userManager = new UserManager<ApplicationUser>(store); _roleManaller = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_ctx)); }
public static void SeedUsers(ThesisContext context) { var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); const string name = "*****@*****.**"; const string password = "******"; const string roleName = "Admin"; var user = userManager.FindByName(name); if (user == null) { user = new ApplicationUser { UserName = name, Email = name, UserInformation = new UserInformation(name), Nickname = "Admin123" }; var result = userManager.Create(user, password); } user.MainPicture = "yos217.png"; var games = context.Games.ToList(); foreach (var game in games) { game.User = user; game.UserId = user.Id; } var posts = context.Posts.ToList(); foreach (var post in posts) { post.User = user; post.UserId = user.Id; } var gamesEvents = context.GamingEvents.ToList(); foreach (var gameEvent in gamesEvents) { gameEvent.Publisher = user; gameEvent.UserId = user.Id; } context.SaveChanges(); var role = roleManager.FindByName(roleName); if (role == null) { role = new IdentityRole(roleName); var roleresult = roleManager.Create(role); } var rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains(role.Name)) { var result = userManager.AddToRole(user.Id, role.Name); } }
public MyUserClaimsPrincipalFactory(UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager, IOptions <IdentityOptions> optionsAssessor) : base(userManager, roleManager, optionsAssessor) { }
public void Page_Load(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>(); var roleStore = new RoleStore <IdentityRole>(Models.ApplicationDbContext.Create()); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>()); var loggedInUser = User.Identity; var context = Models.ApplicationDbContext.Create(); if (!IsPostBack) { if (HasPassword(manager)) { if (manager.IsInRole(loggedInUser.GetUserId(), "Administrator")) { //var userRoles = Roles.GetRolesForUser(User.Identity.GetUserId()); var userRoles = roleManager.Roles; DataTable dtUsers = Models.ConversionClass.CreateDataTable(manager.Users.ToList()); ddlUsers.DataSource = dtUsers; ddlUsers.DataValueField = "Id"; ddlUsers.DataTextField = "UserName"; ddlUsers.DataBind(); BindRolesDetails(); //BindUserRoles(userRoles); //BindRolesDetails(userRoles); dvDisplayRoles.Visible = false; dvAssignRole.Visible = true; dvCreateRole.Visible = true; } else { //List<string> userRoles; List <string> roles; List <string> users; roles = (from r in roleManager.Roles select r.Name).ToList(); var userStore = new UserStore <Models.ApplicationUser>(context); var userManager = new UserManager <Models.ApplicationUser>(userStore); users = (from u in userManager.Users select u.UserName).ToList(); var user = userManager.FindByName(loggedInUser.GetUserName()); if (user == null) { throw new Exception("User not found!"); } var userRoleIds = (from r in user.Roles select r.RoleId); var userRoles = (from id in userRoleIds let r = roleManager.FindById(id) select new CustomRole { Name = r.Name }).ToList(); DataTable dtRoles = Models.ConversionClass.CreateDataTable(userRoles); BindUserRoles(dtRoles); dvDisplayRoles.Visible = true; dvAssignRole.Visible = false; dvCreateRole.Visible = false; } } } }
public RoleAdminController(RoleManager <IdentityRole> roleMgr, UserManager <AppUser> userMgr) { roleManager = roleMgr; userManager = userMgr; }
public static async Task AddAdmin(IServiceProvider serviceProvider) { AppDbContext _db = serviceProvider.GetRequiredService <AppDbContext>(); UserManager <AppUser> _userManager = serviceProvider.GetRequiredService <UserManager <AppUser> >(); RoleManager <IdentityRole> _roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); //TODO: Add the needed roles //if role doesn't exist, add it if (await _roleManager.RoleExistsAsync("Manager") == false) { await _roleManager.CreateAsync(new IdentityRole("Manager")); } if (await _roleManager.RoleExistsAsync("Customer") == false) { await _roleManager.CreateAsync(new IdentityRole("Customer")); } if (await _roleManager.RoleExistsAsync("Employee") == false) { await _roleManager.CreateAsync(new IdentityRole("Employee")); } //check to see if the manager has been added AppUser manager = _db.Users.FirstOrDefault(u => u.Email == "*****@*****.**"); //if manager hasn't been created, then add them if (manager == null) { manager = new AppUser(); manager.UserName = "******"; manager.Email = "*****@*****.**"; manager.PhoneNumber = "(512)555-5555"; manager.FirstName = "Admin"; //TODO: Add any other fields for your app user class here manager.LastName = "Example"; manager.Address = "123 Bevo Ln."; manager.City = "Austin"; manager.State = "TX"; manager.Zip = "78705"; //manager.DateAdded = DateTime.Today; //NOTE: Ask the user manager to create the new user //The second parameter for .CreateAsync is the user's password var result = await _userManager.CreateAsync(manager, "Abc123!"); if (result.Succeeded == false) { throw new Exception("This user can't be added - " + result.ToString()); } _db.SaveChanges(); manager = _db.Users.FirstOrDefault(u => u.UserName == "*****@*****.**"); } //make sure user is in role if (await _userManager.IsInRoleAsync(manager, "Manager") == false) { await _userManager.AddToRoleAsync(manager, "Manager"); } //save changes _db.SaveChanges(); }
public IdentitySeeder(UserManager <ApplicationUser> userMgr, RoleManager <IdentityRole> roleMgr) { _userMgr = userMgr; _roleMgr = roleMgr; }
public Seed(UserManager <User> userManager, RoleManager <Role> roleManager) { _roleManager = roleManager; _userManager = userManager; }
public ManageUserController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager,RoleManager<IdentityRole> roleManager) : base() { this.signInManager = signInManager; this.userManager = userManager; this.roleManager = roleManager; }
internal FakeIdentityContextFactory(string databaseName) { if (string.IsNullOrEmpty(databaseName)) { throw new ArgumentException($"{nameof(databaseName)} is Null or Empty.", nameof(databaseName)); } IServiceCollection services = new ServiceCollection(); services.AddTransient <IConfiguration>((sp) => new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary <string, string> { { "databaseName", databaseName } }).Build()); services.AddDbContext <FakeIdentityContext>(); services.AddIdentity <ApplicationUser, ApplicationRole>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 3; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }) .AddEntityFrameworkStores <FakeIdentityContext>() .AddDefaultTokenProviders(); HttpRequest request = new DefaultHttpContext().Request; HttpContextAccessor contextAccessor = new HttpContextAccessor { HttpContext = request.HttpContext }; services.AddSingleton <IHttpContextAccessor>(contextAccessor); IServiceProvider serviceProvider = services.BuildServiceProvider(); contextAccessor.HttpContext.RequestServices = serviceProvider; ParkingDBContext context = serviceProvider.GetRequiredService <FakeIdentityContext>(); UserStore <ApplicationUser, ApplicationRole, ParkingDBContext, string> userStore = new UserStore <ApplicationUser, ApplicationRole, ParkingDBContext, string>(context); IOptions <IdentityOptions> serviceIOptions = serviceProvider.GetRequiredService <IOptions <IdentityOptions> >(); UserManager <ApplicationUser> serviceUserManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >(); ILogger <UserManager <ApplicationUser> > serviceILoggerUserManager = serviceProvider.GetRequiredService <ILogger <UserManager <ApplicationUser> > >(); RoleStore <ApplicationRole, ParkingDBContext, string> roleStore = new RoleStore <ApplicationRole, ParkingDBContext, string>(context); RoleManager <ApplicationRole> serviceRoleManager = serviceProvider.GetRequiredService <RoleManager <ApplicationRole> >(); ILogger <RoleManager <ApplicationRole> > serviceILoggerRoleManager = serviceProvider.GetRequiredService <ILogger <RoleManager <ApplicationRole> > >(); IHttpContextAccessor serviceIHttpContextAccessor = serviceProvider.GetRequiredService <IHttpContextAccessor>(); SignInManager <ApplicationUser> serviceSignInManager = serviceProvider.GetRequiredService <SignInManager <ApplicationUser> >(); ILogger <SignInManager <ApplicationUser> > serviceILoggerSignInManager = serviceProvider.GetRequiredService <ILogger <SignInManager <ApplicationUser> > >(); IAuthenticationSchemeProvider serviceIAuthenticationSchemeProvider = serviceProvider.GetRequiredService <IAuthenticationSchemeProvider>(); UserManager = new UserManager <ApplicationUser>( userStore, serviceIOptions, serviceUserManager.PasswordHasher, serviceUserManager.UserValidators, serviceUserManager.PasswordValidators, serviceUserManager.KeyNormalizer, serviceUserManager.ErrorDescriber, serviceProvider, serviceILoggerUserManager ); RoleManager = new RoleManager <ApplicationRole>( roleStore, serviceRoleManager.RoleValidators, serviceRoleManager.KeyNormalizer, serviceRoleManager.ErrorDescriber, serviceILoggerRoleManager ); SignInManager = new SignInManager <ApplicationUser>( UserManager, serviceIHttpContextAccessor, serviceSignInManager.ClaimsFactory, serviceIOptions, serviceILoggerSignInManager, serviceIAuthenticationSchemeProvider ); }
public RoleAdminController(AppDbContext context, UserManager <User> userManager, RoleManager <IdentityRole> roleManager) { _db = context; _userManager = userManager; _roleManager = roleManager; }
protected override void Seed(DashoundCoachTravels.Models.ApplicationDbContext context) { var userManager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); //Creating new role types for accounts var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); IdentityResult roleResult; // Adding new role types named: Administrator, Employee, User if (!roleManager.RoleExists("Administrator")) { roleResult = roleManager.Create(new IdentityRole("Administrator")); } if (!roleManager.RoleExists("Employee")) { roleResult = roleManager.Create(new IdentityRole("Employee")); } if (!roleManager.RoleExists("User")) { roleResult = roleManager.Create(new IdentityRole("User")); } //Adding sample users: 1 for each role type testing only: Basic|Employee|Admin var sampleAccount = userManager.FindByEmail("*****@*****.**"); if (sampleAccount == null) { var hasher = new PasswordHasher(); sampleAccount = new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, PasswordHash = hasher.HashPassword("user"), Name = "Jon", Surname = "Doe", Town = "aaa", Street = "streetA", NumHouse = "1", NumFlat = "12", ZIPCode = "22-222", Country = "Uganda" }; userManager.Create(sampleAccount); userManager.AddToRole(sampleAccount.Id, "User"); context.SaveChanges(); } sampleAccount = userManager.FindByEmail("*****@*****.**"); if (sampleAccount == null) { var hasher = new PasswordHasher(); sampleAccount = new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, PasswordHash = hasher.HashPassword("employee"), Name = "Jonatan", Surname = "Doppey", Town = "bbb", Street = "streetB", NumHouse = "2", NumFlat = "186", ZIPCode = "66-666", Country = "Nigeria" }; userManager.Create(sampleAccount); userManager.AddToRole(sampleAccount.Id, "Employee"); context.SaveChanges(); } sampleAccount = userManager.FindByEmail("*****@*****.**"); if (sampleAccount == null) { var hasher = new PasswordHasher(); sampleAccount = new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, PasswordHash = hasher.HashPassword("admin"), Name = "Jonny", Surname = "Dope", Town = "ccc", Street = "streetC", NumHouse = "79", NumFlat = "6", ZIPCode = "99-971", Country = "Egypt" }; userManager.Create(sampleAccount); userManager.AddToRole(sampleAccount.Id, "Administrator"); context.SaveChanges(); } // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. }
protected override void Seed(BugTracker.Models.ApplicationDbContext context) { var roleManager = new RoleManager <IdentityRole>( new RoleStore <IdentityRole>(context)); if (!context.Roles.Any(r => r.Name == "Admin")) { roleManager.Create(new IdentityRole { Name = "Admin" }); } if (!context.Roles.Any(r => r.Name == "ProjectManager")) { roleManager.Create(new IdentityRole { Name = "ProjectManager" }); } if (!context.Roles.Any(r => r.Name == "Developer")) { roleManager.Create(new IdentityRole { Name = "Developer" }); } if (!context.Roles.Any(r => r.Name == "Submitter")) { roleManager.Create(new IdentityRole { Name = "Submitter" }); } var userManager = new UserManager <ApplicationUser>( new UserStore <ApplicationUser>(context)); if (!context.Users.Any(u => u.Email == "*****@*****.**")) { userManager.Create(new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Caleb", LastName = "Fields", DisplayName = "JCFields", }, "Abc&123!"); } if (!context.Users.Any(u => u.Email == "*****@*****.**")) { userManager.Create(new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Paul", LastName = "Flynn", DisplayName = "PJ", }, "Abc&123!"); } if (!context.Users.Any(u => u.Email == "*****@*****.**")) { userManager.Create(new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Chase", LastName = "Price", DisplayName = "Pryce", }, "Abc&123!"); } if (!context.Users.Any(u => u.Email == "*****@*****.**")) { userManager.Create(new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Caitlyn", LastName = "Booth", DisplayName = "Booth", }, "Abc&123!"); } var userId = userManager.FindByEmail("*****@*****.**").Id; userManager.AddToRole(userId, "Admin"); userId = userManager.FindByEmail("*****@*****.**").Id; userManager.AddToRole(userId, "ProjectManager"); userId = userManager.FindByEmail("*****@*****.**").Id; userManager.AddToRole(userId, "Developer"); userId = userManager.FindByEmail("*****@*****.**").Id; userManager.AddToRole(userId, "Submitter"); }
public BaseController(RoleManager <IdentityRole> _roleManager, /* ILogger<LoginModel> logger,*/ UserManager <ApplicationUser> _userManager) { userManager = _userManager; roleManager = _roleManager; }
public static async Task SeedAsync(UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager) { //Seed Default User var defaultUser = new ApplicationUser { UserName = "******", Email = "*****@*****.**", FirstName = "Mukesh", LastName = "Murugan", EmailConfirmed = true, PhoneNumberConfirmed = true }; if (userManager.Users.All(u => u.Id != defaultUser.Id)) { var user = await userManager.FindByEmailAsync(defaultUser.Email); if (user == null) { await userManager.CreateAsync(defaultUser, "123Pa$$word!"); await userManager.AddToRoleAsync(defaultUser, Roles.Basic.ToString()); await userManager.AddToRoleAsync(defaultUser, Roles.Moderator.ToString()); await userManager.AddToRoleAsync(defaultUser, Roles.Admin.ToString()); await userManager.AddToRoleAsync(defaultUser, Roles.SuperAdmin.ToString()); } } }
public RoleManagementApiController(UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager) : base(userManager) { _userManager = userManager; _roleManager = roleManager; }
public CreateModel(RoleManager <IdentityRole> roleManager) { _roleManager = roleManager; }
public IndexModel(UserManager <User> userManager, RoleManager <IdentityRole <long> > roleManager) { _userManager = userManager; _roleManager = roleManager; }
public static void Initialize(IServiceProvider serviceProvider) { ApplicationDbContext context = serviceProvider.GetRequiredService <ApplicationDbContext>(); _userManager = serviceProvider.GetRequiredService <UserManager <Client> >(); _roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole <int> > >(); context.Database.Migrate(); if (!context.Users.Any()) { AddAdmin(); } if (context.Workshops.Any()) { return; } var carServiceTypes = new List <CarServices> { new CarServices { TireReplacement = true, AirConCharging = true, PunctureRepair = true, SuspensionAdjustment = true }, new CarServices { TireReplacement = true, AirConCharging = true, PunctureRepair = true, SuspensionAdjustment = false }, new CarServices { TireReplacement = true, AirConCharging = false, PunctureRepair = true, SuspensionAdjustment = false }, new CarServices { TireReplacement = false, AirConCharging = false, PunctureRepair = true, SuspensionAdjustment = false } }; var workShops = new List <Workshop> { new Workshop { Name = "Fix thy Car", Address = "Hogwarts School of Witchcraft and Wizardry", ProvidedServices = carServiceTypes[0] }, new Workshop { Name = "The Master Mechanic", Address = "Willy Wonka's Factory", ProvidedServices = carServiceTypes[1] }, new Workshop { Name = "Super Quick Fix", Address = "The Emerald City", ProvidedServices = carServiceTypes[2] }, new Workshop { Name = "Branded Repair", Address = "5. Gotham City", ProvidedServices = carServiceTypes[3] } }; foreach (var workShop in workShops) { context.Workshops.Add(workShop); } context.SaveChanges(); }
public RoleAppService(IRepository <Role> repository, RoleManager roleManager, UserManager userManager) : base(repository) { _roleManager = roleManager; _userManager = userManager; }
public HomeController(ILogger <HomeController> logger, ApplicationDbContext context, RoleManager <IdentityRole> roleManager) { _roleManger = roleManager; _context = context; _logger = logger; }
public static void Seed(UserManager <Employee> userManager, RoleManager <IdentityRole> roleManager) { SeedRoles(roleManager); SeedUsers(userManager); }
public ClaimsController(UserManager <TIRIRIT_USER> userManager, RoleManager <IdentityRole <int> > roleManager) { this.userManager = userManager; this.roleManager = roleManager; }
/*private DbContextService _dbContext; * * public PackagesController(DbContextService dbContext) * { * _dbContext = dbContext; * } */ // SignInManager<ApplicationUser> signInManagerService, RoleManager<IdentityRole> roleManagerService, IProviderRepository providerRepo, ICustomerRepository customerRepo public PackagesController(IHostingEnvironment hostingEnv, UserManager <ApplicationUser> userManagerService, RoleManager <IdentityRole> roleManagerService, IEmailService emailService, ISmsService smsService, ICustomerRepository customerRepo, IProviderRepository providerRepo, IPackageRepository packageRepo, IFeedbackRepository feedbackRepo, IBookingRepository bookingRepo) { _hostingEnv = hostingEnv; _packageRepo = packageRepo; _customerRepo = customerRepo; _providerRepo = providerRepo; _feedbackRepo = feedbackRepo; _bookingRepo = bookingRepo; _emailService = emailService; _smsService = smsService; _userManagerService = userManagerService; _roleManagerService = roleManagerService; }
public UserManagerService(UserManager<AppIdentityUser> userMenager, IAuthenticationManager authenticationManager, RoleManager<IdentityRole> roleManager) { this._userMenager = userMenager; this._authenticationManager = authenticationManager; this._roleManager = roleManager; //Pasword validation rules _userMenager.UserValidator = new UserValidator<AppIdentityUser>(userMenager) { RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = false }; _userMenager.PasswordValidator = new PasswordValidator() { RequiredLength = 6, RequireLowercase = true, RequireUppercase = true, RequireDigit = true }; _signInMenager = new SignInManager<AppIdentityUser, string>(_userMenager, _authenticationManager); //_userMenager.UserLockoutEnabledByDefault = true; //_userMenager.DefaultAccountLockoutTimeSpan = TimeSpan.FromDays(int.MaxValue); //_userMenager.SetLockoutEnabled(user.Id, enabled) // Enables or disables lockout for a user //Register e-mail service for identity _userMenager.EmailService = new EmailService(); //Token provider for password reset var dataProtectionProvider = Startup.dataProtectionProvider; if (dataProtectionProvider != null) { IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity"); userMenager.UserTokenProvider = new DataProtectorTokenProvider<AppIdentityUser>(dataProtector); } }