private static async Task SeedUsers(UserManager <User> userManager) { var res = await userManager.CreateAsync(new User { UserName = "******", PhoneNumber = "0000000000", Name = "Administrator", Email = "*****@*****.**", Profile = new UserProfile { Name = "Administrator", Description = "Administrator Role", Privileges = RoleNames.Aggregate((a, b) => $"{a},{b}"), Locked = true }, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, "admin@app"); if (res.Succeeded) { var user = userManager.FindByNameAsync("Admin").Result; await userManager.AddToRolesAsync(user, RoleNames); } }
public async Task <ActionResult> Edit([Bind(Include = "Id,FirstName,LastName,Email,PhoneNumber,Login,Password,ConfirmPassword,OldHashedPassword,IsActive,InititallySelectedRoles")] CustomerCreateUpdateViewModel customer, int[] roleId) { if (ModelState.IsValid) { var customerEntity = (CustomerEntity)customer; _db.Entry(customerEntity).State = EntityState.Modified; await _db.SaveChangesAsync(); // Updating roles var selectedRoleNames = roleId.Select(id => _db.Roles.Find(id).Name); var notSelectedNamesInRole = RoleNames.GetAllRoleNames().Except(selectedRoleNames).Where(roleName => Roles.IsUserInRole(customer.Login, roleName)).ToArray(); if (notSelectedNamesInRole.Length > 0) { Roles.RemoveUserFromRoles(customer.Login, notSelectedNamesInRole); } var selectedNamesNotInRole = selectedRoleNames.Where(roleName => !Roles.IsUserInRole(customer.Login, roleName)).ToArray(); if (selectedNamesNotInRole.Length > 0) { Roles.AddUserToRoles(customer.Login, selectedNamesNotInRole); } return(RedirectToAction("Index")); } return(View(customer)); }
public ActionResult _SetUserRoles(long userId, string returnUrl) { IEnumerable <Role> AllRoles = roleService.GetRoles(); IEnumerable <Role> roles = null; if (AllRoles != null) { IUser currentUser = UserContext.CurrentUser; long FounderId = systemDataService.GetLong("Founder"); if (FounderId == currentUser.UserId) { roles = AllRoles; } else if (authorizer.IsSuperAdministrator(currentUser)) { roles = AllRoles.Where(n => n.RoleName != RoleNames.Instance().SuperAdministrator()); } else { roles = AllRoles.Where(n => n.RoleName != RoleNames.Instance().SuperAdministrator() || n.RoleName != RoleNames.Instance().ContentAdministrator()); } } ViewData["user"] = userService.GetFullUser(userId); ViewData["returnUrl"] = returnUrl; return(View(roles)); }
/// <summary> /// Evaluates whether the field should be shown or hidden. If this method returns null, the next filter attribute will be evaluated. /// </summary> public VisibilityMode?CanShow(IViewContext viewContext) { if (viewContext.CurrentUser != null && RoleNames.Any(viewContext.CurrentUser.IsInRole)) { return(Mode); } return(null); }
/// <inheritdoc /> public async Task InitializeRoles() { foreach (var roleName in RoleNames.GetAllRoleNames()) { if (!await _roleManager.RoleExistsAsync(roleName)) await _roleManager.CreateAsync(new IdentityRole(roleName)); } }
/// <summary> /// Configures the admin account /// </summary> /// <returns>Task</returns> private static async Task ConfigureAdminAccount() { ServiceProvider serviceProvider = ServiceProviderBuilder.BuildServiceProvider(); IUserDbAccess userDbAccess = serviceProvider.GetService <IUserDbAccess>(); if (await userDbAccess.DoesAdminUserExist()) { MessageService.PrintAdminAccountExistMessage(); return; } string email; do { try { string displayName = MessageService.GetAdminAccountDisplayName(); email = MessageService.GetAdminAccountEMail(); string password = MessageService.GetAdminAccountPassword(); IUserCreator userCreator = serviceProvider.GetService <IUserCreator>(); IdentityResult result = await userCreator.CreateUser(new MockUrlHelper(), "https", displayName, email, password, RoleNames.Administrator); if (!result.Succeeded) { throw new Exception(string.Join(',', result.Errors.Select(e => e.Description))); } MessageService.PrintSuccessCreatingAdminAccount(); break; } catch (Exception ex) { MessageService.PrintErrorCreatingAdminAccount(ex); } }while(true); try { UserManager <GoNorthUser> userManager = serviceProvider.GetService <UserManager <GoNorthUser> >(); GoNorthUser adminUser = await userManager.FindByEmailAsync(email); List <string> rolesToAdd = RoleNames.GetAllRoleNames().Where(r => r != RoleNames.Administrator).ToList(); IdentityResult result = await userManager.AddToRolesAsync(adminUser, rolesToAdd); if (!result.Succeeded) { throw new Exception(string.Join(',', result.Errors.Select(e => e.Description))); } } catch (Exception ex) { MessageService.PrintErrorAssignAllRolesToUser(ex); } }
public ActionResult ManageTags(string keyword, string tenantTypeId, bool?isFeatured, AuditStatus?auditStatus = null, int pageIndex = 1, int pageSize = 20) { pageResourceManager.InsertTitlePart("标签管理"); TagService tagService = new TagService(tenantTypeId); PubliclyAuditStatus?publiclyAuditStatus = null; if (auditStatus != null) { publiclyAuditStatus = (PubliclyAuditStatus?)auditStatus; } TagQuery tagQuery = new TagQuery(); tagQuery.PubliclyAuditStatus = publiclyAuditStatus; tagQuery.Keyword = keyword; tagQuery.TenantTypeId = tenantTypeId; if (isFeatured.HasValue) { tagQuery.IsFeatured = isFeatured.Value; } PagingDataSet <Tag> tags = tagService.GetTags(tagQuery, pageIndex, pageSize); AuthorizationService authorizationService = new AuthorizationService(); //所属下拉框 List <TenantType> tenantTypesList = tenantTypeService.Gets(MultiTenantServiceKeys.Instance().Tag()).ToList <TenantType>(); List <TenantType> newTenantTypesList = new List <TenantType>(); if (UserContext.CurrentUser.IsInRoles(RoleNames.Instance().SuperAdministrator(), RoleNames.Instance().ContentAdministrator())) { newTenantTypesList.Insert(0, new TenantType { ApplicationId = 0, Name = "不限", TenantTypeId = "" }); newTenantTypesList.AddRange(tenantTypesList); } else { foreach (var item in tenantTypesList) { if (new AuthorizationService().IsApplicationManager(UserContext.CurrentUser, item.ApplicationId)) { newTenantTypesList.Add(item); } } } SelectList tenants = new SelectList(newTenantTypesList.Select(n => new { text = n.Name, value = n.TenantTypeId }), "value", "text", tenantTypeId); ViewData["tenants"] = tenants; //所属名称 Dictionary <string, string> tenantsDictionary = tenantTypesList.ToDictionary(n => n.TenantTypeId, n => n.Name); ViewData["tenantsDictionary"] = tenantsDictionary; return(View(tags)); }
/// <summary> /// 是不是内容管理员 /// </summary> public bool IsContentAdministrator(IUser user) { IEnumerable <Role> rolesOfUser = new RoleService().GetRolesOfUser(user.UserId); if (rolesOfUser == null) { return(false); } return(rolesOfUser.Where(n => n.RoleName == RoleNames.Instance().ContentAdministrator()).Count() > 0 ? true : false); }
/// <summary> /// Adds a user to a role /// </summary> /// <param name="user">User</param> /// <param name="roleName">Rolename</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>Task</returns> public async Task AddToRoleAsync(GoNorthUser user, string roleName, CancellationToken cancellationToken) { GoNorthUser completeUser = await _UserDbAccess.GetUserById(user.Id); string interalRoleName = RoleNames.GetRoleNameByNormalizedName(roleName); completeUser.Roles.Add(interalRoleName); user.Roles.Add(interalRoleName); await _UserDbAccess.UpdateUser(completeUser); }
/// <summary> /// 常用操作侧边栏 /// </summary> /// <returns></returns> public ActionResult _CommonOperationMenu() { if (!UserContext.CurrentUser.IsInRoles(RoleNames.Instance().SuperAdministrator(), RoleNames.Instance().ContentAdministrator())) { return(new EmptyResult()); } var userId = UserContext.CurrentUser.UserId; IEnumerable <InitialNavigation> commonOperations = navigationService.GetCommonOperations(userId); return(View(commonOperations)); }
public override IActionResult GetRoles() { var result = _supervisor.SafeExecute ( () => { return(RoleNames.GetRoles()); } ); return(new JsonResult(result)); }
private static void CheckBeforeUpdate(DataModel.Account dbItem, Account account, DataContext context) { if (dbItem == null) { throw new InconsistencyException ( string.Format(Resources.TextMessages.WasAlreadyDeleted, account.GetType().Name) ); } if (string.IsNullOrEmpty(account.Login)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.ThePropertyCantBeEmpty, "Login") ); } if (string.IsNullOrEmpty(account.Role)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.ThePropertyCantBeEmpty, "Role") ); } var allRoles = RoleNames.GetRoles(); if (!allRoles.Contains(account.Role)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.TheRoleDoesNotExist, account.Role) ); } if (dbItem.Version != account.Version) { throw new InconsistencyException ( string.Format(Resources.TextMessages.ItemWasAlreadyChanged, account.GetType().Name) ); } if (dbItem.Login != account.Login && context.Accounts.Any(x => x.Login == account.Login)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.PropertyDuplicate, "Login") ); } }
/// <summary> /// 设置所有角色名 /// </summary> /// <param name="roles"></param> public void SetRoleNames(IRole[] roles) { if (roles == null) { return; } if (!RoleNames.IsNullOrWhiteSpace()) { return; } RoleNames = roles.Select(s => s.Name).Join(); }
public async Task UserWithNecessaryRightsCanGetUserInfo(RoleNames role) { var correctInfo = AutoMapper.Mapper.Map <User, UserInfoResponse>(TestData.User); var response = await Api.Client.WithRole(role).GetAsync(_uri + "/user/" + TestData.User.Id); var body = await response.Content.ReadAsStringAsync(); var info = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfoResponse>(body); response.StatusCode.Should().BeEquivalentTo(200); info.Should().BeEquivalentTo(correctInfo); }
protected override void Seed(ShoppingListContext context) { context.UserVerificationStatuses.AddOrUpdate( b => b.UserVerificationStatusId, UserVerificationStatus.GetDefaults().ToArray()); context.UserVerificationReasons.AddOrUpdate(uv => uv.UserVerificationReasonId, UserVerificationReason.GetDefaults().ToArray()); context.Roles.AddOrUpdate(r => r.Name, RoleNames.GetRolesWithCaptions().Select(r => new IdentityRole { Name = r.Key, ArabicName = r.Value, EnglishName = r.Value }).ToArray()); context.SaveChanges(); }
public async Task InitializeDefaultDataTest() { //Act await _service.InitializeRoles(); await _service.InitializeAdmin(); var admin = _dataContext.Users.First(); //Assert Assert.AreEqual(RoleNames.GetAllRoleNames().Count(), _dataContext.Roles.Count()); Assert.AreEqual(1, _dataContext.Users.Count()); Assert.AreEqual("*****@*****.**", admin.UserName); }
/// <summary> /// 验证当前用户是否修改皮肤的权限 /// </summary> /// <param name="ownerId"></param> /// <returns></returns> public bool Validate(long ownerId) { IUser currentUser = UserContext.CurrentUser; if (currentUser == null) { return(false); } if (currentUser.IsInRoles(RoleNames.Instance().SuperAdministrator(), RoleNames.Instance().ContentAdministrator())) { return(true); } return(false); }
public ActionResult AddNewRole(string id) { UserRole userroles = new UserRole(); try { ApplicationUser user = new ApplicationUser(); using (ApplicationDbContext db = new ApplicationDbContext()) { //user = db.Users.Find("cca628e9-d8c9-4c6f-9195-47aa75db3ffc"); user = db.Users.Find(id); userroles.Id = user.Id; userroles.name = user.Email; userroles.Role = "fgh"; } RoleNames role1 = new RoleNames() { id = "1", Role = "Admin" }; RoleNames role2 = new RoleNames() { id = "2", Role = "Superuser" }; RoleNames role3 = new RoleNames() { id = "3", Role = "User" }; List <RoleNames> roles = new List <RoleNames>(); roles.Add(role1); roles.Add(role2); roles.Add(role3); ViewBag.Role = new SelectList(roles, "Role", "Role"); } catch (Exception e) { throw e; } return(View(userroles)); }
public async Task UserWithNecessaryRightsCanModifyUser(RoleNames role) { var request = AutoMapper.Mapper.Map <User, UpdateUserInfoRequest>(TestData.ModifyUser()); var response = await Api.Client.WithRole(role).PatchAsJsonAsync(_uri + "/user/36", typeof(UpdateUserInfoRequest), request); response.StatusCode.Should().BeEquivalentTo(200); var body = await response.Content.ReadAsStringAsync(); var profile = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfoResponse>(body); profile.Should().BeEquivalentTo(request); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // eğer sesion kullanırsak if (filterContext.RequestContext.HttpContext.Session["User"] == null) { filterContext.Result = new RedirectResult("/Account/Login", false); return; } //todo User içinde roller hatalı bu nedenle tekrar db nesnesini kullandık incele @KADİR var User = Service.LoginControl.ControlLogin(); if (User == null) { filterContext.Result = new RedirectResult("/Account/Login", false); return; } if (!string.IsNullOrEmpty(RoleNames)) { Data.SimpleData db = new Data.SimpleData(); List <Data.Role> userDbRoles = db.Users.FirstOrDefault(t => t.ID == User.ID).Roles.ToList(); string[] roles = RoleNames.Split(';'); List <string> userroles = userDbRoles.Select(t => t.Name).ToList(); var result = true; foreach (var item in roles) { if (!userroles.Contains(item)) { result = false; break; } } if (result != true) { //yetkisiz bir sayfaya giriş yapılmaya çalışılıyor filterContext.Result = new RedirectResult("/Error/Index", false); } } }
/// <summary> /// It will call initially from global ascx /// </summary> public static void Setup() { var roles = RoleNames.GetRoles(); var manager = Users.Roles; foreach (var role in roles) { if (!Users.Roles.RoleExists(role)) { var roleEntity = new IdentityRole() { Name = role, }; manager.Create(roleEntity); } } }
/// <summary> /// Removes the unused roles for the users /// </summary> /// <param name="userDbAccess">Usser Db Access</param> /// <returns>Task</returns> private async Task RemoveUnusedRolesForUsers(IUserDbAccess userDbAccess) { List <string> existingRoles = RoleNames.GetAllRoleNames(); IList <GoNorthUser> users = await userDbAccess.GetUsers(0, int.MaxValue); foreach (GoNorthUser curUser in users) { IEnumerable <string> deletedRoles = curUser.Roles.Except(existingRoles); if (deletedRoles != null && deletedRoles.Any()) { GoNorthUser user = await userDbAccess.GetUserById(curUser.Id); user.Roles = curUser.Roles.Except(deletedRoles).ToList(); await userDbAccess.UpdateUser(user); } } }
public void CheckBeforeCreate(Account account) { if (string.IsNullOrEmpty(account.Login)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.ThePropertyCantBeEmpty, "Login") ); } if (string.IsNullOrEmpty(account.Password)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.ThePropertyCantBeEmpty, "Password") ); } if (string.IsNullOrEmpty(account.Role)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.ThePropertyCantBeEmpty, "Password") ); } var allRoles = RoleNames.GetRoles(); if (!allRoles.Contains(account.Role)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.TheRoleDoesNotExist, account.Role) ); } if (_context.Accounts.Any(x => x.Login == account.Login)) { throw new InconsistencyException ( string.Format(Resources.TextMessages.PropertyDuplicate, "Login") ); } }
public ActionResult Login(LoginViewModel model, string returnUrl, string errorMessage) { if (!RoleNames.GetRoleNamesWithAcccessToSite().Any(r => Roles.GetRolesForUser(model.Login).Contains(r))) { ModelState.AddModelError("", "Your current role(s) has no access to this site."); FormsAuthentication.SignOut(); return(View(model)); } if (ModelState.IsValid) { if (Membership.ValidateUser(model.Login, model.Password)) { var membershipUser = Membership.GetUser(model.Login); if (membershipUser != null && membershipUser.IsApproved) { FormsAuthentication.SetAuthCookie(model.Login, true); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Customers")); } } else { ModelState.AddModelError("", "The user is disabled. Please contact to your system administrator."); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public List <RoleModel> GetIDMRoles() { string[] allowedRoles; System.Security.Claims.ClaimsPrincipal user = _httpContextAccessor.HttpContext.User; if (user.UserIsVRO()) { allowedRoles = RoleNames.GetVROMonafasatRoles(); } else { allowedRoles = RoleNames.GetMonafasatRoles(); } var result = _iDMAppService.GetIDMRoles(); return(result.Where(alw => allowedRoles.Contains(alw.Name)).Select(r => new RoleModel() { RoleId = r.Id, RoleName = r.Name, RoleNameAr = r.NormalizedName }).ToList()); }
/// <summary> /// 验证当前用户是否修改皮肤的权限 /// </summary> /// <param name="ownerId"></param> /// <returns></returns> public bool Validate(long ownerId) { IUser currentUser = UserContext.CurrentUser; if (currentUser == null) { return(false); } PresentArea pa = new PresentAreaService().Get(PresentAreaKeysOfBuiltIn.UserSpace); if (!pa.EnableThemes) { return(false); } if (currentUser.UserId == ownerId || currentUser.IsInRoles(RoleNames.Instance().SuperAdministrator(), RoleNames.Instance().ContentAdministrator())) { return(true); } return(false); }
public ActionResult UpdateUserRoles(long userId, string returnUrl) { if (!authorizer.User_Manage(userId)) { return(Json(new StatusMessageData(StatusMessageType.Error, "对不起,您没有权限对此用户操作"))); } IEnumerable <string> strRoles = null; if (Request.Form.Gets <string>("RoleName") == null) { } else { strRoles = Request.Form.Gets <string>("RoleName").Where(n => !n.Equals("false", StringComparison.CurrentCultureIgnoreCase)); } roleService.RemoveUserRoles(userId); if (strRoles != null) { IUser currentUser = UserContext.CurrentUser; IEnumerable <Role> rolesOfUsers = roleService.GetRolesOfUser(currentUser.UserId); long FounderId = systemDataService.GetLong("Founder"); if (currentUser.UserId == FounderId) { roleService.AddUserToRoles(userId, strRoles.ToList()); return(Redirect(returnUrl)); } else if (authorizer.IsSuperAdministrator(currentUser)) { if (strRoles.Where(n => n.ToString() == RoleNames.Instance().SuperAdministrator()).Count() > 0 ? false : true) { roleService.AddUserToRoles(userId, strRoles.ToList()); return(Redirect(returnUrl)); } } } return(Json(new StatusMessageData(StatusMessageType.Error, "对不起,您没有权限执行此操作"))); }
/// <summary> /// 判断浏览着是否具有管理权限 /// </summary> /// <param name="navigation"></param> /// <param name="currentUser"></param> /// <returns></returns> public static bool IsControlPanelManageable(this InitialNavigation navigation, IUser currentUser) { if (currentUser.IsInRoles(RoleNames.Instance().SuperAdministrator())) { return(true); } if (navigation.ApplicationId > 0) { if (new Authorizer().IsAdministrator(navigation.ApplicationId)) { return(true); } } else if (currentUser.IsInRoles(RoleNames.Instance().ContentAdministrator()) && !navigation.UrlRouteName.StartsWith("ControlPanel_User") && !navigation.UrlRouteName.StartsWith("ControlPanel_Settings")) { return(true); } if (navigation.UrlRouteName == "ControlPanel_Home" || navigation.UrlRouteName == "ControlPanel_Content_Home") { return(true); } return(false); }
protected override void Seed(RefactorName.SqlServerRepository.AppDbContext 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. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // //Roles context.Roles.AddOrUpdate( r => r.Id, RoleNames.GetRolesWithCaptions().Select(r => new IdentityRole { Name = r.Key }).ToArray()); }
/// <summary> /// 获取租户类型 /// </summary> /// <param name="tenantTypeId"></param> /// <param name="isEditTag">是否是编辑标签</param> /// <returns></returns> private SelectList GetTenantSelectList(string serviceKey, string tenantTypeId, bool isEditTag = false) { IEnumerable <TenantType> tenantTypes = tenantTypeService.Gets(serviceKey); List <TenantType> newTenantTypesList = new List <TenantType>(); if (UserContext.CurrentUser.IsInRoles(RoleNames.Instance().SuperAdministrator(), RoleNames.Instance().ContentAdministrator())) { if (!isEditTag) { newTenantTypesList.Insert(0, new TenantType { ApplicationId = 0, Name = "不限", TenantTypeId = "" }); } newTenantTypesList.AddRange(tenantTypes); } else { foreach (var item in tenantTypes) { if (new AuthorizationService().IsApplicationManager(UserContext.CurrentUser, item.ApplicationId)) { newTenantTypesList.Add(item); } } } SelectList tenants = null; if (string.IsNullOrEmpty(tenantTypeId)) { tenants = new SelectList(newTenantTypesList.Select(n => new { text = n.Name, value = n.TenantTypeId }), "value", "text"); } else { tenants = new SelectList(newTenantTypesList.Select(n => new { text = n.Name, value = n.TenantTypeId }), "value", "text", tenantTypeId); } return(tenants); }
public AgencyBuilder WithRole(RoleNames role) { defaultRole = role; return this; }