public void AddNewUser(User user) { var cfrp = new CodeFirstRoleProvider(Context); VerfiyNewUserIsValid(user); WebSecurity.CreateUserAndAccount(user.Username, user.Password, user.TimeZone, user.Email); var newlyAddedUser = Context.Users.First(x => x.Username == user.Username); newlyAddedUser.CreateDate = DateTime.UtcNow; UpdateUserValues(user, newlyAddedUser); try { Context.SaveChanges(); } catch (Exception ex) { Log.Debug(ex); throw new Exception("There was an error processing your request."); } // Add the asigned roles if (user.Roles == null || !user.Roles.Any()) { return; } foreach (var role in user.Roles) { WebUserUtils.AssignUserToRole(user, role, cfrp); } }
public ActionResult AddRole(Role role) { CodeFirstRoleProvider roleProvider = new CodeFirstRoleProvider(); roleProvider.CreateRole(role.RoleName); return(View("AdminTasks")); }
public void AddNewUser(User user) { var cfrp = new CodeFirstRoleProvider(Context); VerfiyNewUserIsValid(user); WebSecurity.CreateUserAndAccount(user.Username, user.Password, user.TimeZone, user.Email); var newlyAddedUser = Context.Users.First(x => x.Username == user.Username); newlyAddedUser.CreateDate = DateTime.UtcNow; UpdateUserValues(user, newlyAddedUser); try { Context.SaveChanges(); } catch (Exception ex) { Log.Debug(ex); throw new Exception("There was an error processing your request."); } // Add the asigned roles if (user.Roles == null || !user.Roles.Any()) { return; } foreach (var role in user.Roles) { WebUserUtils.AssignUserToRole(user, role, cfrp); } }
public static void AssignUserToRole(User user, Role role, CodeFirstRoleProvider cfrp) { if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } cfrp.AddUsersToRoles(new[] { user.Username }, new[] { role.RoleName }); }
public ActionResult AddEmployee() { CodeFirstRoleProvider roleProvider = new CodeFirstRoleProvider(); //SqlParameter appIdParam = new SqlParameter("@ApplicationId","/"); List <string> roles = roleProvider.GetAllRoles().ToList(); //context.Database.SqlQuery<string>("dbo.aspnet_Roles_GetAllRoles @ApplicationId", appIdParam).ToList<string>(); ViewBag.Roles = roles; ViewBag.Teams = teamRepository.All; return(View()); }
public JsonResult AddUserRole(Role role) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var cfrp = new CodeFirstRoleProvider(Context); var success = 0; if (cfrp.RoleExists(role.RoleName)) { // bail return(result); } var NewRole = new Role { RoleId = Guid.NewGuid(), RoleName = role.RoleName, Permissions = new List <Permission>() }; if (role.Permissions != null) { foreach (var permission in role.Permissions) { var existingPermission = Context.Permissions.FirstOrDefault(x => x.PermissionId == permission.PermissionId); if (existingPermission != null) { NewRole.Permissions.Add(existingPermission); } } } Context.Roles.Add(NewRole); success = Context.SaveChanges(); // Add to WebSecurity as well Roles.CreateRole(role.RoleName); if (success > 0) { result.Data = new { success = true, message = "Role added successfully." }; } return(result); }
public JsonResult AddUser(User user) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var cfrp = new CodeFirstRoleProvider(Context); var success = 0; if (!String.IsNullOrEmpty(user.Username)) { // Add to .Net Membership Framework First WebSecurity.CreateUserAndAccount(user.Username, user.Password, user.TimeZone, user.Email); // Now add additional fields to CodeFirst User var newlyAddedUser = Context.Users.FirstOrDefault(x => x.Username == user.Username); newlyAddedUser.CreateDate = DateTime.UtcNow; newlyAddedUser.FirstName = user.FirstName; newlyAddedUser.LastName = user.LastName; newlyAddedUser.Email = user.Email; newlyAddedUser.UserImageLocation = user.UserImageLocation; newlyAddedUser.IsApproved = user.IsApproved; success = Context.SaveChanges(); // Add the asigned roles if (user.Roles != null && user.Roles.Any()) { foreach (var role in user.Roles) { // Add to Membership Framework Roles.AddUserToRole(user.Username, role.RoleName); // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } if (success > 0) { result.Data = new { success = true, message = "User added successfully." }; } return(result); }
public JsonResult AddUser(User user) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var cfrp = new CodeFirstRoleProvider(Context); var success = 0; if (!String.IsNullOrEmpty(user.Username)) { // Add to .Net Membership Framework First WebSecurity.CreateUserAndAccount(user.Username, user.Password, user.TimeZone, user.Email); // Now add additional fields to CodeFirst User var newlyAddedUser = Context.Users.FirstOrDefault(x => x.Username == user.Username); newlyAddedUser.CreateDate = DateTime.UtcNow; newlyAddedUser.FirstName = user.FirstName; newlyAddedUser.LastName = user.LastName; newlyAddedUser.Email = user.Email; newlyAddedUser.UserImageLocation = user.UserImageLocation; success = Context.SaveChanges(); // Add the asigned roles if (user.Roles != null && user.Roles.Any()) { foreach (var role in user.Roles) { // Add to Membership Framework Roles.AddUserToRole(user.Username, role.RoleName); // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } if (success > 0) { result.Data = new { success = true, message = "User added successfully." }; } return result; }
public JsonResult AddUserRole(Role role) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var cfrp = new CodeFirstRoleProvider(Context); var success = 0; if (cfrp.RoleExists(role.RoleName)) { // bail return result; } var NewRole = new Role { RoleId = Guid.NewGuid(), RoleName = role.RoleName, Permissions = new List<Permission>() }; if (role.Permissions != null) { foreach (var permission in role.Permissions) { var existingPermission = Context.Permissions.FirstOrDefault(x => x.PermissionId == permission.PermissionId); if (existingPermission != null) { NewRole.Permissions.Add(existingPermission); } } } Context.Roles.Add(NewRole); success = Context.SaveChanges(); // Add to WebSecurity as well Roles.CreateRole(role.RoleName); if (success > 0) { result.Data = new { success = true, message = "Role added successfully." }; } return result; }
public void UpdateUser(User user) { if (String.IsNullOrEmpty(user.UserId.ToString())) { throw new Exception("There was an error processing your request."); } var cfrp = new CodeFirstRoleProvider(Context); var editUser = Context.Users.FirstOrDefault(x => x.UserId == user.UserId); var currentUsername = UserUtils.CurrentMembershipUsername(); VerifyChangeIsValid(user, editUser, currentUsername); UpdateUserValues(user, editUser); if (user.Roles == null) { throw new Exception("There was an error processing your request."); } try { foreach (var role in editUser.Roles.ToList()) { RemoveUserFromFole(user, role, cfrp); } foreach (var role in user.Roles) { AssignUserToRole(user, role, cfrp); } Context.SaveChanges(); if (user.Username != currentUsername) { FormsAuthentication.SignOut(); FormsAuthentication.SetAuthCookie(user.Username, false); } } catch (Exception e) { Log.Debug(e); throw new Exception("There was an error processing your request."); } }
public void UpdateUser(User user) { if (String.IsNullOrEmpty(user.UserId.ToString())) { throw new Exception("There was an error processing your request."); } var cfrp = new CodeFirstRoleProvider(Context); var editUser = Context.Users.FirstOrDefault(x => x.UserId == user.UserId); var currentUsername = UserUtils.CurrentMembershipUsername(); VerifyChangeIsValid(user, editUser, currentUsername); UpdateUserValues(user, editUser); if (user.Roles == null) { throw new Exception("There was an error processing your request."); } try { foreach (var role in editUser.Roles.ToList()) { RemoveUserFromFole(user, role, cfrp); } foreach (var role in user.Roles) { AssignUserToRole(user, role, cfrp); } Context.SaveChanges(); if (user.Username != currentUsername) { FormsAuthentication.SignOut(); FormsAuthentication.SetAuthCookie(user.Username, false); } } catch (Exception e) { Log.Debug(e); throw new Exception("There was an error processing your request."); } }
public ActionResult AddEmployee(Employee employee, FormCollection col) { Employee emp = new Employee(); emp.TeamID = Convert.ToInt32(col["EmployeeTeam"]); emp.EmployeeRole = col["roles"]; emp.EmployeeContact = employee.EmployeeContact; employeeRepository.InsertOrUpdate(emp); employeeRepository.Save(); string[] roles = { emp.EmployeeRole }; string[] username = { employee.EmployeeContact.ContactEmail }; MembershipCreateStatus createStatus; CodeFirstMembershipProvider provider = new CodeFirstMembershipProvider(); provider.CreateAccount(username[0], "KStart123", employee.EmployeeContact.ContactEmail, out createStatus); CodeFirstRoleProvider roleProvider = new CodeFirstRoleProvider(); roleProvider.AddUsersToRoles(username, roles); return(View("AdminTasks")); }
public ActionResult ClientRegister(ClientRegister form) { ClientRegister details = new ClientRegister(); details = form; int enqID = Convert.ToInt32(TempData["EnquiryIdClient"]); //RegisterModel regMod = new RegisterModel(); //AccountController accController = new AccountController(); Enquiry enq = new Enquiry(); enq = enquiryRepository.Find(enqID); //regMod.UserName = enq.Contact.ContactEmail; string Password = PasswordGeneration(enq.Contact.ContactName, enq.Contact.MobileNumber); //regMod.Email = enq.Contact.ContactEmail; //accController.Register(regMod); MembershipCreateStatus createStatus; CodeFirstMembershipProvider provider = new CodeFirstMembershipProvider(); provider.CreateAccount(enq.Contact.ContactEmail, Password, enq.Contact.ContactEmail, out createStatus); CodeFirstRoleProvider roleProvider = new CodeFirstRoleProvider(); if (createStatus == MembershipCreateStatus.Success) { if (!roleProvider.RoleExists("Client")) { roleProvider.CreateRole("Client"); } string[] roles = { "Client" }; string[] users = { enq.Contact.ContactEmail.ToString() }; roleProvider.AddUsersToRoles(users, roles); } details.EnquiryID = Convert.ToInt32(TempData["EnquiryIdClient"]); details.ContactID = enq.ContactID; // Please see this--Pankaj clientRegisterRepository.InsertOrUpdate(details); clientRegisterRepository.Save(); return(RedirectToAction("Details", new { id = details.EnquiryID })); }
public static bool RoleExist(string role) { CodeFirstRoleProvider rp = new CodeFirstRoleProvider(); return(rp.RoleExists(role)); }
public static string[] GetUsersInRole(string role) { CodeFirstRoleProvider rp = new CodeFirstRoleProvider(); return(rp.GetUsersInRole(role)); }
public static void AddUsersToRoles(string[] usernames, string[] rolenames) { CodeFirstRoleProvider rp = new CodeFirstRoleProvider(); rp.AddUsersToRoles(usernames, rolenames); }
public static void RemoveUsersFromRoles(string[] usernames, string[] rolenames) { CodeFirstRoleProvider rp = new CodeFirstRoleProvider(); rp.RemoveUsersFromRoles(usernames, rolenames); }
public static string[] GetAllRoles() { CodeFirstRoleProvider rp = new CodeFirstRoleProvider(); return(rp.GetAllRoles()); }
public JsonResult AddUserRole(Role role) { var result = new JsonResult(); var cfrp = new CodeFirstRoleProvider(); if (cfrp.RoleExists(role.RoleName)) { // bail return result; } using (var context = new DataContext()) { var NewRole = new Role { RoleId = Guid.NewGuid(), RoleName = role.RoleName, Permissions = role.Permissions }; context.Roles.Add(NewRole); context.SaveChanges(); } // Add to WebSecurity as well Roles.CreateRole(role.RoleName); return result; }
public ActionResult ModifyUsersInRole(List<Guid> RemoveUsers, List<Guid> AddUsers, Guid RoleID) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var cfrp = new CodeFirstRoleProvider(Context); var role = Context.Roles.FirstOrDefault(x => x.RoleId == RoleID); if (role == null) { return result; } result.Data = new { success = true, message = "Users updated." }; // Remove Users if (RemoveUsers != null && RemoveUsers.Any()) { foreach (var gid in RemoveUsers) { var user = Context.Users.Where(x => x.UserId == gid).FirstOrDefault(); if (user != null) { Roles.RemoveUserFromRole(user.Username, role.RoleName); cfrp.RemoveUsersFromRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } // Add Users if (AddUsers != null && AddUsers.Any()) { foreach (var gid in AddUsers) { var user = Context.Users.Where(x => x.UserId == gid).FirstOrDefault(); if (user != null) { // Add to Membership Framework if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } return result; }
protected override void Seed(BlogUnitOfWork context) { //Roles CodeFirstRoleProvider provider = new CodeFirstRoleProvider(); provider.CreateRole("admin"); provider.CreateRole("user"); provider.CreateRole("premium"); // Create indexes context.Database.ExecuteSqlCommand("CREATE INDEX IDX_Posts_Code ON Posts (Code);"); context.Database.ExecuteSqlCommand("CREATE INDEX IDX_Posts_DateCreated ON Posts (DateCreated DESC);"); context.Database.ExecuteSqlCommand("CREATE INDEX IDX_Subscriptions_SubscriberEmail ON Subscriptions (SubscriberEmail);"); //Resources context.Set <BlogResource>().Add(new BlogResource { Name = "Admin_Role", Value = "admin" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Categories_Number_of_Categories_per_Page", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Comments_Number_of_Comments_per_Page", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Copyright", Value = "©MyCopyright 2XXX" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Dark_Background_Themes", Value = "" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Dark_Header_Themes", Value = "Aristo;Rocket;Cobalt" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Default_Theme", Value = "Cobalt" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Directories_Temp_Data", Value = "~/Content/Files/Temp_Data/" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Email_Password", Value = "xxxxxx" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Email_UserName", Value = "*****@*****.**" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Google_Analytics_Track_Code", Value = "xx-xxxxxxxx-x" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Index_Number_of_Posts", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Logo", Value = "~/Content/Icons/logo.jpg" }); context.Set <BlogResource>().Add(new BlogResource { Name = "No_Image", Value = "~/Content/Icons/no_image.jpg" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Posts_Number_of_Posts_per_Page", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Premium_Role", Value = "premium" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Recaptcha_Private_Key_Http", Value = "xxxx" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Recaptcha_Public_Key_Http", Value = "xxxx" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Akismet_API_key", Value = "" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Roles_Number_of_Roles_per_Page", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "SearchImages_Number_of_Images_per_Page", Value = "15" }); context.Set <BlogResource>().Add(new BlogResource { Name = "SearchVideos_Number_of_Videos_per_Page", Value = "12" }); context.Set <BlogResource>().Add(new BlogResource { Name = "SiteTitle", Value = "MySiteName.com" }); context.Set <BlogResource>().Add(new BlogResource { Name = "SiteUrl", Value = "http://www.MySiteDomain.com" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Smtp_Port", Value = "25" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Smtp_Server", Value = "smtp.live.com" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Email_SSL", Value = "false" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Send_Mail_When_Comment_Received", Value = "false" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Tags_Number_of_Tags_per_Page", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "ThumbnailHeight", Value = "150" }); context.Set <BlogResource>().Add(new BlogResource { Name = "ThumbnailWidth", Value = "200" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Users_Number_of_Users_per_Page", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Video_Container_Height", Value = "160" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Video_Container_Width", Value = "250" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Posts_HomeIndexPostsPerPage", Value = "10" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Twitter_User", Value = "" }); context.Set <BlogResource>().Add(new BlogResource { Name = "Twitter_Search_Query", Value = "" }); context.SaveChanges(); }
public JsonResult ModifyUser(User user) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var success = 0; if (!String.IsNullOrEmpty(user.UserId.ToString())) { var cfrp = new CodeFirstRoleProvider(Context); var editUser = Context.Users.FirstOrDefault(x => x.UserId == user.UserId); editUser.Username = user.Username; editUser.FirstName = user.FirstName; editUser.LastName = user.LastName; editUser.Email = user.Email; editUser.UserImageLocation = user.UserImageLocation; editUser.IsLockedOut = user.IsLockedOut; if (user.Roles != null) { // Modify the user roles // First delete existing roles foreach (var role in editUser.Roles.ToList()) { // get current role for comparison var rolesList = user.Roles.Select(a => a.RoleName).ToList(); var userRoles = Context.Roles.Where(x => rolesList.Contains(role.RoleName)).ToList(); var foundRole = !userRoles.Contains(role); // Only remove roles if it's not in the new set if (foundRole) { Roles.RemoveUserFromRole(user.Username, role.RoleName); cfrp.RemoveUsersFromRoles(new string[] {user.Username}, new string[] {role.RoleName}); } } // Add the asigned roles foreach (var role in user.Roles) { // Add to Membership Framework if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] {user.Username}, new string[] {role.RoleName}); } success = Context.SaveChanges(); } } if (success > 0) { result.Data = new { success = true, message = "Changes saved successfully." }; } return result; }
public JsonResult ModifyUser(User user) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var success = 0; if (!String.IsNullOrEmpty(user.UserId.ToString())) { var cfrp = new CodeFirstRoleProvider(Context); var editUser = Context.Users.FirstOrDefault(x => x.UserId == user.UserId); editUser.Username = user.Username; editUser.FirstName = user.FirstName; editUser.LastName = user.LastName; editUser.Email = user.Email; editUser.UserImageLocation = user.UserImageLocation; editUser.IsLockedOut = user.IsLockedOut; if (user.Roles != null) { // Modify the user roles // First delete existing roles foreach (var role in editUser.Roles) { // get current role for comparison var rolesList = user.Roles.Select(a => a.RoleName).ToList(); var userRoles = Context.Roles.Where(x => rolesList.Contains(role.RoleName)).ToList(); var foundRole = !userRoles.Contains(role); // Only remove roles if it's not in the new set if (foundRole) { Roles.RemoveUserFromRole(user.Username, role.RoleName); cfrp.RemoveUsersFromRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } // Add the asigned roles foreach (var role in user.Roles) { // Add to Membership Framework if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } success = Context.SaveChanges(); } } if (success > 0) { result.Data = new { success = true, message = "Changes saved successfully." }; } return(result); }
public JsonResult ModifyUser(User user) { var result = new JsonResult(); if (!String.IsNullOrEmpty(user.UserId.ToString())) { using (var context = new DataContext()) { var cfrp = new CodeFirstRoleProvider(); var editUser = context.Users.FirstOrDefault(x => x.UserId == user.UserId); editUser.Username = user.Username; editUser.UserImageLocation = user.UserImageLocation; editUser.IsLockedOut = user.IsLockedOut; // Modify the user roles // First delete existing roles foreach (var role in editUser.Roles) { // Only remove roles if it's not in the new set if (user.Roles != null && !user.Roles.Contains(role)) { Roles.RemoveUserFromRole(user.Username, role.RoleName); cfrp.RemoveUsersFromRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } // Add the asigned roles foreach (var role in user.Roles) { // Add to Membership Framework if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } context.SaveChanges(); } } return result; }
private string GetUserRole(string userName) { string userRole = string.Empty; if (!string.IsNullOrEmpty(userName)) { userRole = new CodeFirstRoleProvider().GetRolesForUser(userName).FirstOrDefault(); } return userRole; }
public ActionResult ModifyUsersInRole(List<Guid> RemoveUsers, List<Guid> AddUsers, Guid RoleID) { var result = new JsonResult(); var cfrp = new CodeFirstRoleProvider(); using (var context = new DataContext()) { var role = context.Roles.FirstOrDefault(x => x.RoleId == RoleID); if (role == null) { return result; } // Remove Users if (RemoveUsers != null && RemoveUsers.Any()) { foreach (var gid in RemoveUsers) { var user = context.Users.Where(x => x.UserId == gid).FirstOrDefault(); if (user != null) { Roles.RemoveUserFromRole(user.Username, role.RoleName); cfrp.RemoveUsersFromRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } // Add Users if (AddUsers != null && AddUsers.Any()) { foreach (var gid in AddUsers) { var user = context.Users.Where(x => x.UserId == gid).FirstOrDefault(); if (user != null) { // Add to Membership Framework if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } } return result; }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { var cfrp = new CodeFirstRoleProvider(); WebSecurity.CreateUserAndAccount(model.UserName, model.Password); WebSecurity.Login(model.UserName, model.Password); // By default add the user to the admin group, unless user has specified another group in the settings area string defaultRole = "Administrators"; using (var context = new DataContext()) { var siteSettings = context.SiteSettings.FirstOrDefault(); if (siteSettings != null && !String.IsNullOrEmpty(siteSettings.DefaultUserRole)) { defaultRole = siteSettings.DefaultUserRole; } } // Now check if user entered a registration Code. // Registration Codes allow users to be inserted into a non-default role if (!String.IsNullOrEmpty(model.RegistrationCode)) { // Check for a Role that has this registration code using (var context = new DataContext()) { var role = context.Roles.FirstOrDefault(x => x.RegistrationCode == model.RegistrationCode); if (role != null) { defaultRole = role.RoleName; } } } // Make sure roll exists if (!Roles.RoleExists(defaultRole)) { Roles.CreateRole(defaultRole); } // Double Check CodeFirst Provider if (!cfrp.RoleExists(defaultRole)) { cfrp.CreateRole(defaultRole); } // Sanity Check if (!Roles.IsUserInRole(model.UserName, defaultRole)) { Roles.AddUserToRole(model.UserName, defaultRole); } // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] { model.UserName }, new string[] { defaultRole }); return RedirectToAction("Index", "Admin"); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return View(model); }
public static void AssignUserToRole(User user, Role role, CodeFirstRoleProvider cfrp) { if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } cfrp.AddUsersToRoles(new[] { user.Username }, new[] { role.RoleName }); }
public ActionResult ModifyUsersInRole(List <Guid> RemoveUsers, List <Guid> AddUsers, Guid RoleID) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; var cfrp = new CodeFirstRoleProvider(Context); var role = Context.Roles.FirstOrDefault(x => x.RoleId == RoleID); if (role == null) { return(result); } result.Data = new { success = true, message = "Users updated." }; // Remove Users if (RemoveUsers != null && RemoveUsers.Any()) { foreach (var gid in RemoveUsers) { var user = Context.Users.Where(x => x.UserId == gid).FirstOrDefault(); if (user != null) { Roles.RemoveUserFromRole(user.Username, role.RoleName); cfrp.RemoveUsersFromRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } // Add Users if (AddUsers != null && AddUsers.Any()) { foreach (var gid in AddUsers) { var user = Context.Users.Where(x => x.UserId == gid).FirstOrDefault(); if (user != null) { // Add to Membership Framework if (!Roles.IsUserInRole(user.Username, role.RoleName)) { Roles.AddUserToRole(user.Username, role.RoleName); } cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } return(result); }
public static bool IsUserInRole(string user, string role) { CodeFirstRoleProvider rp = new CodeFirstRoleProvider(); return(rp.IsUserInRole(user, role)); }
// PUT api/<controller>/5 public HttpResponseMessage Put(string userName, MembershipViewModel membershipViewModel) { if (!IsAuthorize("write")) { return Request.CreateResponse(HttpStatusCode.Unauthorized); } User user = _facade.GetUserByUserName(userName); if (user != null) { if (ModelState.IsValid && userName == membershipViewModel.Username) { var codeFirstProvider = new CodeFirstRoleProvider(); _facade.RemoveUsersFromRoles(new string[] { user.Username }, user.Roles.Select(x=>x.RoleName).ToArray()); if (!codeFirstProvider.IsUserInRole(user.Username, membershipViewModel.role)) { _facade.AddUsersToRoles(new string[] { user.Username }, new string[] { membershipViewModel.role }); } if (!String.IsNullOrEmpty(membershipViewModel.password)) { user.Password = WebSecurity.GetHash(membershipViewModel.password); user.LastPasswordChangedDate = DateTime.Now; } user.Email = membershipViewModel.email; if(_facade.UpdateUser(user)) return Request.CreateResponse(HttpStatusCode.OK); else return Request.CreateResponse(HttpStatusCode.NotFound); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
public JsonResult AddUser(User user) { var result = new JsonResult(); var cfrp = new CodeFirstRoleProvider(); if (!String.IsNullOrEmpty(user.Username)) { // Add to .Net Membership Framework First WebSecurity.CreateUserAndAccount(user.Username, user.Password); // Now add additional fields to CodeFirst User using (var context = new DataContext()) { var newlyAddedUser = context.Users.Where(x => x.Username == user.Username).FirstOrDefault(); newlyAddedUser.CreateDate = DateTime.Now; newlyAddedUser.UserImageLocation = user.UserImageLocation; context.SaveChanges(); // Add the asigned roles foreach (var role in user.Roles) { // Add to Membership Framework Roles.AddUserToRole(user.Username, role.RoleName); // Add to CodeFirst as well cfrp.AddUsersToRoles(new string[] { user.Username }, new string[] { role.RoleName }); } } } return result; }