public ActionResult RemoveRole(string id, string role) { var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); var user = userManager.Users.First(u => u.Id == id); // code to prevent removing the last administrator if (role == "Administrator") { var adminUsers = userManager.Users.ToList() .Where(u => userManager.IsInRole(u.Id, "Administrator")) .ToList().Count(); if (adminUsers < 2) { //For some reason ViewBag does not work here. Switched to Session and now it works. Session["CannotRemoveLastAdminError"] = "Cannot remove last administrator."; return(RedirectToAction("Details", "Admin", new { id = user.Id })); } } userManager.RemoveFromRole(id, role); if (user.EmployeeID != null) { try { var usrMgr = new LogicLayer.UserManager(); usrMgr.DeleteEmployeeRole((int)user.EmployeeID, role); } catch (Exception) { // nothing to do } } return(RedirectToAction("Details", "Admin", new { id = user.Id })); }
public ActionResult RemoveRole(string id, string role) { var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); var user = userManager.Users.First(u => u.Id == id); if (role == "Administrator") { var adminUsers = userManager.Users.ToList().Where(u => userManager.IsInRole(u.Id, "Administrator")).ToList().Count(); if (adminUsers < 2) { ViewBag.Error = "Cannot remove last Administrator"; return(RedirectToAction("Details", "Admin", new { id = user.Id })); } } userManager.RemoveFromRole(id, role); if (user.EmployeeID != null) { try { var usrMgr = new LogicLayer.UserManager(); usrMgr.DeleteUserRole((int)user.EmployeeID, role); } catch (Exception) { //Do nothing } } return(RedirectToAction("Details", "Admin", new { id = user.Id })); }
// GET: Admin/Details/5 public ActionResult Details(string id) { ViewBag.Title = "User Details"; if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } //ApplicationUser applicationUser = db.ApplicationUsers.Find(id); userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationUser applicationUser = userManager.FindById(id); if (applicationUser == null) { return(HttpNotFound()); } // get a list of roles the user has and put them into a viewbag as roles // along with a list of roles the user doesn't have as noRoles var usrMgr = new LogicLayer.UserManager(); var allRoles = usrMgr.GetEmployeeRoles(); var roles = userManager.GetRoles(id); var noRoles = allRoles.Except(roles); ViewBag.Roles = roles; ViewBag.NoRoles = noRoles; return(View(applicationUser)); }
public async Task <ActionResult> RegisterUser(RegisterViewModel model) { if (ModelState.IsValid) { // check to see if this user is in the existing database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { var oldUser = usrMgr.AuthenticateUser(model.Email, model.Password); var user = new ApplicationUser { GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { string role = oldUser.Role; UserManager.AddToRole(user.Id, role); // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return(RedirectToAction("Index", "Admin")); } AddErrors(result); } else // not an existing user, create a user without roles { var user = new ApplicationUser { GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return(RedirectToAction("Index", "Admin")); } AddErrors(result); } } catch { // creating old user failed return(View(model)); } } // modelstate was not valid return(View(model)); }
/// <summary> /// Updater: Zach Behrensmeyer /// Updated: 4/21/2020 /// Update: Added Identity System Logic /// </summary> /// <param name="context"></param> protected override void Seed(WPFPresentation.Models.ApplicationDbContext context) { // 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. var userStore = new UserStore <ApplicationUser>(context); var userManager = new UserManager <ApplicationUser>(userStore); const string admin = "*****@*****.**"; const string adminPassword = "******"; LogicLayer.UserManager usermgr = new LogicLayer.UserManager(); LogicLayer.ERoleManager rolemgr = new LogicLayer.ERoleManager(); var roles = rolemgr.RetrieveAllERoles(); List <string> RoleNames = new List <string>(); foreach (var role in roles) { RoleNames.Add(role.ERoleID); } foreach (var role in RoleNames) { context.Roles.AddOrUpdate(r => r.Name, new IdentityRole() { Name = role }); } if (!RoleNames.Contains("Administrator")) { context.Roles.AddOrUpdate(r => r.Name, new IdentityRole() { Name = "Administrator" }); } if (!context.Users.Any(u => u.UserName == admin)) { var user = new ApplicationUser() { UserName = admin, Email = admin, GivenName = "PUAdmin", FamilyName = "Company" }; IdentityResult result = userManager.Create(user, adminPassword); context.SaveChanges(); if (result.Succeeded) { userManager.AddToRole(user.Id, "Administrator"); context.SaveChanges(); } } }
protected override void Seed(MVCPresentationLayer.Models.ApplicationDbContext context) { // 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. var userStore = new UserStore <ApplicationUser>(context); var userManager = new UserManager <ApplicationUser>(userStore); const string admin = "*****@*****.**"; const string adminPassword = "******"; // new code for step 6 // Note: There is purposely no using statement for LogicLayer. This is to force // programmers to use th fully qualified name for our internal UserManager, to // keep it clear that this is not the Identity systems UserManager class. LogicLayer.UserManager userMgr = new LogicLayer.UserManager(); var roles = userMgr.RetrievePersonRoles(); foreach (var role in roles) { context.Roles.AddOrUpdate(r => r.Name, new IdentityRole() { Name = role }); } if (!roles.Contains("Administrator")) { context.Roles.AddOrUpdate(r => r.Name, new IdentityRole() { Name = "Administrator " }); // Note: even though administrator should be in the list of roles, this check is // to remove any risk of it being missing due to deletion from the internal database. } if (!context.Users.Any(u => u.UserName == admin)) { var user = new ApplicationUser() { UserName = admin, Email = admin, GivenName = "Admin", FamilyName = "Company" }; IdentityResult result = userManager.Create(user, adminPassword); context.SaveChanges(); // updates the database // this code will add the Administrator role to admin if (result.Succeeded) { userManager.AddToRole(user.Id, "Administrator"); context.SaveChanges(); } } }
// // GET: /Manage/Index public async Task <ActionResult> Index(ManageMessageId?message) { LogicLayer.UserManager userMgr = new LogicLayer.UserManager(); LogicLayer.VolunteerManager volMgr = new LogicLayer.VolunteerManager(); LogicLayer.CustomerManager custMgr = new LogicLayer.CustomerManager(); ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var userId = User.Identity.GetUserId(); var userName = User.Identity.GetUserName(); var user = userMgr.getUserByEmail(userName); var volunteer = volMgr.RetrieveVolunteerFromEmail(User.Identity.Name); var customer = custMgr.RetrieveCustomerByCustomerEmail(User.Identity.Name); if (user == null && customer == null && volunteer != null) { ViewBag.FullName = volunteer.FirstName + " " + volunteer.LastName; ViewBag.Email = volunteer.Email; ViewBag.PhoneNumber = volunteer.PhoneNumber; } else if (user == null && customer != null && volunteer == null) { ViewBag.FullName = customer.FirstName + " " + customer.LastName; ViewBag.Email = customer.Email; ViewBag.PhoneNumber = customer.PhoneNumber; ViewBag.Address = customer.AddressLineOne + " " + customer.AddressLineTwo + ", " + customer.City + " " + customer.State; } else if (user != null && customer == null && volunteer == null) { ViewBag.FullName = user.FirstName + " " + user.LastName; ViewBag.Email = user.Email; ViewBag.PhoneNumber = user.PhoneNumber; ViewBag.Address = user.Address1 + " " + user.Address2 + ", " + user.City + " " + user.State; } var model = new IndexViewModel { HasPassword = HasPassword(), PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), Logins = await UserManager.GetLoginsAsync(userId), BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) }; return(View(model)); }
public async Task <ActionResult> RegisterEmployeeUser(RegisterEmployeeViewModel model) { if (ModelState.IsValid) { // Check to see if this user is in the existing database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { // If this user already exists, we need to use the regular Register method return(RedirectToAction("Register", "Account")); } // Not an existing user, create a DataObjects.User without roles else { var employee = new DataObjects.User() { // These fields are need by sp_insert_user Email = model.Email, FirstName = model.GivenName, LastName = model.FamilyName, PhoneNumber = model.PhoneNumber, }; // Add the DataObjects.User to Employe table if (usrMgr.AddUser(employee)) { var employeeID = usrMgr.RetrieveUserIDFromEmail(model.Email); var user = new ApplicationUser() { EmployeeID = employeeID, GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, "newuser"); if (result.Succeeded) { return(RedirectToAction("Index", "Admin")); } AddErrors(result); } } } catch { // Creating Employee Failed return(View(model)); } } // ModelState was not valid return(View(model)); }
public async Task <ActionResult> RegisterEmployeeUser(RegisterEmployeeViewModel model) { if (ModelState.IsValid) { // check to see if the user is in the existing database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { // if the user already exists, we need to use the regular Register method return(RedirectToAction("Register", "Account")); } else // not an existing user, create a DataObjects.User without any roles { var employee = new DataObjects.User() { // these fields are needed by sp_insert_user Email = model.Email, FirstName = model.GivenName, LastName = model.FamilyName, PhoneNumber = model.PhoneNumber }; if (usrMgr.CreateEmployee(employee.FirstName, employee.LastName, employee.PhoneNumber, employee.Email)) // add the DataObjects.User to Employee table { var employeeID = usrMgr.RetrieveUserIdFromEmail(model.Email); var user = new ApplicationUser // if it worked, create an Identity user { EmployeeID = employeeID, GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, "newuser"); if (result.Succeeded) // go back to Admin/Index View { return(RedirectToAction("Index", "Admin")); } AddErrors(result); } } } catch { // creating employee failed return(View(model)); } } // modelstate was not valid return(View(model)); }
protected override void Seed(SandwhichMVC.Models.ApplicationDbContext context) { var userStore = new UserStore <ApplicationUser>(context); var userManager = new UserManager <ApplicationUser>(userStore); const string admin = "*****@*****.**"; const string adminPassword = "******"; LogicLayer.UserManager userMg = new LogicLayer.UserManager(); var roles = userMg.RetrieveEmployeeRoles(); foreach (var role in roles) { context.Roles.AddOrUpdate(r => r.Name, new IdentityRole() { Name = role }); } if (!roles.Contains("Administrator")) { context.Roles.AddOrUpdate(r => r.Name, new IdentityRole() { Name = "Administrator" }); } if (!context.Users.Any(u => u.UserName == admin)) { var user = new ApplicationUser() { UserName = admin, Email = admin, GivenName = "Admin", FamilyName = "Company" }; IdentityResult result = userManager.Create(user, adminPassword); context.SaveChanges(); if (result.Succeeded) { userManager.AddToRole(user.Id, "Administrator"); context.SaveChanges(); } } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // check to see if this user is in the existing user database var usrMgr = new LogicLayer.UserManager(); try { var oldUser = usrMgr.AuthenticateUser(model.Email, model.Password); foreach (var role in oldUser.Roles) { UserManager.AddToRole(user.Id, role.RoleID); } } catch (Exception) { // what to do if the user is not an existing user } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult AddRole(string id, string role) { var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); var user = userManager.Users.First(u => u.Id == id); userManager.AddToRole(id, role); if (user.EmployeeID != null) { try { var usrMgr = new LogicLayer.UserManager(); usrMgr.CreateEmployeeRole((int)user.EmployeeID, role); } catch (Exception) { // nothing to do } } return(RedirectToAction("Details", "Admin", new { id = user.Id })); }
// GET: Admin/Details/5 public ActionResult Details(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationUser applicationUser = userManager.FindById(id); if (applicationUser == null) { return(HttpNotFound()); } var userMang = new LogicLayer.UserManager(); var allRoles = userMang.RetrieveEmployeeRoles(); var roles = userManager.GetRoles(id); var noRoles = allRoles.Except(roles); ViewBag.Roles = roles; ViewBag.NoRoles = noRoles; return(View(applicationUser)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { // check to see if this user is in the existing database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { // this requires the user to use the same password as the one in the internal database var oldUser = usrMgr.AuthenticateUser(model.Email, model.Password); var user = new ApplicationUser { // populate these fields with wxisting data from oldUser GivenName = oldUser.FirstName, FamilyName = oldUser.LastName, PersonID = oldUser.PersonID, // populate these fields normally UserName = model.Email, Email = model.Email }; // create the user with the Identity system UserManager normally var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // use the oldUser.Roles list to add the internally assigned roles to the user foreach (var role in oldUser.Roles) { UserManager.AddToRole(user.Id, role); } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } else // not an existing user, create a user withou { var user = new ApplicationUser { // We will uncomment the following two lines later, once our ViewModel and // our View are updated to ask for them: GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // my code var dbUser = new DataObjects.User { FirstName = model.GivenName, LastName = model.FamilyName, Email = model.Email }; usrMgr.AddNewlyRegisteredUser(dbUser, model.Password); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } } catch { // creating old user failed, probably because AuthenticateUser failed return(View(model)); } } // modelstate was not valid return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { // Check to see if this user is in the exising database LogicLayer.UserManager usrMgr = new LogicLayer.UserManager(); try { if (usrMgr.FindUser(model.Email)) { // This requires the user to use the same password as the one in the internal database. var oldUser = usrMgr.AuthenticateUser(model.Email, model.Password); var user = new ApplicationUser { // Populate thes fields with exising data from oldUser GivenName = oldUser.FirstName, FamilyName = oldUser.LastName, EmployeeID = oldUser.EmployeeID, // Populate these fields normally UserName = model.Email, Email = model.Email }; // Create the user with the Identity system UserManager normally. var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // Use the oldUser.Roles list to add the internally assigned roles to the user. foreach (var role in oldUser.Roles) { UserManager.AddToRole(user.Id, role); } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Not an existing user, create a user without roles. else { var user = new ApplicationUser { GivenName = model.GivenName, FamilyName = model.FamilyName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToAction("Index", "Home")); } AddErrors(result); } } catch { // Creating old user failed, probably because AuthenticateUser failed return(View(model)); } } // ModelState was not valid return(View(model)); }