/// <summary> /// The update app user. /// </summary> /// <param name="appUser"> /// The app user. /// </param> /// <param name="additionaUserInfo"> /// The reg user. /// </param> public void UpdateAppUser(IAppUser appUser, IRegistringUser additionaUserInfo) { //var curUser = GetUser(appUser.Id); var curMemUser = MsMembership.GetUser(additionaUserInfo.UserName); var curAppUser = GetById(appUser.Id); curAppUser.Contact.FirstName = appUser.Contact.FirstName; curAppUser.Contact.LastName = appUser.Contact.LastName; curAppUser.SiteId = appUser.SiteId; curAppUser.IsActive = appUser.IsActive; curAppUser.Title = appUser.Title; curAppUser.UpdatedBy = Thread.CurrentPrincipal.Identity.Name; curAppUser.UpdatedOn = DateTime.UtcNow; curAppUser.SortOrder = appUser.SortOrder; curAppUser.Status = appUser.Status; curAppUser.RoleId = appUser.RoleId; if (curMemUser != null) { curMemUser.Email = additionaUserInfo.Email; } //curUser.UserName = additionaUserInfo.UserName; MsMembership.UpdateUser(curMemUser); SetUserRole(additionaUserInfo, curAppUser.User, curAppUser); }
protected void Page_Load(object sender, EventArgs e) { UsernamePlaceHolder.Visible = !Request.IsAuthenticated; OldPasswordPlaceHolder.Visible = Session[OldPasswordSessionKey] == null; if (IsPostBack) { MembershipUser user = Request.IsAuthenticated ? UserManager.GetUser() : UserManager.GetUser(Request["userName"]); string newPass = Request["firstNewPass"]; if (user == null || newPass != Request["secondNewPass"] || Server.HtmlEncode(newPass) != newPass) { ReportError(); } else { try { /*bool changePasswordSuccess =*/ user.ChangePassword( (Session[OldPasswordSessionKey] ?? Request["oldPass"]).ToString(), newPass); Session.Remove(OldPasswordSessionKey); FormsAuthentication.SignOut(); Response.Redirect(FormsAuthentication.LoginUrl); } catch (Exception) { ReportError(); } } } }
public ActionResult AddEmployee(AddEmployeeDetails model) { if (!ModelState.IsValid) { return View(model); } if (_employeeService.EmployeeExist(model.BankId, model.EmployeeCode ?? 0)) { ModelState.AddModelError("Employee","The employee code is already in use."); return View(model); } if (_userManager.DoseUserExist(model.Username)) { ModelState.AddModelError("User","The username is already taken."); return View(model); } MembershipCreateStatus status; Membership.CreateUser(model.Username, model.Password, model.Email, model.Question, model.Answer, true, out status); if (!ModelState.IsValid || status != MembershipCreateStatus.Success) { return View(model); } Roles.AddUserToRole(model.Username, "Banker"); _employeeService.AddEmployee(model.BankId,new EmployeeBO { Code = model.EmployeeCode ?? 0, GivenName = model.GivenName, FamilyName = model.FamilyName, Phone = model.Phone, Email = model.Email, Username = model.Username }); return RedirectToAction("BankEmployeeList", new { bankId = model.BankId }); }
public IEnumerable <UserDetails> GetUsers() { return(UserManager.GetAllUsers().Cast <MembershipUser>().Select(user => new UserDetails { Name = user.UserName, Roles = string.Join(", ", Roles.GetRolesForUser(user.UserName)), Locked = user.IsLockedOut, Online = user.IsOnline })); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { return; } switch (task.Value) { case "Next": MembershipUser membershipUser = UserManager.GetUser(Request["userName"]); if (membershipUser != null) { QuestionPlaceHolder.Visible = true; questionLabel.InnerText = membershipUser.PasswordQuestion; if (Request["answer"] != null) { try { string newPass = membershipUser.ResetPassword(Request["answer"]); Session[Change.OldPasswordSessionKey] = newPass; FormsAuthentication.SetAuthCookie(membershipUser.UserName, false); Response.Redirect("/Account/Change.aspx"); //UsernamePlaceHolder.Visible = false; //QuestionPlaceHolder.Visible = false; //NewPasswordPlaceHolder.Visible = true; //newPassword.InnerText = newPass; //task.Value = "Log In"; } catch (MembershipPasswordException) { ReportError("Wrong answer"); } } } else { ReportError("Unknown username"); } break; case "Restart": Response.Redirect(Request.Path); break; case "Log In": Response.Redirect(FormsAuthentication.LoginUrl); break; default: Response.Redirect(FormsAuthentication.LoginUrl); break; } }
public IEnumerable <UserDetails> GetUsers() // TODO: Следует исключить вошедшего { return(UserManager.GetAllUsers().Cast <MembershipUser>().Select(user => new UserDetails { Name = user.UserName, Email = user.Email, Roles = string.Join(", ", Roles.GetRolesForUser(user.UserName)), Locked = user.IsLockedOut, Online = user.IsOnline })); }
/// <summary> /// Initialize ticket and user name /// </summary> private void Initialize() { var ticketParameter = Request[InvitationSender.TicketParameter]; Ticket = string.IsNullOrEmpty(ticketParameter) ? null : InvitationTicket.Decrypt(ticketParameter); if ((Ticket != null) && !string.IsNullOrEmpty(Ticket.Email)) { var enumerator = Membership.FindUsersByEmail(Ticket.Email).GetEnumerator(); UserName = enumerator.MoveNext() ? ((MembershipUser)enumerator.Current).UserName : string.Empty; } Profile = string.IsNullOrEmpty(UserName) ? EPiServerProfile.Current : EPiServerProfile.Get(UserName); }
/// <summary> /// Creates new user /// <returns>If user was created</returns> /// </summary> private bool CreateUser() { try { Membership.CreateUser(TextBoxUserName.Text, TextBoxPassword.Text, Ticket.Email); UserName = TextBoxUserName.Text; Profile = EPiServerProfile.Get(UserName); return true; } catch (Exception) { return false; } }
/// <summary> /// The create app user with membership. /// </summary> /// <param name="appUser"> /// The app user. /// </param> /// <param name="registeringUser"> /// The registering user. /// </param> /// <param name="contact"> /// The contact. /// </param> public void CreateAppUserWithMembership(IAppUser appUser, IRegistringUser registeringUser, IContact contact) { var memUser = MsMembership.CreateUser(registeringUser.UserName, registeringUser.Password, registeringUser.Email); var appuser = appUser.ToEntity(); if (memUser.ProviderUserKey != null) { var user = GetUser(Guid.Parse(memUser.ProviderUserKey.ToString())); user.AppUsers.Add(appuser); Roles.AddUserToRole(registeringUser.UserName, registeringUser.Role); AddContact(contact); contact.AppUsers.Add(appuser); Commit(); } }
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { var loginVm = new LoginVm(); if (TryUpdateModel(loginVm, new FormValueProvider(ModelBindingExecutionContext)) && (UserManager.ValidateUser(loginVm.Username, loginVm.Password) && ModelState.IsValid)) { FormsAuthentication.RedirectFromLoginPage(loginVm.Username, false); } } else if (Request.IsAuthenticated) { Response.StatusCode = 403; Response.SuppressContent = true; Context.ApplicationInstance.CompleteRequest(); } }
protected void User_Login_Authenticate(object sender, AuthenticateEventArgs e) { var Logins = sender as System.Web.UI.WebControls.Login; MembershipUser User = Members.GetUser(Logins.UserName); if (Members.ValidateUser(User_Login.UserName, User_Login.Password) == true) { String Role = ""; if (HttpContext.Current.User.IsInRole("Administrator")) { Role = "Administrator"; } if (HttpContext.Current.User.IsInRole("Manager")) { Role = "Manager"; } if (HttpContext.Current.User.IsInRole("Users")) { Role = "Users"; } var ticket = new FormsAuthenticationTicket(1, User_Login.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), User_Login.RememberMeSet, Role, FormsAuthentication.FormsCookiePath); String hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } DateTime Last_Login = User.LastLoginDate; Response.Cookies.Add(cookie); Session["Status"] = true; Session["LastLogin"] = Last_Login; Response.Redirect(FormsAuthentication.GetRedirectUrl(User_Login.UserName, User_Login.RememberMeSet)); } else { ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Invalid login details.');", true); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { return; } string userName = Request["userName"]; string userPass = Request["password"]; string email = Request["email"]; string question = Request["question"]; string answer = Request["answer"]; if (IsAnyEmpty(userName, userPass, email, question, answer)) { ReportError("All fields must be filled"); } else { MembershipCreateStatus status; /*MembershipUser membershipUser =*/ UserManager.CreateUser(userName, userPass, email, question, answer, true, out status); if (status == MembershipCreateStatus.Success) { if (!Roles.RoleExists(UsersRoleName)) { Roles.CreateRole(UsersRoleName); } Roles.AddUserToRole(userName, UsersRoleName); FormsAuthentication.SetAuthCookie(userName, false); Response.Redirect(FormsAuthentication.LoginUrl); } else { ReportError(status.ToString()); } } }
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { string user = Request["userName"]; string pass = Request["pass"]; string action = Request["action"]; if (action == "login" && UserManager.ValidateUser(user, pass)) { FormsAuthentication.RedirectFromLoginPage(user, false); } else { message.Style["visibility"] = "visible"; } } else if (Request.IsAuthenticated) { Response.StatusCode = 403; Response.SuppressContent = true; Context.ApplicationInstance.CompleteRequest(); } }
private const string UsersRoleName = "users"; // NOTE: Извлечь эту инфу из конфига protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { return; } var registerVm = new RegisterVm(); if (!TryUpdateModel(registerVm, new FormValueProvider(ModelBindingExecutionContext))) { return; } if (registerVm.Password != registerVm.ConfirmPassword) { ModelState.AddModelError(string.Empty, "Пароли не совпадают"); } else { MembershipCreateStatus status; var membershipUser = UserManager.CreateUser( registerVm.Username, registerVm.Password, registerVm.Email, null, null, true, out status); if (status == MembershipCreateStatus.Success && membershipUser != null && ModelState.IsValid) { Roles.AddUserToRole(membershipUser.UserName, UsersRoleName); FormsAuthentication.SetAuthCookie(membershipUser.UserName, false); Response.Redirect("~/Default.aspx"); } else { ModelState.AddModelError(string.Empty, string.Format("Создание пользователя завершилось неудачей. Возможная причина: {0}", status)); } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { return; } if (Request["unlock"] != null) { var membershipUser = UserManager.GetUser(Request["unlock"]); if (membershipUser != null) { membershipUser.UnlockUser(); } } else if (Request["delete"] != null) { var currentUser = UserManager.GetUser(); if (currentUser != null && Request["delete"] != currentUser.UserName) { UserManager.DeleteUser(Request["delete"]); } } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override string CreateAccount(string userName, string password, bool requireConfirmationToken) { VerifyInitialized(); if (password.IsEmpty()) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword); } string hashedPassword = Crypto.HashPassword(password); if (hashedPassword.Length > 128) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword); } if (userName.IsEmpty()) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName); } using (var unit = unitOfWork.CreateExport().Value) { // Check if the user exists User user; try { user = userRepository.Where(u => u.Username == userName).Single(); } catch { throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError); } // Step 2: Check if the user exists in the Membership table: Error if yes. if (user.Memberships.Count > 0) { throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName); } // Step 3: Create user in Membership table string token = null; object dbtoken = DBNull.Value; if (requireConfirmationToken) { token = GenerateToken(); dbtoken = token; } int defaultNumPasswordFailures = 0; var membership = new Membership() { User = user, Password = hashedPassword, PasswordSalt = String.Empty, IsConfirmed = !requireConfirmationToken, ConfirmationToken = token, }; try { membershipRepository.Add(membership); unit.Commit(); } catch { throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError); } return token; } }
//Fn to create a Membership user from a Entities.Users class private MembershipUser GetMembershipUserFromUser(Membership.User usr) { MembershipUser u = new MembershipUser(this.Name, usr.Username, usr.Id, usr.Email, usr.PasswordQuestion, usr.Comment, usr.IsApproved, usr.IsLockedOut, usr.CreationDate, usr.LastLoginDate, usr.LastActivityDate, usr.LastPasswordChangedDate, usr.LastLockedOutDate); return u; }
/// <summary> /// Handles user name vaildating /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event parameters</param> protected void CustomValidatorUserName_Validate(object sender, ServerValidateEventArgs e) { e.IsValid = Membership.FindUsersByName(TextBoxUserName.Text).Count == 0; }