public async Task <ActionResult> CreateAdmin(AdminRegistrationViewModel model) { if (ModelState.IsValid) { var _firstname = model.FirstName; var _lastname = model.LastName; var _password = model.Password; var _email = model.Email; var _confmessage = "Now the Admin will have to confirm their email and they will offically be admins."; var user = new ApplicationUser { UserName = _email, Email = _email }; var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); var result = await UserManager.CreateAsync(user, _password); if (result.Succeeded) { //string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, _confmessage, _firstname); var special_user = new BTTUser { FirstName = _firstname, LastName = _lastname, ASPNetIdentityID = user.Id }; BeyondTheTutorContext db = new BeyondTheTutorContext(); var sub_user = new Admin(); sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Admins.Add(sub_user); UserManager.AddToRole(user.Id, "Admin"); await db.SaveChangesAsync(); TempData["created"] = "You have successfully created an admin. They will have to confirm their email to access administrator privilages."; return(RedirectToAction("Index", "AllUsers")); } TempData["error"] = "Adding admin failed. Please check with the database administrator for further help!"; AddErrors(result); return(View(model)); } // If we got this far, something failed, redisplay form TempData["error"] = "Something went wrong! please check if you did everything correctly."; return(View(model)); }
// See: https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97 // In this method we will create default User roles and Admin user for login private void CreateRolesandUsers() { // The context that Identity created ApplicationDbContext context = new ApplicationDbContext(); //the main database BeyondTheTutorContext db = new BeyondTheTutorContext(); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); /*roleManager.Delete(roleManager.FindByName(ROLES[0])); * roleManager.Delete(roleManager.FindByName(ROLES[1])); * roleManager.Delete(roleManager.FindByName(ROLES[2])); * roleManager.Delete(roleManager.FindByName(ROLES[3]));*/ // Create admin role and seed with the admin user/ // Assumes neither already exists if (!roleManager.RoleExists(ROLES[0])) { // Create role var role = new IdentityRole(ROLES[0]); // role name is "Admin" IdentityResult res = roleManager.Create(role); // Create user with this role string userPWD = "admin2020"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"]; string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"]; var user = new ApplicationUser { UserName = userEmail, EmailConfirmed = true, Email = userEmail }; // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work res = UserManager.Create(user, userPWD); if (res.Succeeded) { var special_user = new BTTUser { FirstName = "Tracy", LastName = "Boyson", ASPNetIdentityID = user.Id }; var sub_user = new Admin { ID = special_user.ID }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Admins.Add(sub_user); db.SaveChangesAsync(); } if (res.Succeeded) { var result1 = UserManager.AddToRole(user.Id, ROLES[0]); } } // Do we need another role? i.e. "User" // Create admin role and seed with the admin user/ // Assumes neither already exists if (!roleManager.RoleExists(ROLES[1])) { // Create role var role = new IdentityRole(ROLES[1]); // role name is "Professor" IdentityResult res = roleManager.Create(role); // Create user with this role string userPWD = "professor2020"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"]; string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"]; var user = new ApplicationUser { UserName = userEmail, Email = userEmail, EmailConfirmed = true }; // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work res = UserManager.Create(user, userPWD); if (res.Succeeded) { var special_user = new BTTUser { FirstName = "Becka", LastName = "Morgan", ASPNetIdentityID = user.Id }; var sub_user = new Professor { ID = special_user.ID, AdminApproved = true }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Professors.Add(sub_user); db.SaveChangesAsync(); } if (res.Succeeded) { var result1 = UserManager.AddToRole(user.Id, ROLES[1]); } } // Create admin role and seed with the admin user/ // Assumes neither already exists if (!roleManager.RoleExists(ROLES[2])) { // Create role var role = new IdentityRole(ROLES[2]); // role name is "Student" IdentityResult res = roleManager.Create(role); // Create user with this role string userPWD = "student2020"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"]; string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"]; var user = new ApplicationUser { UserName = userEmail, Email = userEmail, EmailConfirmed = true }; // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work res = UserManager.Create(user, userPWD); if (res.Succeeded) { var special_user = new BTTUser { FirstName = "Brandon", LastName = "Linton", ASPNetIdentityID = user.Id }; var sub_user = new Student { ID = special_user.ID, ClassStanding = "Junior", GraduatingYear = 2022 }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Students.Add(sub_user); db.SaveChangesAsync(); } if (res.Succeeded) { var result1 = UserManager.AddToRole(user.Id, ROLES[2]); } } // Create admin role and seed with the admin user/ // Assumes neither already exists if (!roleManager.RoleExists(ROLES[3])) { // Create role var role = new IdentityRole(ROLES[3]); // role name is "Tutor" IdentityResult res = roleManager.Create(role); // Create user with this role string userPWD = "tutor2020"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"]; string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"]; var user = new ApplicationUser { UserName = userEmail, Email = userEmail, EmailConfirmed = true }; // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work res = UserManager.Create(user, userPWD); if (res.Succeeded) { var special_user = new BTTUser { FirstName = "Victoria", LastName = "Rhine", ASPNetIdentityID = user.Id }; var sub_user = new Tutor { ID = special_user.ID, VNumber = "V00000000", ClassOf = 2020, AdminApproved = true }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Tutors.Add(sub_user); db.SaveChangesAsync(); } if (res.Succeeded) { var result1 = UserManager.AddToRole(user.Id, ROLES[3]); } //tutor number two userPWD = "tutor2020"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"]; userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"]; var tutor = new ApplicationUser { UserName = userEmail, Email = userEmail, EmailConfirmed = true }; res = UserManager.Create(tutor, userPWD); if (res.Succeeded) { var special_user = new BTTUser { FirstName = "Shay", LastName = "Green", ASPNetIdentityID = tutor.Id }; var sub_user = new Tutor { ID = special_user.ID, VNumber = "V11111111", ClassOf = 2021, AdminApproved = true }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Tutors.Add(sub_user); db.SaveChangesAsync(); } if (res.Succeeded) { var result1 = UserManager.AddToRole(tutor.Id, ROLES[3]); } } /*{ * * IdentityResult res; * * // Create user with this role * string userPWD = "student2020";// System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"]; * string userEmail = "*****@*****.**";// System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"]; * var user = new ApplicationUser * { * UserName = userEmail, * Email = userEmail, * EmailConfirmed = true * }; * // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same * // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work * * res = UserManager.Create(user, userPWD); * * if (res.Succeeded) * { * var special_user = new BTTUser * { * FirstName = "Maksim", * LastName = "Stoyanov", * ASPNetIdentityID = user.Id * }; * * var sub_user = new Student * { * ID = special_user.ID, * ClassStanding = "Senior", * GraduatingYear = 2020 * }; * * sub_user.BTTUser = special_user; * db.BTTUsers.Add(special_user); * db.Students.Add(sub_user); * db.SaveChangesAsync(); * } * * UserManager.AddToRole(user.Id, ROLES[2]); * }*/ /* * // creating Creating Professor role * if (!roleManager.RoleExists(ROLES[1])) // Professor Role * { * var role = new IdentityRole(); * role.Name = ROLES[1]; * roleManager.Create(role); * }*/ }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); // Error in call here. PasswordSingInAsync needs username not email, so either they need to be the same or you have to modify the // login page and loginviewmodel to get the username var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: BeyondTheTutorContext db = new BeyondTheTutorContext(); // Require the user to have a confirmed email before they can log on. var user = await UserManager.FindByNameAsync(model.Email); // Resolve the user via their email var roles = await UserManager.GetRolesAsync(user.Id); var confirmedByEmail = await UserManager.IsEmailConfirmedAsync(user.Id); var confirmedByAdmin = false; var userID = UserManager.FindByName(model.Email).Id; var currentUserID = db.BTTUsers.Where(m => m.ASPNetIdentityID.Equals(userID)).FirstOrDefault().ID; if (roles.Contains("Tutor")) { confirmedByAdmin = db.Tutors.Find(currentUserID).AdminApproved; } else if (roles.Contains("Professor")) { confirmedByAdmin = db.Professors.Find(currentUserID).AdminApproved; } if (user != null) { if (!confirmedByEmail && roles.Contains("Student")) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); ViewBag.error = "You must have a confirmed email to log on."; return(View()); } else if (!(roles.Contains("Admin") || roles.Contains("Student")) && (!confirmedByEmail || !confirmedByAdmin)) { ViewBag.error = "You must confirm your email and/or get special permission by emailing: [email protected]"; AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return(View()); } } if (roles.Contains("Admin")) { return(RedirectToAction("Index", "Home", new { area = "admin" })); } else if (roles.Contains("Professor")) { return(RedirectToAction("Index", "Home", new { area = "professor" })); } else if (roles.Contains("Student")) { return(RedirectToAction("Index", "Home", new { area = "student" })); } else if (roles.Contains("Tutor")) { return(RedirectToAction("Index", "Home", new { area = "tutor" })); } else { return(RedirectToAction("Index")); } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public async Task <ActionResult> Register(RegistrationTypes model) { bool isStudent, isTutor, isProfessor, _error; isStudent = isTutor = isProfessor = _error = false; string _email, _password, _firstname, _lastname, _confmessage, _class_standing, _vnumber; _email = _password = _firstname = _lastname = _class_standing = _vnumber = null; short _classof = 0000; var response = Request["g-recaptcha-response"]; //secret that was generated in key value pair string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["ReCapSecretKey"]; var client = new WebClient(); var reply = client.DownloadString( string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response)); var captchaResponse = JsonConvert.DeserializeObject <CaptchaResponse>(reply); //when response is false check for the error message if (captchaResponse.Success.Equals(false)) { if (captchaResponse.ErrorCodes.Count <= 0) { return(View()); } var error = captchaResponse.ErrorCodes[0].ToLower(); switch (error) { case ("missing-input-secret"): ViewBag.Message = "The secret parameter is missing."; break; case ("invalid-input-secret"): ViewBag.Message = "The secret parameter is invalid or malformed."; break; case ("missing-input-response"): ViewBag.Message = "The response parameter is missing."; break; case ("invalid-input-response"): ViewBag.Message = "The response parameter is invalid or malformed."; break; default: ViewBag.Message = "Error occured. Please try again"; break; } _error = true; } else { ViewBag.Message = "Valid"; } if (ModelState.IsValid && !_error) { if (model.studentVM != null) { isStudent = true; _firstname = model.studentVM.FirstName; _lastname = model.studentVM.LastName; _password = model.studentVM.Password; _class_standing = model.studentVM.ClassStanding; _classof = model.studentVM.GraduatingYear; _email = model.studentVM.Email; } if (model.tutorVM != null) { isTutor = true; _firstname = model.tutorVM.FirstName; _lastname = model.tutorVM.LastName; _password = model.tutorVM.Password; _vnumber = model.tutorVM.VNumber; _classof = model.tutorVM.ClassOf; _email = model.tutorVM.Email; } if (model.professorVM != null) { isProfessor = true; _firstname = model.professorVM.FirstName; _lastname = model.professorVM.LastName; _password = model.professorVM.Password; _email = model.professorVM.Email; } if (isTutor || isProfessor) { _confmessage = "Confirm your account email and wait for admin approval"; ViewBag.Message = "Once you've confirmed that " + _email + " is your email address and recieved admin approval, you'll be able to use your account."; } else { ViewBag.Message = "Once you've confirmed that " + _email + " is your email address, you can continue to your account."; _confmessage = "Confirm your account email"; } //var user = new ApplicationUser { UserName = model.FirstName + " " + model.LastName, Email = model.Email }; var user = new ApplicationUser { UserName = _email, Email = _email }; var result = await UserManager.CreateAsync(user, _password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, _confmessage, _firstname); TempData["Message"] = ViewBag.Message; // Won't be shown to the user if we redirect to home ViewBag.Message = "Check your email and confirm your account; you must be confirmed " + "if you ever need to recover your password."; // TODO: Handle errors, do this upon refactoring into repository pattern // Succeeded in creating a new Identity account, so let's create a new var special_user = new BTTUser { FirstName = _firstname, LastName = _lastname, ASPNetIdentityID = user.Id }; BeyondTheTutorContext db = new BeyondTheTutorContext(); if (model.studentVM != null) { var sub_user = new Student { ClassStanding = _class_standing, GraduatingYear = _classof }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Students.Add(sub_user); UserManager.AddToRole(user.Id, "Student"); } if (model.tutorVM != null) { var sub_user = new Tutor { VNumber = _vnumber, ClassOf = _classof, }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Tutors.Add(sub_user); UserManager.AddToRole(user.Id, "Tutor"); } if (model.professorVM != null) { var sub_user = new Professor { }; sub_user.BTTUser = special_user; db.BTTUsers.Add(special_user); db.Professors.Add(sub_user); UserManager.AddToRole(user.Id, "Professor"); } await db.SaveChangesAsync(); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form if (model.professorVM != null) { ViewBag.validationError = "professor"; } else if (model.tutorVM != null) { ViewBag.validationError = "tutor"; } else if (model.studentVM != null) { ViewBag.validationError = "student"; } ViewBag.ReCapKey = System.Web.Configuration.WebConfigurationManager.AppSettings["ReCapKey"]; return(View(model)); }