public string CreateBlogAdmin(string _userIDs) { string[] userIDs = _userIDs.Split(','); string newadmins = string.Empty; foreach (string userID in userIDs) { if (!string.IsNullOrEmpty(userID)) { SueetieUser sueetieUser = SueetieUsers.GetUser(Convert.ToInt32(userID)); SueetieBlogs.CreateBlogAdmin(sueetieUser); SueetieBlogUtils.CreateProfile(sueetieUser, "blog"); if (!sueetieUser.IsBlogAdministrator) { Roles.AddUserToRole(sueetieUser.UserName, "BlogAdministrator"); } newadmins += sueetieUser.DisplayName + ","; } } return("The following are now site blog administrators: " + DataHelper.CommaTrim(newadmins)); }
public ActionResult AddUserToRole(AdminAddUserModel model) { try { int id; if (model.Role.Contains("AllDest")) { string[] RolesArray = Roles.GetAllRoles(); foreach (String role in RolesArray) { if (Int32.TryParse(role, out id) == true) { if (!(Roles.IsUserInRole(model.User, role))) { Roles.AddUserToRole(model.User, role); } } } if (Roles.IsUserInRole(model.User, "AllDest")) { Roles.RemoveUserFromRole(model.User, "AllDest"); } Roles.AddUserToRole(model.User, "AllDest"); } else { Roles.AddUserToRole(model.User, model.Role); } Session["success"] = "User: "******" has been successfully added to role: " + model.Role + "."; return(RedirectToAction("AddUser", "Admin")); } catch (Exception msg) { // something went wrong, and you wanna know why throw msg; } }
protected void EsapiCreateUserWizard_CreatedUser(object sender, EventArgs e) { string userName = EsapiCreateUserWizard.UserName; logger.Info(LogEventTypes.SECURITY, String.Format("User {0} was created.", userName)); if (!Roles.RoleExists("user")) { Roles.CreateRole("user"); } Roles.AddUserToRole(userName, "user"); logger.Info(LogEventTypes.SECURITY, String.Format("User {0} added to 'user' role.", userName)); MembershipUser user = Membership.GetUser(userName); user.IsApproved = false; user.Comment = Esapi.Randomizer.GetRandomGUID().ToString(); Membership.UpdateUser(user); String activationUrl = Request.Url.ToString().Replace("Register.aspx", String.Format("Activate.aspx?username={0}&token={1}", userName, user.Comment)); String body = FileUtil.RetrieveFileBody("ActivationBody.txt").Replace("@ActivationUrl", activationUrl); MailUtil.SendMail(user.Email, "User Activation Email", body); Response.Redirect("Message.aspx?message=3"); }
/// <summary> /// Add selected roles to user. /// </summary> public void AddSelected() { System.Collections.Generic.List <string> list; list = GetItemKeys(true); var user = User.GetUser(new Guid(SearchUserId.Text)); int length = list.Count; for (int i = 0; i < length; i++) { string roleName = list[i]; if (user.UserName.Length > 0 && roleName.Length > 0) { if (!Roles.IsUserInRole(user.UserName, roleName)) { Roles.AddUserToRole(user.UserName, roleName); } } } // Clean list. ItemsTextBox.Text = ""; RolesGridView.DataBind(); }
public virtual ActionResult Register(viewModels.RegisterViewModel model) { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, true, out createStatus); if (createStatus == MembershipCreateStatus.Success) { Roles.AddUserToRole(model.UserName, "SecurityGuard"); FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); } } return(RedirectToAction("Register")); }
//metodo para evento click de boton "Agregar Sala" protected void txtAgregarSala_Click(object sender, EventArgs e) { //obtiene valor de confirmBox desde la página web string confirmValue = Request.Form["confirm_value"]; //si el valor es "Si", dispara metodo para guardar sala if (confirmValue == "Si") { sbll.CrearSala( txtCoordinador.Text, Convert.ToInt32(ddlUbicaciones.SelectedValue), txtNombreSala.Text, Convert.ToInt32(txtCapacidad.Text), Convert.ToInt32(txtPiso.Text), txtEquipamiento.Text, chkNotePC.Checked, chkMonitorPantalla.Checked, chkVC.Checked); //si el usuario ingresado no está en la tabla "aspnet_UsersInRoles", lo añade if (Roles.IsUserInRole(txtCoordinador.Text, "Coordinador") == false) { Roles.AddUserToRole(txtCoordinador.Text, "Coordinador"); } txtCoordinador.Text = ""; txtNombreSala.Text = ""; txtCapacidad.Text = ""; txtPiso.Text = ""; txtEquipamiento.Text = ""; //dispara evento de confirmbox confirmando sala creada this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Sala creada correctamente')", true); } else { //dispara evento de confirmbox señalando que ningun cambio se ha guardado this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('No se ha guardado ningún cambio')", true); } }
protected void ChangeRolesButton_Click(object sender, EventArgs e) { try { // Add user to all selected roles from the roles listbox for (int i = 0; i < AvailableRoles.Items.Count; i++) { if (AvailableRoles.Items[i].Selected == true) { Roles.AddUserToRole(User.Identity.Name, AvailableRoles.Items[i].Value); } else if (Roles.IsUserInRole(User.Identity.Name, AvailableRoles.Items[i].Value)) { Roles.RemoveUserFromRole(User.Identity.Name, AvailableRoles.Items[i].Value); } } } catch (InvalidOperationException ex) { ErrorLabel.Text = "Error accessing the data store. Error: " + ex.Message; } }
/// <summary> /// Обновление аккаунта /// </summary> /// <param name="Account"></param> /// <param name="Message"></param> /// <returns></returns> private static bool UpdateAccount(ApplicationAccount Account, out string Message) { if (Account == null) { throw new ArgumentNullException(); } var membershipUser = Membership.GetUser(Account.Id); membershipUser.Email = Account.Email; //сохранение пользователя Membership.UpdateUser(membershipUser); if (Account is ApplicationUser) { // изменение роли var curentRoles = Roles.GetRolesForUser(membershipUser.UserName); if (curentRoles.Length > 0) { Roles.RemoveUserFromRoles(membershipUser.UserName, curentRoles); } Roles.AddUserToRole(Account.Login, ((ApplicationAccountRoles)Account.IdRole).ToString()); } // изменение пароля if (!membershipUser.IsLockedOut && !string.IsNullOrEmpty(Account.Password)) { string oldPassword = membershipUser.GetPassword(); if (!oldPassword.Equals(Account.Password)) { try { membershipUser.ChangePassword(oldPassword, Account.Password); } catch (ArgumentException) { Message = OperationResult.BadPassword.GetDescription(); return(false); } }
protected void AddUser() { // Add User. MembershipUser newUser = Membership.CreateUser(username.Text, password.Text, email.Text); newUser.Comment = comment.Text; Membership.UpdateUser(newUser); Roles.AddUserToRole(username.Text, RoleList1.SelectedValue); Response.Write("<script> window.alert('Added User Successfully.')</script>"); //clear textboxes username.Text = string.Empty; password.Text = string.Empty; email.Text = string.Empty; comment.Text = string.Empty; }
public ActionResult Index(Users.RegistrationViewModel user) { if (user == null) { return(View()); } //TODO: Change recaptcha PRIVATE key if the domain changes register on Recaptcha.com if (ReCaptcha.Validate(privateKey: "6Ld_kt0SAAAAAAWadUrgyxHuqAlp2fjS5RXjdyn9")) { if (ModelState.IsValid) { if (WebSecurity.UserExists(user.Username)) { ModelState.AddModelError("Username", "User Name has already been chosen, please try another."); return(View(user)); } WebSecurity.CreateUserAndAccount( user.Username, user.password, new { user.Username, user.email }); string username = user.Username; Roles.AddUserToRole(username, "User"); WebSecurity.Login(username, user.password, persistCookie: false); ViewBag.Title = "Success!"; ViewBag.Message = "You have succesfully been registered!"; return(RedirectToAction("Index", "Movies")); } ViewBag.Title = "FAILED!"; return(View(user)); } //Else: recaptcha failed! return(View(user)); }
public IHttpActionResult CreateProfiles() { string[] users = new string[1] { "user" }; string[] admins = new string[2] { "admin", "user" }; WebSecurity.InitializeDatabaseConnection("Billing", "Agents", "Id", "Username", autoCreateTables: true); Roles.CreateRole("admin"); Roles.CreateRole("user"); foreach (var agent in UnitOfWork.Agents.Get().ToList()) { if (string.IsNullOrWhiteSpace(agent.Username)) { string[] names = agent.Name.Split(' '); string username = names[0].ToLower(); agent.Username = username; UnitOfWork.Agents.Update(agent, agent.Id); UnitOfWork.Commit(); } WebSecurity.CreateAccount(agent.Username, "billing", false); if (agent.Username == "marlon" || agent.Username == "julia") { Roles.AddUserToRole(agent.Username, "admin"); } else { ; } Roles.AddUserToRole(agent.Username, "user"); } if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("Billing", "Agents", "Id", "Username", autoCreateTables: true); } return(Ok("user profiles created")); }
public static void MembershipRoles() { //don't o anythign if the admin role exists already if (!Roles.RoleExists("Admin")) { Users user = new Users(); if (!Roles.RoleExists("Admin")) { Roles.CreateRole("Admin"); } if (!Roles.RoleExists("Mod")) { Roles.CreateRole(("Mod")); } if (!Roles.RoleExists("User")) { Roles.CreateRole(("User")); } if (!WebSecurity.UserExists("Admin")) { WebSecurity.CreateUserAndAccount("Admin", "Admin", propertyValues: new { Username = "******", firstName = "Admin", lastName = "Admin", email = "*****@*****.**" }); } if (!Roles.GetRolesForUser("Admin").Contains("Admin")) { Roles.AddUserToRole("Admin", "Admin"); } } }
public ActionResult Create(Hotels.ClientDataModel.MetaData.Hotel.UserManagementModel.CreateAspUser obj, FormCollection fc) { // UserManagementProvider sr = new UserManagementProvider(); if (obj.Password != obj.ConfirmPassword) { TempData["ErrorMessage"] = "Registration failed! Your passwords must match, please re-enter and try again"; return(RedirectToAction("Create")); } // sr.CreateUser(obj); Guid userid = ser.ListAllUser().Last().UserId; ///////Get Roles information///////////// //List<Guid> RoleIds = new List<Guid>(); List <aspnet_Roles> vu = ser.GetAllRolesList(); // RoleIds = new List<Guid>(); foreach (aspnet_Roles u in vu) { if (fc["Chk_" + u.RoleId].ToString() != "false") { //string cCid = fc["Chk_" + u.RoleId].ToString(); //int i = cCid.IndexOf(","); //Guid j = Guid.Parse(cCid.Substring(0, i)); //RoleIds.Add(j); Roles.AddUserToRole(obj.UserName, u.RoleName); } } //ser.AddRoleforParticularUser(RoleIds, userid); //////////////End of Role///////////// //var model = new AirLines.DataModel.ModelMetaData.AirLine.UserManagementModel.CreateAspUser //{ // AgentList = _agentPorvider.getAllAgentList() //}; //return View(model); return(RedirectToAction("Index")); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); if (model.Role == "BusinessOwner") { Roles.AddUserToRole(model.UserName, "Business Owner"); } else { Roles.AddUserToRole(model.UserName, "User"); var data = new UserProfileViewModel { Name = model.UserName, Email = model.Email, ImageName = "Default.png", }; userController.Create(data); } return(RedirectToAction("IndexforAll", "Advertisement")); } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form return(View(model)); }
protected void SG_userList_RowCommand(object sender, CommandEventArgs e) { string SG_username = (string)e.CommandArgument; switch (e.CommandName) { case "register": { if (!Roles.IsUserInRole(SG_username, "Uprzywilejowany")) { Roles.AddUserToRole(SG_username, "Uprzywilejowany"); SG_infoLabel.Text = "Użytkownikowi '" + SG_username + "' nadano przywileje!"; } else { SG_infoLabel.Text = "Użytkownik '" + SG_username + "' jest już Uprzywilejowany!"; } SG_infoLabel.Visible = true; break; } case "deregister": { if (Roles.IsUserInRole(SG_username, "Uprzywilejowany")) { Roles.RemoveUserFromRole(SG_username, "Uprzywilejowany"); SG_infoLabel.Text = "Użytkownikowi '" + SG_username + "' zabrano przywileje!"; } else { SG_infoLabel.Text = "Użytkownik '" + SG_username + "' nie był uprzywilejowany!"; } SG_infoLabel.Visible = true; break; } } Page_Load(sender, e); }
public static void UpdateUser(FormCollection form) { MembershipUser mbrUser; if (!String.IsNullOrEmpty(form["edit"])) { mbrUser = Membership.GetUser(new Guid(form["userId"])); if (form["changePw"] == "on") { mbrUser.ChangePassword(mbrUser.GetPassword(), "default"); } } else { mbrUser = Membership.CreateUser(form["username"], "default", form["emailAddr"]); } System.Web.Profile.ProfileBase profile = System.Web.Profile.ProfileBase.Create(mbrUser.UserName); string x = form["emailAddr"]; string y = form["initials"]; mbrUser.Email = form["emailAddr"]; if (form["isAdmin"] == "on" && !Roles.IsUserInRole(mbrUser.UserName, "CompanyAdmin")) { Roles.AddUserToRole(mbrUser.UserName, "CompanyAdmin"); } else if (form["isAdmin"] != "on" && Roles.IsUserInRole(mbrUser.UserName, "CompanyAdmin")) { Roles.RemoveUserFromRole(mbrUser.UserName, "CompanyAdmin"); } profile.SetPropertyValue("firstName", form["firstName"]); profile.SetPropertyValue("lastName", form["lastName"]); profile.SetPropertyValue("initials", form["initials"]); Membership.UpdateUser(mbrUser); profile.Save(); }
public ActionResult RoleAddToUser(AssignRoleVM objvm) { if (objvm.RoleName == "0") { ModelState.AddModelError("RoleName", "Favor Seleccione Nombre de Rol"); } if (objvm.UserName == "0") { ModelState.AddModelError("UserName", "Favor Seleccione el Nombre de Usuario"); } if (ModelState.IsValid) { if (objIAccountData.Get_CheckUserRoles(objvm.UserName) == true) { ViewBag.ResultMessage = "Este Usuario ya Tiene el Rol Especificado!"; } else { var UserName = objIAccountData.GetUserName_BY_UserID(objvm.UserName); Roles.AddUserToRole(UserName, objvm.RoleName); ViewBag.ResultMessage = "¡Nombre de Usuario Agregado Con Éxito!"; } objvm.RolesList = GetAll_Roles(); objvm.Userlist = GetAll_Users(); return(View(objvm)); } else { objvm.RolesList = GetAll_Roles(); objvm.Userlist = GetAll_Users(); ModelState.AddModelError("Error", "Por favor, Introduzca el Nombre de Usuario y la Contraseña"); } return(View(objvm)); }
void Application_Start(object sender, EventArgs e) { // Código que é executado na inicialização do aplicativo RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Usuario", "idUsuario", "login", true); if (!Roles.RoleExists("admin")) { Roles.CreateRole("admin"); } if (!Roles.RoleExists("user")) { Roles.CreateRole("user"); } if (!WebSecurity.UserExists("Admin")) { WebSecurity.CreateUserAndAccount("Admin", "admin", new { nomeUsuario = "Administrador", dataNascimento = Convert.ToDateTime("01/01/2000"), telefone = "00000000000", email = "*****@*****.**" }); Roles.AddUserToRole("Admin", "admin"); } if (!WebSecurity.UserExists("User")) { WebSecurity.CreateUserAndAccount("User", "user", new { nomeUsuario = "Usuário", dataNascimento = Convert.ToDateTime("01/01/2000"), telefone = "00000000000", email = "*****@*****.**" }); Roles.AddUserToRole("User", "user"); } }
public ActionResult Register(RegisterModel model) { try { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.Answer, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { #if _DEV Roles.AddUserToRole(model.UserName, model.Administrator ? "Administrator" : "User"); #else Roles.AddUserToRole(model.UserName, "User"); #endif FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", ErrorCodeToString(createStatus)); } // If we got this far, something failed, redisplay form #if _DEV return(View("Dev_Register", model)); #else return(View(model)); #endif } catch (Exception e) { ExceptionMessageToViewBag(e); return(View("Error")); } }
public string AddNewUser(FormCollection collection, User user) { Message = null; IsValid = true; AMSEntities ae = new AMSEntities(); // User emailcheck = ae.Users.Where(e => e.UserEmail == user.UserEmail).Single(); // if (emailcheck != null) // SetError("Email Id already Exists"); //User uu=ae.Users.Where(e => e.MembershipUserID == WebSecurity.CurrentUserId).Single(); User uu = DataStore.Get <User>(e => e.MembershipUserID == WebSecurity.CurrentUserId); String uname = collection.Get("UserName"); String paswd = collection.Get("Password"); user.CompanyID = uu.CompanyID; if (IsValid) { using (TransactionScope t = new TransactionScope()) { WebSecurity.CreateUserAndAccount(uname, paswd); Roles.AddUserToRole(uname, "User"); user.MembershipUserID = WebSecurity.GetUserId(uname); //ae.Users.AddObject(user); //ae.SaveChanges(); DataStore.Create(user); DataStore.SaveChanges(); Emailer.Send(user.UserEmail, "Welcome to AMS", "Please reset your password"); t.Complete(); }; Message = "successfully added a new user"; return(Message); } else { return(Message); } }
protected void cmdAdd_Click(object sender, EventArgs e) { try { //### validate provided input parameters //make sure the user name does not already exist MembershipUser selUser = Membership.GetUser(txtUserName.Text); if (selUser != null) { //user already exists throw new Exception("Un utilisateur avec le même nom existe déjà !"); } //create the user selUser = Membership.CreateUser(txtUserName.Text, txtPwd.Text, txtEmail.Text); Roles.AddUserToRole(txtUserName.Text, cmbRole.SelectedItem.Text); ProfileBase profile = ProfileBase.Create(selUser.UserName); if (profile != null) { profile["FirstName"] = txtFirstName.Text; profile["LastName"] = txtLastName.Text; profile.Save(); } RefreshUserList(txtUserName.Text); } catch (Exception ex) { var myCustomValidator = new CustomValidator(); myCustomValidator.IsValid = false; myCustomValidator.ErrorMessage = ex.Message; Page.Validators.Add(myCustomValidator); } }
protected void CreateUser_ActiveStepChanged(object sender, EventArgs e) { if (CreateUser.ActiveStep.Title == "Gotowe") { WizardStep UserInfo = CreateUser.FindControl("AdditionalInfo") as WizardStep; TextBox Name = UserInfo.FindControl("NameTB") as TextBox; TextBox Town = UserInfo.FindControl("TownTB") as TextBox; TextBox Street = UserInfo.FindControl("StreetTB") as TextBox; TextBox StreetNumber = UserInfo.FindControl("StreetNumberTB") as TextBox; TextBox PostalCode = UserInfo.FindControl("PostalCodeTB") as TextBox; Calendar DateOfBirth = UserInfo.FindControl("DateOfBirth") as Calendar; MembershipUser newUser = Membership.GetUser(CreateUser.UserName); Guid newUserId = (Guid)newUser.ProviderUserKey; string connectingString = ConfigurationManager.ConnectionStrings["BBB"].ConnectionString; string updateUrl = "INSERT INTO UserProfiles(NameAndSurname, Town, Street, StreetNumber, PostalCode, DateOfBirth, UserId) VALUES (@NameAndSurname, @Town, @Street, @StreetNumber, @PostalCode, @UserId)"; using (SqlConnection myConnection = new SqlConnection(connectingString)) { myConnection.Open(); SqlCommand myCommand = new SqlCommand(updateUrl, myConnection); myCommand.Parameters.AddWithValue("@NameAndSurname", Name.Text.Trim()); myCommand.Parameters.AddWithValue("@Town", Town.Text.Trim()); myCommand.Parameters.AddWithValue("@Street", Street.Text.Trim()); myCommand.Parameters.AddWithValue("@StreetNumber", StreetNumber.Text.Trim()); myCommand.Parameters.AddWithValue("@PostalCode", PostalCode.Text.Trim()); myCommand.Parameters.AddWithValue("@DateOfBirth", DateOfBirth.SelectedDate); myCommand.Parameters.AddWithValue("@UserId", newUserId); myCommand.ExecuteNonQuery(); myConnection.Close(); } string userName = CreateUser.UserName; Roles.AddUserToRole(userName, "patient"); } }
public ActionResult Register(RegisterModel model) { if (this.IsCaptchaValid("Captcha is not valid")) { if (ModelState.IsValid) { // Attempt to register the user try { WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new { FirstName = model.FirstName, LastName = model.LastName, EmailAddress = model.EmailAddress, Phone = model.Phone, Mobile = model.Mobile, Address = model.Address, SSN = model.SSN }); WebSecurity.Login(model.UserName, model.Password); Roles.AddUserToRole(model.UserName, "customer"); return(RedirectToAction("Index", "Home")); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return(View(model)); } TempData["ErrorMessage"] = "Error: captcha is not valid."; return(View()); }
public ActionResult RoleAddToUser(AssignRoleVM objvm) { if (objvm.RoleName == "0") { ModelState.AddModelError("RoleName", "Please select RoleName"); } if (objvm.UserName == "0") { ModelState.AddModelError("UserName", "Please select Username"); } if (ModelState.IsValid) { if (objIAccountData.Get_CheckUserRoles(objvm.UserName) == true) { ViewBag.ResultMessage = "This user already has the role specified !"; } else { var UserName = objIAccountData.GetUserName_BY_UserID(objvm.UserName); Roles.AddUserToRole(UserName, objvm.RoleName); ViewBag.ResultMessage = "Username added to the role succesfully !"; } objvm.RolesList = GetAll_Roles(); objvm.Userlist = GetAll_Users(); return(View(objvm)); } else { objvm.RolesList = GetAll_Roles(); objvm.Userlist = GetAll_Users(); ModelState.AddModelError("Error", "Please enter Username and Password"); } return(View(objvm)); }
private void applyUserBtn_Click(object sender, EventArgs e) { if (appUsers.SelectedIndex == -1) { MessageBox.Show(this, "Please select a user first!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } DialogResult r = MessageBox.Show(this, "Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (r == DialogResult.No) { return; } string user = appUsers.SelectedItem.ToString(); for (int i = 0; i < userRoles.Items.Count; i++) { string role = userRoles.Items[i].ToString(); if (userRoles.GetItemCheckState(i) == CheckState.Checked) { if (!Roles.IsUserInRole(user, role)) { Roles.AddUserToRole(user, role); } } else { if (Roles.IsUserInRole(user, role)) { Roles.RemoveUserFromRole(user, role); } } } //if (unlock.Checked) Membership.GetUser(user).UnlockUser(); //MessageBox.Show(this, "Changes applied!"); }
protected void AddUserToRoleButton_Click(object sender, EventArgs e) { // Get the selected role and username string selectedRoleName = RoleList.SelectedValue; string userNameToAddToRole = UserNameToAddToRole.Text; // Make sure that a value was entered if (userNameToAddToRole.Trim().Length == 0) { ActionStatus.Text = "Nhập tên đăng nhập."; return; } // Make sure that the user exists in the system MembershipUser userInfo = Membership.GetUser(userNameToAddToRole); if (userInfo == null) { ActionStatus.Text = string.Format("Không có tên đăng nhập '{0}' trong hệ thống.", userNameToAddToRole); return; } // Make sure that the user doesn't already belong to this role if (Roles.IsUserInRole(userNameToAddToRole, selectedRoleName)) { ActionStatus.Text = string.Format("{0} đã được gán quyền {1}.", userNameToAddToRole, selectedRoleName); return; } // If we reach here, we need to add the user to the role Roles.AddUserToRole(userNameToAddToRole, selectedRoleName); // Clear out the TextBox UserNameToAddToRole.Text = string.Empty; // Refresh the GridView DisplayUsersBelongingToRole(); // Display a status message ActionStatus.Text = string.Format("Đã thêm {0} vào quyền {1}.", userNameToAddToRole, selectedRoleName); // Refresh the "by user" interface CheckRolesForSelectedUser(); }
public string Register(string username, string password) { StringBuilder sb = new StringBuilder(); sb.Append("<RegisterInfo>"); try { using (TransactionScope scope = new TransactionScope()) { MembershipUser user = Membership.GetUser(username); if (user != null) { sb.AppendFormat("<IsRegistered>{0}</IsRegistered>", false); sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "注册失败,已存在用户:" + username + ",请换一个账号再重试"); } user = Membership.CreateUser(username, password); if (user == null) { sb.AppendFormat("<IsRegistered>{0}</IsRegistered>", false); sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "注册失败,请检查:密码正确格式应由数字或字母组成的字符串,且最小6位,最大30位"); } else { Roles.AddUserToRole(username, "Users"); sb.AppendFormat("<IsRegistered>{0}</IsRegistered>", true); } scope.Complete(); } } catch (Exception ex) { sb.Append("<ErrorMsg> 异常:" + ex.Message + "</ErrorMsg>"); } sb.Append("</RegisterInfo>"); return(sb.ToString()); }
protected void btnInsert_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txt_user.Text) && !string.IsNullOrEmpty(txt_passw.Text)) { var user = Membership.GetUser(txt_user.Text); if (user == null) { string updateStatment = null; Membership.CreateUser(txt_user.Text, txt_passw.Text); if (roleType.SelectedValue == "Administrator") Roles.AddUserToRole(txt_user.Text, "Admins"); else if (roleType.SelectedValue == "Student") { Roles.AddUserToRole(txt_user.Text, "Students"); updateStatment = $"update dbo.aspnet_Users set St_Id = {roleTarget.SelectedValue}, RoleType = '{roleType.SelectedValue}' where UserName = '******'"; } else if (roleType.SelectedValue == "Instructor") { Roles.AddUserToRole(txt_user.Text, "Instructors"); updateStatment = $"update dbo.aspnet_Users set Ins_Id = {roleTarget.SelectedValue}, RoleType = '{roleType.SelectedValue}' where UserName = '******'"; } if (updateStatment == null) updateStatment = $"update dbo.aspnet_Users set RoleType = '{roleType.SelectedValue}' where UserName = '******'"; string cnnStr = ConfigurationManager.ConnectionStrings["OnlineExamsProject"].ConnectionString; SqlConnection sqlConnection = new SqlConnection(cnnStr); SqlCommand sqlCommand = new SqlCommand() { Connection = sqlConnection, CommandText = updateStatment }; sqlConnection.Open(); sqlCommand.ExecuteNonQuery(); sqlConnection.Close(); GridView1.DataBind(); btnClear_Click(sender, e); } } }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { // ChangePassword will throw an exception rather // than return false in certain failure scenarios. bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); //Elimino il ruolo PrimoAccesso Roles.RemoveUserFromRole(currentUser.UserName, ROLE_PRIMO_ACCESSO); //Lo aggiungo al ruolo Dipendenti Roles.AddUserToRole(currentUser.UserName, ROLE_DIPENDENTI); logger.Write(string.Format("L'utente {0} ha cambiato la pw ed è stato aggiunto al ruolo Dipendenti", currentUser.UserName)); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return(RedirectToAction("ChangePasswordSuccess")); } else { ModelState.AddModelError("", "La password corrente non è corretta o la nuova password non è valida."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult RegisterUser(RegisterModel model, FormCollection collection) { if (ModelState.IsValid) { MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, "password!", "*****@*****.**", null, null, true, out createStatus); if (createStatus == MembershipCreateStatus.Success) { MembershipUser user = Membership.GetUser(model.UserName); if (model.IsStaff) { if (!Roles.RoleExists("Staff")) { Roles.CreateRole("Staff"); } Roles.AddUserToRole(model.UserName, "Staff"); } else if (model.IsAdmin) { if (!Roles.RoleExists("Administrators")) { Roles.CreateRole("Administrators"); } Roles.AddUserToRole(model.UserName, "Administrators"); } Membership.UpdateUser(user); this.ShowMessage(MessageType.Success, "Staff user " + model.UserName + " created.", true); return(RedirectToAction("AdminIndex", "Admin")); } else { //ModelState.AddModelError("", ErrorCodeToString(createStatus)); return(View()); } } return(View(model)); }