internal void AddUserAndRole() { ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; RoleStore<IdentityRole> roleStore = new RoleStore<IdentityRole>(context); RoleManager<IdentityRole> roleMgr = new RoleManager<IdentityRole>(roleStore); //create admin role if(!roleMgr.RoleExists("admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" }); } //create master user UserManager<ApplicationUser> userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); ApplicationUser appUser = new ApplicationUser { UserName = "Adam", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Baseball1!"); //add to admin role if(!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin"); } }
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"); }
// GET: AspNetUsers/Details/5 public async Task<ActionResult> Details(string id) { AspNetUserDetailsViewModel mdl = new AspNetUserDetailsViewModel(); if(id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } mdl.User = await db.AspNetUsers.FindAsync(id); if(mdl.User == null) { return HttpNotFound(); } mdl.Roles = await db.AspNetRoles.ToListAsync(); var ctx = new ApplicationDbContext(); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ctx)); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx)); if(userManager.IsInRole(mdl.User.Id, "NetUser")) { mdl.RoleId = RoleManager.FindByName("NetUser")?.Id; } if(userManager.IsInRole(mdl.User.Id, "Admin")) { mdl.RoleId = RoleManager.FindByName("Admin")?.Id; } return View(mdl); }
private void AddPermisionToADM(ApplicationDbContext db) { var userManarge = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); var user = userManarge.FindByName("[email protected]"); if (!userManarge.IsInRole(user.Id, "View")) { userManarge.AddToRole(user.Id, "View"); } if (!userManarge.IsInRole(user.Id, "Create")) { userManarge.AddToRole(user.Id, "Create"); } if (!userManarge.IsInRole(user.Id, "Edit")) { userManarge.AddToRole(user.Id, "Edit"); } if (!userManarge.IsInRole(user.Id, "Delete")) { userManarge.AddToRole(user.Id, "Delete"); } if (!userManarge.IsInRole(user.Id, "Adm")) { userManarge.AddToRole(user.Id, "Adm"); } }
/// <summary> /// Checks for the three roles - Admin, Employee and Complainant and /// creates them if not present /// </summary> public static void InitializeRoles() { // Access the application context and create result variables. ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdUserResult; // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); RoleManager roleMgr = new RoleManager(); if (!roleMgr.RoleExists("Administrator")) { roleMgr.Create(new ApplicationRole { Name = "Administrator" }); } if (!roleMgr.RoleExists("Employee")) { roleMgr.Create(new ApplicationRole { Name = "Employee" }); } if (!roleMgr.RoleExists("Complainant")) { roleMgr.Create(new ApplicationRole { Name = "Complainant" }); } if (!roleMgr.RoleExists("Auditor")) { roleMgr.Create(new ApplicationRole { Name = "Auditor" }); } // Create a UserManager object based on the UserStore object and the ApplicationDbContext // object. Note that you can create new objects and use them as parameters in // a single line of code, rather than using multiple lines of code, as you did // for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "Administrator", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Admin123"); // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Administrator")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Administrator"); } appUser = new ApplicationUser { UserName = "Auditor", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Auditor123"); // If the new "canEdit" user was successfully created, // add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Auditor")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Auditor"); } }
public ActionResult Index() { MyIdentityDbContext db = new MyIdentityDbContext(); UserStore<MyIdentityUser> userStore = new UserStore<MyIdentityUser>(db); UserManager<MyIdentityUser> userManager = new UserManager<MyIdentityUser>(userStore); MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name); NorthWindEntities northwindDb = new NorthWindEntities(); List<Customer> customers = null; if (userManager.IsInRole(user.Id, "Administrator")) { customers = northwindDb.Customers.ToList(); } if (userManager.IsInRole(user.Id, "Operator")) { customers = northwindDb.Customers.Where(m => m.City == "USA").ToList(); } ViewBag.FullName = user.FullName + " (" + user.UserName + ") !"; return View(customers); }
public EnumHelper.Roles GetCurrentUserRoleById(string userId) { var store = new UserStore<ApplicationUser>(_context); var manager = new UserManager<ApplicationUser>(store); EnumHelper.Roles userRole = EnumHelper.Roles.Viewer; if (manager.IsInRole(userId, EnumHelper.Roles.Admin.ToString())) { return EnumHelper.Roles.Admin; } else if (manager.IsInRole(userId, EnumHelper.Roles.Author.ToString())) { return EnumHelper.Roles.Author; } return userRole; }
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 protected]", Email = "[email protected]" }; 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("[email protected]").Id, "admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin"); } }
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 = "administrator", }; 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 ActionResult DeleteRoleForUser(string UserName, string RoleName) { var account = new AccountController(); ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (UserManager.IsInRole(user.Id, RoleName)) { UserManager.RemoveFromRole(user.Id, RoleName); var employee = context.Employees.Single(x => x.employeeFirstName == user.FirstName && x.employeeLastName ==user.LastName); var role = context.RolesForEmployees.Single(x => x.roleName == RoleName); var tmp = context.EmployeeRoles.Single(x => x.role == role && x.employee == employee); context.EmployeeRoles.Remove(tmp); context.SaveChanges(); ViewBag.ResultMessage = "Role removed from this user successfully !"; } else { ViewBag.ResultMessage = "This user doesn't belong to selected role."; } // prepopulat roles for the view dropdown var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); ViewBag.Roles = list; return View("ManageUserRoles"); }
public static void AddUserRole(string userName, string roleName) { using (var context = new ApplicationDbContext()) { try { if (!context.Roles.Any(r => r.Name == roleName)) return; var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var store = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(store); var user = userManager.FindByName(userName); var role = roleManager.FindByName(roleName); if (userManager.IsInRole(user.Id, role.Name)) return; userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. // ReSharper disable once UnusedVariable var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); throw; } } }
protected void btnRegister_Click(object sender, EventArgs e) { var userMgr = new UserManager(); var employee = new Employee() { UserName = UserName.Text, FirstName = FirstName.Text, LastName = LastName.Text, PhoneNumber = PhoneNumber.Text, Email = Email.Text, Department = (Grievance.GrievanceTypes)Convert.ToInt32(Department.SelectedValue) }; IdentityResult IdUserResult = userMgr.Create(employee, Password.Text); if (IdUserResult.Succeeded) { if (!userMgr.IsInRole(employee.Id, "Employee")) // Only users of type "Employee" can be created from the "Register Employee" page. { IdUserResult = userMgr.AddToRole(employee.Id, "Employee"); } SuccessMessage.Text = "Employee created successfully"; SuccessMessage.Visible = true; ErrorMessage.Visible = false; UserName.Text = FirstName.Text = LastName.Text = PhoneNumber.Text = Email.Text = Password.Text = ConfirmPassword.Text = string.Empty; } else { ErrorMessage.Text = IdUserResult.Errors.FirstOrDefault(); ErrorMessage.Visible = true; SuccessMessage.Visible = false; } }
internal void AddUserAndRole() { Models.ApplicationDbContext db = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(db); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("canEdit")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var appUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "NhatSinh123*"); if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "canEdit")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "canEdit"); } }
internal bool UpdateUser(string username, string realUsername, string permission) { IdentityResult result = null; Models.ApplicationDbContext context = new Models.ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var user = userMgr.FindByName(username); if (!string.IsNullOrEmpty(realUsername)) { user.RealUserName = realUsername; result = userMgr.Update(user); } if (!string.IsNullOrEmpty(permission) && !userMgr.IsInRole(user.Id, permission)) { userMgr.RemoveFromRoles(user.Id, "read", "edit", "administrator"); switch (permission) { case "administrator": result = userMgr.AddToRole(user.Id, "administrator"); break; case "edit": result = userMgr.AddToRole(user.Id, "edit"); break; default: result = userMgr.AddToRole(user.Id, "read"); break; } } if (result == IdentityResult.Success) return true; else return false; }
// GET: Maintenance/UserRoleMaintenance public ActionResult Index() { if (Request.IsAuthenticated) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!userManager.IsInRole(User.Identity.GetUserId(), "System Admin")) { return RedirectToAction("AccessBlock", "Account", new { area = "" }); } else { // prepopulat roles for the view dropdown var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); var schemeList = db.Schemes.Select(m => new { Value = m.Name, Text = m.Name }).Distinct().ToList(); ViewBag.Roles = list; var listUsers = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList(); ViewBag.Users = listUsers; ViewBag.SchemeList = new MultiSelectList(schemeList, "Value", "Text"); return View(); } } else { return RedirectToAction("Login", "Account", new { area = "" }); } }
internal void AddUserAndRole() { // Access the application context and create result variable. Models.ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; // 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 "canEdit" role if it doesn't already exist. if (!roleMgr.RoleExists("canEdit")) IdRoleResult = roleMgr.Create(new IdentityRole { Name = "canEdit" }); // Create a UserManager object based on the UserStore objcet and the ApplicationDbContext objcet. // Note that you can create new objects and use them as parameters in a single line of code, rather than using multiple lines of code, as you did for the RoleManager object. var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "Pa$$word1"); // If the new "canEdit" user was successfully created, add the "canEdit" user to the "canEdit" role. if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "canEdit")) IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "canEdit"); }
internal void AddUserAndRole() { ApplicationDbContext context = new ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("Admin")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { Email = "[email protected]" }; IdUserResult = userMgr.Create(appUser, "adminA123..."); if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Admin")) { IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "canEdit"); } }
public ActionResult DeleteRoleForUser(string UserName, string RoleName) { if (ModelState.IsValid) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); ViewBag.Token = "2"; if (userManager.IsInRole(user.Id, RoleName)) { userManager.RemoveFromRole(user.Id, RoleName); ViewBag.ResultMessage = "Role removed from this user successfully !"; } else { ViewBag.ResultMessage = "This user doesn't belong to selected role."; } // prepopulat roles for the view dropdown var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); ViewBag.Roles = list; var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList(); ViewBag.userNames = userList; ViewBag.RolesForThisUser = userManager.GetRoles(user.Id); } return View("ManageUserRoles"); }
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 = "administrator", ImgUrl = "user2-160x160.jpg", Description = "High Level", SinceDate = new DateTime(2016, 1, 1) }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
public ActionResult Create([Bind(Include = "ID,Code,Name")] Scheme scheme) { if (Request.IsAuthenticated) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!userManager.IsInRole(User.Identity.GetUserId(), "System Admin")) { return RedirectToAction("AccessBlock", "Account", new { area = "" }); } else { if (ModelState.IsValid) { db.Schemes.Add(scheme); db.SaveChanges(); return RedirectToAction("Index"); } return View(scheme); } } else { return RedirectToAction("Login", "Account", new { area = "" }); } }
public static bool IsAdmin(this AspNetUser user) { using (var context = new ApplicationDbContext()) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); return userManager.IsInRole(user.Id, "admin"); } }
internal void AddToNormalUserRole(ApplicationUser user) { Models.ApplicationDbContext context = new ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!userMgr.IsInRole(userMgr.FindByEmail(user.Email).Id, "Normal")) { userMgr.AddToRole(userMgr.FindByEmail(user.Email).Id, "Normal"); } }
private void AddPermissionToSuperUser(ApplicationDbContext db) { //Variable que nos permiter manipular los usuarios, crear, elimina y mas: var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); // AquĆ ya el usuario existe: var user = userManager.FindByName("[email protected]"); //Verifico si el usuario ya tienes roles asignados, si no, se lo asigno : if (!userManager.IsInRole(user.Id, "View")) { userManager.AddToRole(user.Id, "View"); } if (!userManager.IsInRole(user.Id, "Edit")) { userManager.AddToRole(user.Id, "Edit"); } if (!userManager.IsInRole(user.Id, "Create")) { userManager.AddToRole(user.Id, "Create"); } if (!userManager.IsInRole(user.Id, "Delete")) { userManager.AddToRole(user.Id, "Delete"); } if (!userManager.IsInRole(user.Id, "Details")) { userManager.AddToRole(user.Id, "Details"); } if (!userManager.IsInRole(user.Id, "Orders")) { userManager.AddToRole(user.Id, "Orders"); } if (!userManager.IsInRole(user.Id, "Admin")) { userManager.AddToRole(user.Id, "Admin"); } if (!userManager.IsInRole(user.Id, "Inventories")) { userManager.AddToRole(user.Id, "Inventories"); } if (!userManager.IsInRole(user.Id, "Shopping")) { userManager.AddToRole(user.Id, "Shopping"); } }
public ActionResult Config(int id) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (Request.IsAuthenticated) { if (!userManager.IsInRole(User.Identity.GetUserId(), "Configuration") && !userManager.IsInRole(User.Identity.GetUserId(), "System Admin")) { return RedirectToAction("AccessBlock", "Account", new { area = "" }); } else { CalcConfiguration ProjectBoard = db.CalcConfiguration.Find(Convert.ToInt32(id)); var List = db.UserSession.Where(i => i.Record == id); if (List.Count() == 0) { UserSession UsersessionAdd = new UserSession(); UsersessionAdd.Section = "Calculation"; UsersessionAdd.Record = id; UsersessionAdd.StartTime = DateTime.Now; UsersessionAdd.Username = HttpContext.User.Identity.Name.ToString(); db.UserSession.Add(UsersessionAdd); db.SaveChanges(); } try { ViewData["SchemeName"] = ProjectBoard.Scheme; ViewData["CalcName"] = ProjectBoard.Name; } catch { } return View(); } } else { return RedirectToAction("Login", "Account", new { area = "" }); } }
public ActionResult Index() { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var allusers = db.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList(); //var workers = allusers.Where(x => x.Equals("a720143e-25b2-47fc-a642-5487304d173a")).ToList(); var workers = db.Users.ToList().Where(x => UserManager.IsInRole(x.Id, "Worker")).ToList(); ViewBag.Workers = workers; return View(); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { using (var ctx = new ApplicationDbContext()) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx)); if (!httpContext.User.Identity.IsAuthenticated) return false; var userId = httpContext.User.Identity.GetUserId(); var isInRole = userManager.IsInRole(userId, Roles); return isInRole; } }
public static SupplierViewModel ToViewModel(this Supplier supplier) { var isAccountActivated = true; if (!string.IsNullOrEmpty(supplier.AspNetUserId)) { var context = ServiceLocator.Current.Resolve<IApplicationDbContext>(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context as ApplicationDbContext)); isAccountActivated = userManager.IsInRole(supplier.AspNetUserId, Role.Supplier.ToString()); } var vm = new SupplierViewModel { Id = supplier.Id, Name = supplier.Name, Address = supplier.Address, VATStatus = supplier.VATStatus, RC = supplier.RC, Email = supplier.Email, IsActive = supplier.IsActive, IsAcceptingPayment = supplier.IsAcceptingPayment, Iban = supplier.Iban, Bank = supplier.Bank, Fax = supplier.Fax, Company = supplier.Company, PostalCode = supplier.PostalCode, CIF = supplier.CIF, BrandLogo = supplier.BrandLogo, BrandText = supplier.BrandText, AspNetUserId = supplier.AspNetUserId, IsAccountActivated = isAccountActivated }; if (supplier.IsNew) { vm.Contact = new ContactViewModel() { Type = ContactType.Contact }; vm.Admin = new ContactViewModel() { Type = ContactType.Admin }; vm.ActivityPackages = new List<ActivityPackageViewModel>(); } else { vm.Contact = (supplier.Contact ?? new Domain.Contact()).ToViewModel(); vm.Contact.Type = ContactType.Contact; vm.Admin = (supplier.Admin ?? new Domain.Contact()).ToViewModel(); vm.Admin.Type = ContactType.Admin; vm.ActivityPackages = new List<ActivityPackageViewModel>(supplier.ActivityPackages.ToViewModel()); } return vm; }
public ActionResult Index() { var userId = User.Identity.GetUserId(); var userManager = new UserManager<AppUser>(new UserStore<AppUser>(new ApplicationDbContext())); if(userId == null) { return View(); } else if(userManager.IsInRole(userId, Role.Student.ToString())) { return RedirectToAction("StudentIndex","Home"); } else if(userManager.IsInRole(userId, Role.Tutor.ToString())) { return RedirectToAction("TutorIndex","Home"); } else if(userManager.IsInRole(userId, "Admin")) { return RedirectToAction("AdminIndex","Home"); } return View(); }
/// <summary> /// Fixes the navbar login view. /// </summary> private void FixNavbarLoginView() { //Rolemanager var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>()); var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>()); //find controls from master page var adminView = (LoginView) Master.FindControl("lvAdminContent"); var employeeView = (LoginView) Master.FindControl("lvEmployeeContent"); var userStatus = (LoginView) Master.FindControl("lvUserStatus"); //find user from list //IdentityUser user = userManager.FindByName(listBoxAllUsers.SelectedValue); if (User.Identity.IsAuthenticated) { IdentityUser user = userManager.FindByName(User.Identity.Name); if (userManager.IsInRole(user.Id, "Admin")) { adminView.Visible = true; employeeView.Visible = false; userStatus.Visible = false; } else if (userManager.IsInRole(user.Id, "Employee")) { adminView.Visible = false; employeeView.Visible = true; userStatus.Visible = false; } else { adminView.Visible = false; employeeView.Visible = false; userStatus.Visible = true; } } }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var userMgr = new UserManager(); var thisUsers = userMgr.Users; ApplicationUser user = userMgr.Find(UserName.Text, Password.Text); if (user != null) { if (!userMgr.IsInRole(user.Id, rdUserRole.Text)) { FailureText.Text = "Invalid username or password"; ErrorMessage.Visible = true; return; } IdentityHelper.SignIn(userMgr, user, RememberMe.Checked); //ApplicationDbContext dbcon = new ApplicationDbContext(); //Grievance gr = new Grievance(); //gr.GrievanceDescription ="hello"; //gr.DateLogged = DateTime.Now; //gr.TargetCompletionDate = DateTime.Now; //gr.ResolutionStatus = Grievance.ResolutionStatuses.Created; ////gr.DateLogged = DateTime.Now; //dbcon.Grievances.Add(gr); //dbcon.SaveChanges(); if (rdUserRole.Text == "Auditor") { Response.Redirect("~/AuditorPortal/Complaints.aspx"); } else if (rdUserRole.Text == "Administrator") { Response.Redirect("~/AdministratorPortal/Complaints.aspx"); } else if (rdUserRole.Text == "Employee") { Response.Redirect("~/EmployeePortal/Tasks.aspx"); } IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }