public void Refresh() { RoleCache.GetInstance().Clear(); Roles = new ObservableCollection <EmployeeRole>(RoleCache.GetInstance().Roles); ListViewRoles.ItemsSource = Roles; ListViewRoles.SelectedItem = GetFirstRole(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { var highProfile = RoleCache.Get(ddlHighRoles.SelectedValue.AsInteger()); var extremeProfile = RoleCache.Get(ddlExtremeRoles.SelectedValue.AsInteger()); if (highProfile == null || extremeProfile == null) { return; } _securitySettingsService.SecuritySettings.AccountProtectionProfilesForDuplicateDetectionToIgnore = cblIgnoredAccountProtectionProfiles.SelectedValuesAsInt.Select(a => ( AccountProtectionProfile )a).ToList(); _securitySettingsService.SecuritySettings.DisableTokensForAccountProtectionProfiles = cblDisableTokensForAccountProtectionProfiles.SelectedValuesAsInt.Select(a => ( AccountProtectionProfile )a).ToList(); _securitySettingsService.SecuritySettings.AccountProtectionProfileSecurityGroup.AddOrReplace(AccountProtectionProfile.Extreme, extremeProfile); _securitySettingsService.SecuritySettings.AccountProtectionProfileSecurityGroup.AddOrReplace(AccountProtectionProfile.High, highProfile); if (_securitySettingsService.Save()) { nbSaveResult.Text = "Your Security Settings have been saved."; nbSaveResult.NotificationBoxType = NotificationBoxType.Success; nbSaveResult.Visible = true; } else { var errors = "<li>" + _securitySettingsService.ValidationResults.Select(r => r.ErrorMessage).JoinStrings("</li><li>") + "</li>"; errors = errors.Replace("<li></li>", string.Empty); nbSaveResult.Text = $"The following errors occurred while trying to save:<ul>{errors}</ul>"; nbSaveResult.NotificationBoxType = NotificationBoxType.Danger; nbSaveResult.Visible = true; } }
} // InitOnStart private static void RegisterGlobalFilters(GlobalFilterCollection filters) { const string webRole = "Web"; var underwriterRoles = string.Join(", ", ObjectFactory.GetInstance <IRolesRepository>() .GetAll() .Where(x => x.Name != webRole) .Select(x => x.Name)); if (CurrentValues.Instance.LandingPageEnabled) { filters.Add(new WhiteListFilter(), 0); } RoleCache roleCache = new RoleCache(); filters.Add( new GlobalAreaAuthorizationFilter( roleCache, GlobalAreaAuthorizationFilter.AreaName.Underwriter, underwriterRoles ), 1 ); filters.Add( new GlobalAreaAuthorizationFilter(roleCache, GlobalAreaAuthorizationFilter.AreaName.Customer, webRole), 1 ); filters.Add(new EzBobHandleErrorAttribute()); filters.Add(new LoggingContextFilter(), 1); } // RegisterGlobalFilters
private Role(RoleCache role) { Id = role.Id; Name = role.Name; IsSecurityTypeGroup = role.IsSecurityTypeGroup; People = new ConcurrentDictionary <Guid, bool>(role.People); }
private void ButtonDashboard_Click(object sender, RoutedEventArgs e) { TextblockPanelName.Text = "Dashboard"; RoleCache.GetInstance().Clear(); EmployeeCache.GetInstance().Clear(); ResourceCache.GetInstance().Clear(); CustomerCache.GetInstance().Clear(); ProcessCache.GetInstance().Clear(); ProjectCache.GetInstance().Clear(); List <Resource> recs = ResourceCache.GetInstance().Resources; recs = ResourceCache.GetInstance().UpdateAllQSizes(); recs = recs.OrderByDescending(r => r.QSize).ToList <Resource>(); var emps = EmployeeCache.GetInstance().Employees; emps = EmployeeCache.GetInstance().UpdateAllQSizes(); emps = emps.OrderByDescending(e => e.QSize).ToList <Employee>(); DataContext = new DashboardViewModel { Resources = new ObservableCollection <Resource>(recs), SelectedResource = recs[0], Employees = new ObservableCollection <Employee>(emps), SelectedEmployee = emps[0] }; }
private void ProjectViewNewProjectClickHandler(ProjectsViewModel viewModel) { TextblockPanelName.Text = "Create New Project"; RoleCache.GetInstance().Clear(); EmployeeCache.GetInstance().Clear(); ResourceCache.GetInstance().Clear(); CustomerCache.GetInstance().Clear(); ProcessCache.GetInstance().Clear(); ProjectCache.GetInstance().Clear(); var resources = ResourceCache.GetInstance().Resources; resources = ResourceCache.GetInstance().UpdateAllQSizes(); DataContext = new AddEditProjectViewModel { Project = new Project { Id = 0, Processes = new List <Process>(), StartDate = DateTimeOffset.UtcNow, PoDate = DateTimeOffset.UtcNow, Quantity = 1, OrderStatus = Project.ProjectOrderStatus.WaitingQuote, }, BackClickedHandler = AddEditProjectViewBackClickHandler, Customers = CustomerCache.GetInstance().Customers, Processes = new ObservableCollection <Process>(new List <Process>()), Resources = resources.OrderByDescending(r => r.QSize).ToList <Resource>(), Employees = EmployeeCache.GetInstance().Employees }; }
/// <summary> /// Gets the ordered explicit authorization rules for an entity. The first rule in the list /// should be checked first, and so on. The order follows from the first explicit rule on the /// entity to the last explicit rule on the entity, then the first explicit rule on the parent /// entity to the last explicit rule on the parent entity and so on. /// </summary> /// <param name="entity">The entity.</param> /// <returns>A collection of explicit authorization rules in the proper order.</returns> private static List <string> GetOrderedExplicitAuthorizationRules(ISecured entity) { var explicitRules = new List <string>(); if (entity == null) { return(explicitRules); } // // Get the ancestor authorization rules. // var parentEntity = entity.ParentAuthority; if (parentEntity != null) { explicitRules = GetOrderedExplicitAuthorizationRules(parentEntity); } var authRules = Authorization.AuthRules(entity.TypeId, entity.Id, Authorization.VIEW); // // Walk each rule in descending order so that the final order is correct // since we insert rules at index 0. // foreach (var rule in authRules.OrderByDescending(a => a.Order)) { string entityIdentifier; if (rule.SpecialRole != SpecialRole.None) { entityIdentifier = $"S:{( int ) rule.SpecialRole}"; } else if (rule.GroupId.HasValue) { var role = RoleCache.Get(rule.GroupId.Value); if (role == null) { continue; } entityIdentifier = $"G:{role.Guid}"; } else if (rule.PersonId.HasValue) { /* Not currently supported, maybe in the future. -dsh */ continue; } else { continue; } explicitRules.Insert(0, $"{entityIdentifier}:{rule.AllowOrDeny}"); } return(explicitRules); }
/// <summary> /// 载入页面关联的按钮配置 /// </summary> /// <param name="loginUser">登录用户</param> /// <param name="page">页面,不能为空</param> /// <returns>按钮配置集合</returns> List <string> IPowerChecker.LoadPageButtons(ILoginUser loginUser, IPageItem page) { if (page == null) { return(new List <string>()); } return(BusinessContext.Current.IsSystemMode ? PageItemLogical.LoadPageButtons(page.Id) : RoleCache.LoadButtons(loginUser.RoleId, page.ID)); }
/// <summary> /// Binds the role dropdown list. /// </summary> /// <param name="rockDropdownList">The rock dropdown list.</param> private void BindRoleDropdownList(RockDropDownList rockDropdownList) { rockDropdownList.Items.Clear(); foreach (var role in RoleCache.AllRoles()) { string name = role.IsSecurityTypeGroup ? role.Name : "GROUP - " + role.Name; rockDropdownList.Items.Add(new ListItem(name, role.Id.ToString())); } }
public void Refresh() { EmployeeCache.GetInstance().Clear(); RoleCache.GetInstance().Clear(); Roles = new ObservableCollection <EmployeeRole>(RoleCache.GetInstance().Roles); Employees = new ObservableCollection <Employee>(EmployeeCache.GetInstance().Employees); ComboboxEmpRole.ItemsSource = Roles; ListViewEmployees.ItemsSource = Employees; ListViewEmployees.SelectedItem = GetFirstEmployee(); ComboboxEmpRole.SelectedItem = ((Employee)ListViewEmployees.SelectedItem).Role; }
private void SaveRole(EmployeeRole roleToSave) { if (roleToSave.Id > 0) { RoleCache.GetInstance().UpdateRole(roleToSave); } else { RoleCache.GetInstance().InsertRole(roleToSave); } Roles = new ObservableCollection <EmployeeRole>(RoleCache.GetInstance().Roles); }
/// <summary> /// 载入页面关联的按钮配置 /// </summary> /// <param name="loginUser">登录用户</param> /// <param name="page">页面</param> /// <param name="action">动作</param> /// <returns>是否可执行页面动作</returns> bool IPowerChecker.CanDoAction(ILoginUser loginUser, IPageItem page, string action) { if (BusinessContext.Current.IsSystemMode) { return(true); } if (defaults.ContainsKey(action)) { return(defaults[action]); } return(page != null && RoleCache.CanDoAction(loginUser.RoleId, page.Id, action)); }
/// <summary> /// 返回表示当前对象的字符串。 /// </summary> /// <returns> /// 表示当前对象的字符串。 /// </returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("姓名:"); sb.Append(Personnel.Personnel); sb.Append("<br/>部门:"); sb.Append(Personnel.Organization); sb.Append("<br/>职位:"); sb.Append(Personnel.Position); sb.Append("<br/>角色:"); sb.Append(RoleCache.GetRole(RoleId).Caption); return(sb.ToString()); }
/// <summary> /// Updates any Cache Objects that are associated with this entity /// </summary> /// <param name="entityState">State of the entity.</param> /// <param name="dbContext">The database context.</param> public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext) { var group = this.Group ?? new GroupService(new RockContext()).GetNoTracking(this.GroupId); if (group != null) { var groupType = GroupTypeCache.Get(group.GroupTypeId, (RockContext)dbContext); if (group.IsSecurityRole || groupType?.Guid == Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()) { RoleCache.FlushItem(group.Id); Rock.Security.Authorization.Clear(); } } }
/// <summary> /// Get the MobilePerson object for the specified Person. /// </summary> /// <param name="person">The person to be converted into a MobilePerson object.</param> /// <param name="site">The site to use for configuration data.</param> /// <returns>A MobilePerson object.</returns> public static MobilePerson GetMobilePerson(Person person, SiteCache site) { var baseUrl = GlobalAttributesCache.Value("PublicApplicationRoot"); var homePhoneTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Id; var mobilePhoneTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id; var alternateIdTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID).Id; var additionalSettings = site.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>(); if (person.Attributes == null) { person.LoadAttributes(); } var personAttributes = person.Attributes .Select(a => a.Value) .Where(a => a.Categories.Any(c => additionalSettings.PersonAttributeCategories.Contains(c.Id))); var roleGuids = RoleCache.AllRoles() .Where(r => r.IsPersonInRole(person.Guid)) .Select(r => r.Guid) .ToList(); var alternateId = person.GetPersonSearchKeys() .Where(a => a.SearchTypeValueId == alternateIdTypeId) .FirstOrDefault()?.SearchValue; return(new MobilePerson { FirstName = person.FirstName, NickName = person.NickName, LastName = person.LastName, Gender = (Rock.Common.Mobile.Enums.Gender)person.Gender, BirthDate = person.BirthDate, Email = person.Email, HomePhone = person.PhoneNumbers.Where(p => p.NumberTypeValueId == homePhoneTypeId).Select(p => p.NumberFormatted).FirstOrDefault(), MobilePhone = person.PhoneNumbers.Where(p => p.NumberTypeValueId == mobilePhoneTypeId).Select(p => p.NumberFormatted).FirstOrDefault(), HomeAddress = GetMobileAddress(person.GetHomeLocation()), CampusGuid = person.GetCampus()?.Guid, PersonAliasId = person.PrimaryAliasId.Value, PhotoUrl = (person.PhotoId.HasValue ? $"{baseUrl}{person.PhotoUrl}" : null), SecurityGroupGuids = roleGuids, PersonalizationSegmentGuids = new List <Guid>(), PersonGuid = person.Guid, PersonId = person.Id, AlternateId = alternateId, AttributeValues = GetMobileAttributeValues(person, personAttributes) }); }
/// <summary> /// Binds the roles. /// </summary> private void BindRoles() { ddlRoles.Items.Clear(); ddlRoles.Items.Add(new ListItem("[All Users]", "-1")); ddlRoles.Items.Add(new ListItem("[All Authenticated Users]", "-2")); ddlRoles.Items.Add(new ListItem("[All Un-Authenticated Users]", "-3")); var securityRoleType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()); foreach (var role in RoleCache.AllRoles()) { string name = role.IsSecurityTypeGroup ? role.Name : "GROUP - " + role.Name; ddlRoles.Items.Add(new ListItem(name, role.Id.ToString())); } }
/// <summary> /// Loads the role dropdown lists. /// </summary> private void LoadRoleDropdownLists() { RoleCache highRole = null; RoleCache extremeRole = null; _securitySettingsService.SecuritySettings.AccountProtectionProfileSecurityGroup.TryGetValue(AccountProtectionProfile.High, out highRole); _securitySettingsService.SecuritySettings.AccountProtectionProfileSecurityGroup.TryGetValue(AccountProtectionProfile.Extreme, out extremeRole); if (highRole != null) { ddlHighRoles.SelectedValue = highRole.Id.ToString(); } if (extremeRole != null) { ddlExtremeRoles.SelectedValue = extremeRole.Id.ToString(); } }
/// <summary> /// Returns a list of all the possible Roles /// </summary> /// <returns></returns> public static List <Role> AllRoles() { var roles = new List <Role>(); var cacheRoles = RoleCache.AllRoles(); if (cacheRoles == null) { return(roles); } foreach (var cacheRole in cacheRoles) { roles.Add(new Role(cacheRole)); } return(roles); }
/// <summary> /// Updates any Cache Objects that are associated with this entity /// </summary> /// <param name="entityState">State of the entity.</param> /// <param name="dbContext">The database context.</param> public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext) { // If the group changed, and it was a security group, flush the security for the group Guid?originalGroupTypeGuid = null; Guid groupTypeScheduleRole = Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid(); if (_originalGroupTypeId.HasValue && _originalGroupTypeId != this.GroupTypeId) { originalGroupTypeGuid = GroupTypeCache.Get(_originalGroupTypeId.Value, (RockContext)dbContext)?.Guid; } var groupTypeGuid = GroupTypeCache.Get(this.GroupTypeId, (RockContext)dbContext)?.Guid; if (this.IsSecurityRole || (_originalIsSecurityRole == true) || (groupTypeGuid == groupTypeScheduleRole) || (originalGroupTypeGuid == groupTypeScheduleRole)) { RoleCache.FlushItem(this.Id); } }
/// <summary> /// Initializes a new instance of the <see cref="SecuritySettingsService"/> class. /// </summary> public SecuritySettingsService() { _validationResults = new List <ValidationResult>(); var securitySettings = SystemSettings.GetValue(SYSTEM_SETTING_KEY).FromJsonOrNull <SecuritySettings>(); if (securitySettings == null) { securitySettings = GetDefaultSecuritySettings(); } else { var keys = securitySettings.AccountProtectionProfileSecurityGroup.Keys.ToList(); foreach (var key in keys) { var roleCache = securitySettings.AccountProtectionProfileSecurityGroup[key]; securitySettings.AccountProtectionProfileSecurityGroup[key] = RoleCache.Get(roleCache.Id); } } SecuritySettings = securitySettings; }
private void ProjectViewOpenProectClickHandler(ProjectsViewModel viewModel) { TextblockPanelName.Text = "Project Details"; RoleCache.GetInstance().Clear(); EmployeeCache.GetInstance().Clear(); ResourceCache.GetInstance().Clear(); CustomerCache.GetInstance().Clear(); ProcessCache.GetInstance().Clear(); ProjectCache.GetInstance().Clear(); var resources = ResourceCache.GetInstance().Resources; resources = ResourceCache.GetInstance().UpdateAllQSizes(); DataContext = new AddEditProjectViewModel { Project = viewModel.SelectedProject, BackClickedHandler = AddEditProjectViewBackClickHandler, Customers = CustomerCache.GetInstance().Customers, Processes = new ObservableCollection <Process>(viewModel.SelectedProject.Processes), Resources = resources.OrderByDescending(r => r.QSize).ToList <Resource>(), Employees = EmployeeCache.GetInstance().Employees }; }
/// <summary> /// Gets the default security settings. /// </summary> /// <returns></returns> private SecuritySettings GetDefaultSecuritySettings() { Group adminGroup = null; Group dataIntegrityGroup = null; using (var rockContext = new RockContext()) { var groupService = new GroupService(rockContext); adminGroup = groupService.GetByGuid(SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid()); dataIntegrityGroup = groupService.GetByGuid(SystemGuid.Group.GROUP_DATA_INTEGRITY_WORKER.AsGuid()); } var allRoles = RoleCache.AllRoles(); var adminRole = allRoles .Where(r => r.Guid == SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid()) .FirstOrDefault(); var dataIntegrityRole = allRoles .Where(r => r.Guid == SystemGuid.Group.GROUP_DATA_INTEGRITY_WORKER.AsGuid()) .FirstOrDefault(); return(new SecuritySettings { AccountProtectionProfilesForDuplicateDetectionToIgnore = new List <AccountProtectionProfile> { AccountProtectionProfile.Extreme, AccountProtectionProfile.High, AccountProtectionProfile.Medium }, AccountProtectionProfileSecurityGroup = new Dictionary <AccountProtectionProfile, RoleCache> { { AccountProtectionProfile.Extreme, adminRole }, { AccountProtectionProfile.High, dataIntegrityRole } }, DisableTokensForAccountProtectionProfiles = new List <AccountProtectionProfile> { AccountProtectionProfile.Extreme }, }); }
/// <summary> /// Gets the or add existing. /// </summary> /// <param name="key">The key.</param> /// <param name="valueFactory">The value factory.</param> /// <returns></returns> public static Role GetOrAddExisting(string key, Func <Role> valueFactory) { // This mehod should not have been public, but it was, so leaving it with just a get. return(new Role(RoleCache.Get(key.AsInteger()))); }
} // enum AreaName public GlobalAreaAuthorizationFilter(RoleCache roleCache, AreaName areaName, string roleName) { this.roleCache = roleCache; this.areaName = areaName; Roles = roleName; } // constructor
private void DeleteSelectedRole() { RoleCache.GetInstance().DeleteRole(ListViewRoles.SelectedItem as EmployeeRole); Roles = new ObservableCollection <EmployeeRole>(RoleCache.GetInstance().Roles); }
/// <summary> /// Returns all roles assigned to the passed user /// </summary> /// <param name="username"></param> /// <returns>Array of roles</returns> /// <remarks> /// <para> /// Roles assigned to roles are also properly handled /// </para> /// </remarks> public override string[] GetRolesForUser(string username) { if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentNullException("username"); } RoleCache cached; if (_userRoles.TryGetValue(username, out cached)) { // Found the roles in the cache. if (DateTime.Now - cached.TimeStamp > MAX_CACHE_DURATION) { // Cache is stale. Ignore it. _userRoles.TryRemove(username, out cached); } else { // Thankfully query is avoided return cached.Roles; } } if (string.Compare(_connectionStringBuilder.ProxyUserId, username, true) == 0) { return new[] { "WEB_PROXYUSER" }; } /* * TODO: Use this new query which uses recursive subquery syntax instead of CONNECT BY. This syntax was introduced in 11gR2 * Inspired by http://technology.amis.nl/blog/6104/oracle-rdbms-11gr2-goodbye-connect-by-or-the-end-of-hierarchical-querying-as-we-know-it */ const string QUERY_ALL_ROLES = @" WITH Q1(GRANTED_ROLE, PATH) AS (SELECT P.GRANTED_ROLE, CAST(U.USERNAME AS VARCHAR2(2000)) FROM DBA_ROLE_PRIVS P INNER JOIN DBA_USERS U ON P.GRANTEE = U.USERNAME UNION ALL SELECT P.GRANTED_ROLE, CAST(Q1.PATH || '/' || P.GRANTEE AS VARCHAR2(2000)) FROM DBA_ROLE_PRIVS P INNER JOIN Q1 ON Q1.GRANTED_ROLE = P.GRANTEE LEFT OUTER JOIN DBA_USERS U ON P.GRANTEE = U.USERNAME WHERE U.USERNAME IS NULL) SELECT DISTINCT Q.GRANTED_ROLE AS ROLES FROM Q1 Q WHERE (Q.PATH = :username OR Q.PATH LIKE :username || '/%') ORDER BY ROLES "; const string QUERY_PRIVILEGES = @" SELECT T.PRIV_ID AS PRIVS FROM <proxy />UPRIV T WHERE T.ORACLE_USER_NAME = :username ORDER BY PRIVS "; cached = new RoleCache { TimeStamp = DateTime.Now }; //var binder = new SqlBinder<string>("Querying Roles and privileges"); var binder = SqlBinder.Create(row => row.GetString(0)); binder.Parameter("username", username.ToUpper()); //binder.Query = QUERY_ALL_ROLES; //binder.Factory = row => row.GetString(); //binder.CreateMapper(QUERY_ALL_ROLES); using (var db = new OracleDatastore(HttpContext.Current.Trace)) { db.CreateConnection(_connectionStringBuilder.ConnectionString, string.Empty); IEnumerable<string> roles = db.ExecuteReader(QUERY_ALL_ROLES, binder); //binder.Query = QUERY_PRIVILEGES; IEnumerable<string> privs; try { privs = db.ExecuteReader(QUERY_PRIVILEGES, binder); } catch (OracleDataStoreException ex) { if (ex.OracleErrorNumber == 942) { // Table or view does not exist. Stay silent privs = Enumerable.Empty<string>(); } else { throw; } } cached.Roles = roles.Concat(privs).ToArray(); _userRoles.TryAdd(username, cached); return cached.Roles; } }
/// <summary> /// Removes role from cache /// </summary> /// <param name="id">The id.</param> public static void Flush(int id) { RoleCache.Remove(id); }
public object InsertTemporaryPeople([FromBody] JObject jObject) { var userService = new UserBLL(); try { string res = jObject.Value <string>("json"); var dy = JsonConvert.DeserializeAnonymousType(res, new { userid = string.Empty, data = new List <TemporaryPeopleParameter>() }); UserEntity createUser = userService.GetEntity(dy.userid);; if (createUser == null) { throw new Exception("你没有权限添加权限"); } List <UserEntity> successList = new List <UserEntity>(); //要新增到数据库里的数据 List <object> badList = new List <object>(); //有问题的数据 foreach (TemporaryPeopleParameter item in dy.data) { try { if (!string.IsNullOrWhiteSpace(item.Mobile) && !userService.ExistMoblie(item.Mobile)) { //校验手机号是否重复,重复该条数据不让添加 badList.Add(new { data = item, msg = "手机号重复" }); continue; } //如果账号存在则再生成一个,直到没有重复的为止 string pyStr = Str.PinYin(item.RealName); string account = pyStr; int count = 1; while (!userService.ExistAccount(account)) { account = pyStr + GetNumStr(count); count++; } UserEntity user = new UserEntity(); user.UserId = Guid.NewGuid().ToString(); user.RealName = item.RealName; user.IdentifyID = item.IdentifyID; user.Mobile = item.Mobile; user.Account = account; user.IdentifyID = item.IdentifyID; user.IsEpiboly = "1"; user.Gender = "男"; user.OrganizeId = createUser.OrganizeId; user.OrganizeCode = createUser.OrganizeCode; user.CreateUserOrgCode = createUser.OrganizeCode; user.CreateDate = DateTime.Now; user.CreateUserDeptCode = createUser.DepartmentCode; user.CreateUserId = createUser.UserId; user.CreateUserName = createUser.RealName; user.DepartmentId = createUser.DepartmentId; user.DepartmentCode = createUser.DepartmentCode; user.Password = "******";//默认密码123456 user.IsPresence = "1"; //岗位随机分配一个本班组下没有负责人角色的岗位 IEnumerable <RoleEntity> rlist = new JobBLL().GetList().Where(p => p.DeptId == createUser.DepartmentId && !p.RoleIds.Contains("27eb996b-1294-41d6-b8e6-837645a66819")); if (rlist != null && rlist.Count() > 0) { var defaultRole = rlist.FirstOrDefault(); user.DutyId = defaultRole.RoleId; user.DutyName = defaultRole.FullName; } // 职务:默认为编码管理中排序为最后一个的职务 var defaultJob = new JobBLL().GetList().Where(p => p.OrganizeId == createUser.OrganizeId).OrderByDescending(x => x.SortCode).FirstOrDefault(); if (defaultJob != null) { user.PostName = defaultJob.FullName; user.PostId = defaultJob.RoleId; user.PostCode = defaultJob.EnCode; } //角色,默认班组级用户 RoleEntity roleEntity = new RoleCache().GetList().Where(a => a.OrganizeId == createUser.OrganizeId || string.IsNullOrWhiteSpace(a.OrganizeId)).Where(p => p.FullName.Contains("班组级用户")).FirstOrDefault(); if (roleEntity != null) { user.RoleId = roleEntity.RoleId; } user.RoleName = roleEntity.FullName; roleEntity = new RoleCache().GetList().Where(a => a.OrganizeId == createUser.OrganizeId || string.IsNullOrWhiteSpace(a.OrganizeId)).Where(p => p.FullName.Contains("普通用户")).FirstOrDefault(); if (roleEntity != null) { if (!string.IsNullOrEmpty(roleEntity.RoleId)) { user.RoleId += "," + roleEntity.RoleId; user.RoleName += "," + roleEntity.FullName; } else { user.RoleId += roleEntity.RoleId; user.RoleName = roleEntity.FullName; } } string objId = userService.SaveForm(user.UserId, user, 0); if (!string.IsNullOrWhiteSpace(objId)) { //不为空则添加成功 successList.Add(user); if (!string.IsNullOrWhiteSpace(new DataItemDetailBLL().GetItemValue("bzAppUrl"))) { user.Password = "******"; var task = Task.Factory.StartNew(() => { SaveUser(user); }); } } else { badList.Add(new { data = item, msg = "添加失败" }); } } catch (Exception itemEx) { badList.Add(new { data = item, msg = itemEx.Message }); } } return(new { Code = 0, Info = "操作成功", data = successList.Select(p => new { p.RealName, p.Account, Password = "******" }) }); } catch (Exception ex) { return(new { Code = -1, info = "操作失败", data = ex.Message }); } }
/// <summary> /// Loads the by identifier. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public static Role LoadById(int id) { return(new Role(RoleCache.LoadById(id))); }
/// <summary> /// Returns Role object from cache. If role does not already exist in cache, it /// will be read and added to cache /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public static Role Read(int id) { return(new Role(RoleCache.Get(id))); }
/// <summary> /// Find the matching Auth record for this entity, action and person combination. Only explicit /// Auth records are checked. /// </summary> /// <param name="entity">The entity whose Auth records we are going to search for.</param> /// <param name="action">The type of action that is to be authenticated.</param> /// <param name="person">The person that is requesting permission.</param> /// <returns>An Auth object if an explicit permission was found, otherwise null.</returns> Auth MatchingAuth(ISecured entity, string action, Person person) { var rockContext = new RockContext(); var authService = new AuthService(rockContext); var rules = authService.Get(entity.TypeId, entity.Id).Where(a => a.Action == action).ToList(); bool matchFound = false; bool authorized = false; foreach (var authRule in rules) { // All Users if (authRule.SpecialRole == SpecialRole.AllUsers) { matchFound = true; authorized = authRule.AllowOrDeny == "A"; return(authRule); } // All Authenticated Users if (!matchFound && authRule.SpecialRole == SpecialRole.AllAuthenticatedUsers && person != null) { matchFound = true; authorized = authRule.AllowOrDeny == "A"; return(authRule); } // All Unauthenticated Users if (!matchFound && authRule.SpecialRole == SpecialRole.AllUnAuthenticatedUsers && person == null) { matchFound = true; authorized = authRule.AllowOrDeny == "A"; return(authRule); } if (!matchFound && authRule.SpecialRole == SpecialRole.None && person != null) { // See if person has been authorized to entity if (authRule.PersonAliasId.HasValue && person.Aliases.Where(a => a.Id == authRule.PersonAliasId.Value).Any()) { matchFound = true; authorized = authRule.AllowOrDeny == "A"; return(authRule); } // See if person is in role authorized if (!matchFound && authRule.GroupId.HasValue) { var role = RoleCache.Get(authRule.GroupId.Value); if (role != null && role.IsPersonInRole(person.Guid)) { matchFound = true; authorized = authRule.AllowOrDeny == "A"; return(authRule); } } } } return(null); }