public ActionResult DeleteUser(int id = 0) { var user = userprofile.UserProfiles.ToList(); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider; UserProfile profile = userprofile.UserProfiles.Find(id); if (profile == null) { return(View(user)); } else { var roole = roles.GetRolesForUser(profile.UserName); roles.RemoveUsersFromRoles(new[] { profile.UserName }, roole); membership.DeleteUser(profile.UserName, true); var autorised = Request.IsAuthenticated ? User.Identity.Name : "nothing"; if (autorised == profile.UserName) { WebSecurity.Logout(); } TempData["_UserRole"] = "Prosto"; return(RedirectToAction("DeleteUser")); } }
public ActionResult Login(LoginModel model, string returnUrl) { SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider; if (roles.IsUserInRole(model.UserName, "Admin")) { TempData["_UserRole"] = "Admin"; } else if (roles.IsUserInRole(model.UserName, "Moderator")) { TempData["_UserRole"] = "Moderator"; } else { TempData["_UserRole"] = "Prosto"; } if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) { return(RedirectToLocal(returnUrl)); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы ModelState.AddModelError("", "Имя пользователя или пароль указаны неверно."); return(View(model)); }
public void SimpleRoleProvider_CasingBehavior_ValidatesRange(int value, bool isValid) { // Arrange var provider = new SimpleRoleProvider(); var message = "The value of argument 'value' (" + value + ") is invalid for Enum type " + "'SimpleMembershipProviderCasingBehavior'." + Environment.NewLine + "Parameter name: value"; // Act Exception exception = null; try { provider.CasingBehavior = (SimpleMembershipProviderCasingBehavior)value; } catch (Exception ex) { exception = ex; } // Assert if (isValid) { Assert.Equal((SimpleMembershipProviderCasingBehavior)value, provider.CasingBehavior); } else { Assert.NotNull(exception); Assert.IsAssignableFrom<InvalidEnumArgumentException>(exception); Assert.Equal(message, exception.Message); } }
public ActionResult RoleList() { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; var roles = simpleRoles.GetAllRoles().Select(r => new RoleModel(r)); return(View(roles)); }
public void Initialize() { Database.SetInitializer <ShopDBContext>(null); try { using (var context = new ShopDBContext()) { if (!context.Database.Exists()) { ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("ShopDB", "Users", "UserId", "Email", autoCreateTables: true); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider memberships = (SimpleMembershipProvider)Membership.Provider; if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (memberships.GetUser("*****@*****.**", false) == null) { memberships.CreateUserAndAccount("*****@*****.**", "qwerty1234"); roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "Admin" }); } } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public JsonResult CreateAccount(string Address, string Code, string Discount, string Name, string UserName, string Password, string ConfirmPassword) { try { SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; RegisterModel model = new RegisterModel(); model.UserName = UserName; model.Password = Password; model.ConfirmPassword = ConfirmPassword; WebSecurity.CreateUserAndAccount(model.UserName, model.Password); roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Customer" }); Customer customer = new Customer(); customer.Address = Address; customer.Code = Code; customer.Discount = Int32.Parse(Discount); customer.Name = Name; customer.CustomerId = Guid.NewGuid(); customer.UserId = WebSecurity.GetUserId(model.UserName); unitOfWork.CustomerRepository().Insert(customer); unitOfWork.Save(); return(this.Json(new { success = true })); } catch (Exception e) { List <string> ErrorList = new List <string>(); ErrorList.Add(e.Message); return(this.Json(new { success = false, errors = ErrorList })); } }
//[ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { WebSecurity.CreateUserAndAccount(model.Email, model.Password); UsersContext db = new UsersContext(); SimpleRoleProvider provider = new SimpleRoleProvider(); db.UserProfiles.Add(new UserProfile { UserId = WebSecurity.GetUserId(model.Email), FirstName = model.FirstName, LastName = model.LastName }); Roles.AddUsersToRoles(new string[] { model.Email }, new string[] { "User" }); db.SaveChanges(); SmtpClient mail = new SmtpClient(); string str = @"<a href=""http://www.yahoo.com""> Click me </a>"; MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "Email subject", "body"); msg.IsBodyHtml = true; mail.Send(msg); //WebSecurity.Login(model.Email, model.Password); return(RedirectToAction("Index", "Home")); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return(View(model)); }
protected void InitializeUserAndRoles() { SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider; if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (!roles.RoleExists("Manager")) { roles.CreateRole("Manager"); } if (!roles.RoleExists("User")) { roles.CreateRole("User"); } if (membership.GetUser("*****@*****.**", false) == null) { WebSecurity.CreateUserAndAccount("*****@*****.**", "123456", new { IsBlocked = false }); roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "Admin" }); } if (membership.GetUser("*****@*****.**", false) == null) { WebSecurity.CreateUserAndAccount("*****@*****.**", "123456", new { IsBlocked = false }); roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "User" }); } }
public ActionResult Index(LoginModel model) { HttpCookie existingCookie = Request.Cookies["info_username"]; if (model.RememberMe) { if (existingCookie != null) { existingCookie.Expires = DateTime.Today.AddDays(7); } else { HttpCookie newCookie = new HttpCookie("info_username", model.Login); newCookie.Expires = DateTime.Today.AddDays(7); Response.Cookies.Add(newCookie); } } else { if (existingCookie != null) { Response.Cookies["info_username"].Expires = DateTime.Now.AddDays(-1); } } if (ModelState.IsValid && WebSecurity.Login(model.Login, model.Password, persistCookie: model.RememberMe)) { var user = Membership.GetUser(model.Login); if (user != null) { if (Membership.ValidateUser(model.Login, model.Password)) { Session["UserLogin"] = model.Login; FormsAuthentication.SetAuthCookie(user.UserName, true); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; if (roles.IsUserInRole(model.Login, "admin")) { return(RedirectToAction("Index", "Admin")); } if (roles.IsUserInRole(model.Login, "librarian")) { return(RedirectToAction("Index", "LibrarianPage")); } if (roles.IsUserInRole(model.Login, "provider")) { return(RedirectToAction("Index", "ProviderPage")); } if (roles.IsUserInRole(model.Login, "reader")) { return(RedirectToAction("Index", "ReaderPage")); } } } } return(RedirectToAction("Index", "Login")); }
public ActionResult RoleDelete(string id) { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; simpleRoles.DeleteRole(id, false); return(RedirectToAction("RoleList")); }
public ActionResult RoleCreatePost(string name) { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; simpleRoles.CreateRole(name); return(RedirectToAction("RoleList")); }
static string ReadFile(FileTypes fileType, string path, bool isEncrypted, bool useRoles, string role) { IEncryptionProvider encryptionProvider = null; IRoleProvider roleProvider = null; if (isEncrypted) { encryptionProvider = new ReverseEncryption(); } if (useRoles) { roleProvider = new SimpleRoleProvider(); } Reader reader = new Reader(encryptionProvider, roleProvider); try { return(reader.ReadFile(fileType, path, isEncrypted: isEncrypted, role: role)); } catch (UnauthorizedAccessException) { return($"ERROR: Role \"{role}\" is not authorized to access this file"); } }
protected override void Seed(FCIH_OJ.Models.UsersContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // ////////////////////////////////////////////////////// // user module WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); SimpleRoleProvider roles = new SimpleRoleProvider(Roles.Provider); SimpleMembershipProvider membership = new SimpleMembershipProvider(Membership.Provider); if (!roles.RoleExists("admin")) { roles.CreateRole("admin"); } if (!WebSecurity.UserExists("admin")) { WebSecurity.CreateUserAndAccount("admin", "admin", new { Email = "*****@*****.**", Password = "******" }); } if (!roles.GetRolesForUser("admin").Contains("admin")) { roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" }); } //end of user module ////////////////////////////////////////////////////// //other modules }
private void AsignUserRoles(CGDataEntities.CGWebEntities webEntities) { SimpleRoleProvider provider = new SimpleRoleProvider(); List <int> roleKeyList = _usersInRoles.Select(T => T.Value).Distinct().ToList(); foreach (int roleKey in roleKeyList) { string roleName = _roles[roleKey]; int[] usersInRoleIndexes = _usersInRoles.Where(kv => kv.Value.Equals(roleKey)).Select(kv => kv.Key).ToArray(); string[] userNames = new string[usersInRoleIndexes.Count()]; for (int i = 0; i < usersInRoleIndexes.Count(); i++) { userNames[i] = _userProfileList[usersInRoleIndexes[i]].Username; } //wont work without HttpContext :( //provider.AddUsersToRoles(userNames, roleNames); webpages_Roles currentRole = webEntities.webpages_Roles.Where(R => R.RoleName.Equals(roleName)).Single(); foreach (UserProfile profile in webEntities.UserProfiles.Where(UP => userNames.Contains(UP.UserName))) { profile.webpages_Roles.Add(currentRole); } webEntities.SaveChanges(); } log.Info("Added Roles to system."); }
public void SimpleRoleProvider_CasingBehavior_ValidatesRange(int value, bool isValid) { // Arrange var provider = new SimpleRoleProvider(); var message = "The value of argument 'value' (" + value + ") is invalid for Enum type " + "'SimpleMembershipProviderCasingBehavior'." + Environment.NewLine + "Parameter name: value"; // Act Exception exception = null; try { provider.CasingBehavior = (SimpleMembershipProviderCasingBehavior)value; } catch (Exception ex) { exception = ex; } // Assert if (isValid) { Assert.Equal((SimpleMembershipProviderCasingBehavior)value, provider.CasingBehavior); } else { Assert.NotNull(exception); Assert.IsAssignableFrom <InvalidEnumArgumentException>(exception); Assert.Equal(message, exception.Message); } }
protected void ExistenceRole(SimpleRoleProvider provider, string role) { if (!provider.RoleExists(role)) { provider.CreateRole(role); } }
private static SimpleRoleProvider CreateDefaultSimpleRoleProvider(string name, RoleProvider currentDefault) { var roleProvider = new SimpleRoleProvider(previousProvider: currentDefault); NameValueCollection config = new NameValueCollection(); roleProvider.Initialize(name, config); return(roleProvider); }
public ExcelHelper(ExcelWorkbook workBook, PortalContext db) { _usersRegister = new Dictionary <string, UserRegister>(); currentWorkBook = workBook; roles = (SimpleRoleProvider)Roles.Provider; membership = (SimpleMembershipProvider)Membership.Provider; currentDb = db; }
public SimpleMembershipInitializer() { Database.SetInitializer <UsersContext>(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // Создание базы данных SimpleMembership без применения миграции Entity Framework ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } // Настройка ASP.NET Simple Membership // 1 параметр - имя строки подключения к базе данных. // 2 параметр - таблица, которая содержит информацию о пользователях // 3 параметр - имя колонки в таблице, которая отвечает за хранение логина // 4 параметр - autoCreateTables автоматическое создание таблиц если они не существуют в базе WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider; // Проверка наличия роли Moderator if (!roles.RoleExists("Moderator")) { roles.CreateRole("Moderator"); } // Проверка наличия роли Admin if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (membership.GetUser("OverLord56_1", false) == null) { membership.CreateUserAndAccount("OverLord56_1", "89Zxcv"); // создание пользователя roles.AddUsersToRoles(new[] { "OverLord56_1" }, new[] { "Admin" }); // установка роли для пользователя } // Поиск пользователя с логином admin if (membership.GetUser("admin", false) == null) { membership.CreateUserAndAccount("admin", "qwe123"); // создание пользователя roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); // установка роли для пользователя } if (membership.GetUser("user1", false) == null) { membership.CreateUserAndAccount("user1", "qwe123"); roles.AddUsersToRoles(new[] { "user1" }, new[] { "Moderator" }); } } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public SimpleMembershipInitializer() { Database.SetInitializer <UsersContext>(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // Создание базы данных SimpleMembership без схемы миграции Entity Framework ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } // WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider; // Проверка наличия роли Moderator if (!roles.RoleExists("Moderator")) { roles.CreateRole("Moderator"); } // Проверка наличия роли Admin if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (!roles.RoleExists("User")) { roles.CreateRole("User"); } // Поиск пользователя с логином admin if (membership.GetUser("admin", false) == null) { membership.CreateUserAndAccount("admin", "qwe123"); // создание пользователя roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); // установка роли для пользователя } if (membership.GetUser("user1", false) == null) { membership.CreateUserAndAccount("user1", "qwe123"); roles.AddUsersToRoles(new[] { "user1" }, new[] { "Moderator" }); } } catch (Exception ex) { throw new InvalidOperationException("Не удалось инициализировать базу данных ASP.NET Simple Membership. Чтобы получить дополнительные сведения, перейдите по адресу: http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public ActionResult RoleAddUser(string id, string selectedUserNameFromList) { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; if (!simpleRoles.IsUserInRole(selectedUserNameFromList, id)) { simpleRoles.AddUsersToRoles(new string[] { selectedUserNameFromList }, new string[] { id }); } return(PartialView("RoleUserList", simpleRoles.GetUsersInRole(id))); }
public void AllowAdmin() { SimpleRoleProvider provider = new SimpleRoleProvider(); string path = "C:/user_test.txt"; string role = "admin"; bool expected = true; bool actual = provider.HasAccess(path, role); Assert.Equal(expected, actual); }
public ActionResult RoleEdit(string id) { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; var model = new RoleModel(id) { PrevName = id, UserList = simpleRoles.GetUsersInRole(id) }; return(View(model)); }
public void DenyUser_WhenFileDoesntStartWithUser() { SimpleRoleProvider provider = new SimpleRoleProvider(); string path = "C:/admin_test.txt"; string role = "user"; bool expected = false; bool actual = provider.HasAccess(path, role); Assert.Equal(expected, actual); }
protected override void Seed(PortalContext context) { WebSecurity.InitializeDatabaseConnection("PortalContext", "UserProfile", "UserId", "UserName", autoCreateTables: true); roles = (SimpleRoleProvider)Roles.Provider; membership = (SimpleMembershipProvider)Membership.Provider; if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (!roles.RoleExists("Member")) { roles.CreateRole("Member"); } if (!roles.RoleExists("RefundVisualizator")) { roles.CreateRole("RefundVisualizator"); } if (!roles.RoleExists("RefundAdministrator")) { roles.CreateRole("RefundAdministrator"); } if (!roles.RoleExists("Manager")) { roles.CreateRole("Manager"); } if (!roles.RoleExists("Freelancer")) { roles.CreateRole("Freelancer"); } if (membership.GetUser("admin", false) == null) { membership.CreateUserAndAccount("admin", "pesca160064"); } if (!roles.GetRolesForUser("admin").Contains("Admin")) { roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); } var currentCpf = "38287346851"; CheckUser(currentCpf, "Bruno Tachinardi Andrade Silva", "*****@*****.**"); CheckRefund(currentCpf); CheckRefundAdministrator(currentCpf); CheckManager(currentCpf, "BRUNO"); CheckFreelancer(currentCpf, "BRUNO", 8, 1200, 128, 50, FreelancerType.EDUCATOR); currentCpf = "17858466801"; CheckUser(currentCpf, "Pedro de Almeida Pereira", "*****@*****.**"); CheckRefund(currentCpf); CheckFreelancer(currentCpf, "BRUNO", 8, 1200, 128, 50, FreelancerType.EDUCATOR); }
public void AllowUser_WhenFileStartsWithUser() { SimpleRoleProvider provider = new SimpleRoleProvider(); string path = "C:/user_test.txt"; string role = "user"; bool expected = true; bool actual = provider.HasAccess(path, role); Assert.Equal(expected, actual); }
public ActionResult RoleEdit(RoleModel model) { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; var users = simpleRoles.GetUsersInRole(model.PrevName); simpleRoles.RemoveUsersFromRoles(users, new string[] { model.PrevName }); simpleRoles.DeleteRole(model.PrevName, false); simpleRoles.CreateRole(model.Name); simpleRoles.AddUsersToRoles(users, new string[] { model.Name }); return(RedirectToAction("RoleList")); }
public ActionResult RoleDetails(string id) { SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider; var model = new RoleModel(id); model.UserList = simpleRoles.GetUsersInRole(id); using (var context = new UsersContext()) { model.FullUserList = new SelectList(context.UserProfiles.ToList(), "UserName", "UserName"); } return(View(model)); }
public JsonResult GetPositionsByOrderId(Guid?OrderId) { try { var orderPositions = unitOfWork.PositionRepository().Get(d => d.OrderId == OrderId); List <ManagerPositionInfo> positionInfoList = new List <ManagerPositionInfo>(); Order order = unitOfWork.OrderRepository().GetByID(OrderId); // Проверка соответствия запрашиваемого заказа пользователю string currentUser = User.Identity.Name; int userId = WebSecurity.GetUserId(currentUser); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; string userRole = roles.GetRolesForUser(currentUser).First(); if (userRole == "Customer") { Customer currentСustomer = unitOfWork.CustomerRepository().Get(d => d.UserId == userId).First(); if (currentСustomer.CustomerId != order.CustomerId) { throw new Exception("Запрашиваемый заказ Вам не принадлежит"); } } Customer customer = unitOfWork.CustomerRepository().GetByID(order.CustomerId); ManagerCustomerInfo customerInfo = new ManagerCustomerInfo(); customerInfo.Name = customer.Name; customerInfo.Address = customer.Address; customerInfo.Discount = customer.Discount; foreach (var position in orderPositions) { ManagerPositionInfo positionInfo = new ManagerPositionInfo(); positionInfo.ItemsCount = position.ItemsCount; // Получение данных о товаре Item item = unitOfWork.ItemRepository().GetByID(position.ItemId); positionInfo.Name = item.Name; positionInfo.Price = item.Price; positionInfoList.Add(positionInfo); } return(this.Json(new { success = true, data = positionInfoList, info = customerInfo }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(this.Json(new { success = false, error = e.Message })); } }
internal static void InitializeRoleProvider(SimpleRoleProvider simpleRoles, DatabaseConnectionInfo connect, string userTableName, string userIdColumn, string userNameColumn, bool createTables) { if (simpleRoles.InitializeCalled) { throw new InvalidOperationException(WebDataResources.Security_InitializeAlreadyCalled); } simpleRoles.ConnectionInfo = connect; simpleRoles.UserTableName = userTableName; simpleRoles.UserIdColumn = userIdColumn; simpleRoles.UserNameColumn = userNameColumn; if (createTables) { simpleRoles.CreateTablesIfNeeded(); } simpleRoles.InitializeCalled = true; }
public ActionResult Login(LoginModel model, string returnUrl) { //Витягуємо роль користувача і при LogOut SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider; if (roles.IsUserInRole(model.UserName, "Admin")) { TempData["_UserRole"] = "Admin"; } else if (roles.IsUserInRole(model.UserName, "Moderator")) { TempData["_UserRole"] = "Moderator"; } else { TempData["_UserRole"] = "Prosto"; } // WebSecurity.Login - аутентифицирует пользователя. // Если логин и пароль введены правильно - метод возвращает значение true после чего выполняет добавление специальных значений в cookies. if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) { try { if (HttpContext.Request.Cookies["num_of_film"].Value == null) { return(RedirectToAction("Index", "Home")); } else { return(RedirectToLocal(returnUrl)); } } catch { return(RedirectToAction("Index", "Home")); } } // Был введен не правильный логин или пароль ModelState.AddModelError("", "The user name or password provided is incorrect."); return(View(model)); }
private static SimpleRoleProvider CreateDefaultSimpleRoleProvider(string name, RoleProvider currentDefault) { var roleProvider = new SimpleRoleProvider(previousProvider: currentDefault); NameValueCollection config = new NameValueCollection(); roleProvider.Initialize(name, config); return roleProvider; }