public ActionResult Create(CSPersonnel cspersonnel) { if (ModelState.IsValid) { // I would really like a transaction here.... CSPersonnel cp = new CSPersonnel(); cp.firstName = cspersonnel.firstName; cp.lastName = cspersonnel.lastName; cp.middleName = cspersonnel.middleName; cp.isActive = cspersonnel.isActive; cp.lastAccess = DateTime.Now; try { if (WebSecurity.Initialized == false) { // WebSecurity is used to create the new user and account. WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: false); } string password = Membership.GeneratePassword(12, 1); // Create both the user and account. WebSecurity.CreateUserAndAccount(cspersonnel.UserProfile.UserName, password, new { email = cspersonnel.UserProfile.Email }); // Assign a user to a role. Roles.AddUserToRole(cspersonnel.UserProfile.UserName, "Personnel"); // Update the foreign key in cp cp.UserId = (int)Membership.GetUser(cspersonnel.UserProfile.UserName).ProviderUserKey; // save cspersonnel to db db.CSPersonnels.Add(cp); db.SaveChanges(); CIOS.Email.EmailSystem email = new CIOS.Email.EmailSystem(); email.toEmail = cspersonnel.UserProfile.Email; email.subject = "CIOS: New Account Created"; email.body = "You can log into your account with the following information:\n" + "Username: "******"\n" + "Password: "******"\n\n" + "Please log into the CIOS system and change your password."; email.sendNewEmail(); return RedirectToAction("Index"); } catch (System.Web.Security.MembershipCreateUserException e) { ModelState.AddModelError("", "The username already exists."); } } // ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "UserName", cspersonnel.UserId); return View(cspersonnel); }
public ActionResult ForgotPassword(EmailVer model, FormCollection formData) { string password = Membership.GeneratePassword(12, 1); UserProfile prof; var variable = formData["Email"]; foreach (var profile in db.UserProfiles) { if (profile.Email == variable) { prof = profile; var token = WebSecurity.GeneratePasswordResetToken(prof.UserName); //var pwResetURL = Request.Url.GetLeftPart(UriPartial.Authority) + "/resetpassword?token=" + token; WebSecurity.ResetPassword(token, password); CIOS.Email.EmailSystem email = new CIOS.Email.EmailSystem(); email.toEmail = prof.Email; email.subject = "CIOS: Password Change"; email.body = "Hello " + prof.UserName + ". Here's your new password: "******". Please reset your password once signed in!"; try { email.sendNewEmail(); return RedirectToAction("Login", "Account"); } catch (Exception e) { ModelState.AddModelError("", "Error occured whilst email sendage" + e.Message); } } else { ModelState.AddModelError("", "Email address not found"); return View(model); } } ModelState.AddModelError("", "Email address not found"); return View(model); }