private void LogEvent(IResource resource, IResourceRequest irr, ResourceAction action) { if (s_diagnostics) { _Debug.WriteLine(m_model.Executive.Now + " : Resource Tracker " + m_target.Name + " (" + m_target.Guid + ") logged " + action + " with " + irr.QuantityDesired + "."); } ResourceEventRecord rer = new ResourceEventRecord(m_model.Executive.Now, resource, irr, action); if (m_rerFilter == null || m_rerFilter(rer)) { m_record.Add(rer); if (s_diagnostics) { _Debug.WriteLine("\tLogged."); } } else { if (s_diagnostics) { _Debug.WriteLine("\tFiltered out."); } } }
private Resource ToModel(Persistance.Models.Resource resource) { var identifier = CRN.FromValue(resource.CanonicalName); var actions = resource.Actions.Select(a => ResourceAction.FromValue(a.Action.CanonicalName)).ToArray(); return(Resource.FromIdentifier(identifier).WithActions(actions)); }
// this method will see if the requesting user has permissions to take the action on the // specified resource private async Task <bool> CanManageResource(ScampResource resource, ResourceAction action) { ScampUser currentUser = await _securityHelper.GetOrCreateCurrentUser(); // System admin can do everything EXCEPT create a resource // to create a resource, you must be a group admin if (action != ResourceAction.Create && currentUser.IsSystemAdmin) { return(true); //Sysadmin can do everything } // Resource owner can also do anything to their resource except create var owner = resource.Owners.Find(user => user.Id == currentUser.Id); // if current user is in list of resource owners, allow action if (action != ResourceAction.Create && owner != null) { return(true); } // Resource's Group Managers can do anything to the resources in groups // they manage var rscGroup = currentUser.GroupMembership.Find(grp => grp.Id == resource.ResourceGroup.Id); // if current user is a manager of the group that owns the resource, allow action if (rscGroup != null && rscGroup.isManager) { return(true); } // if no positive results, default to false and deny action return(false); }
public IActionResult Get() { // somehow determine what the resource, action and schema are var resource = CRN.FromValue("crn:farm/1"); var action = ResourceAction.FromValue("iam:owner"); var schema = CSN.FromValue("csn:ag-data:farm"); // validate permissions var permissionsValid = this.ValidatePermissions(resource, action, schema); if (!permissionsValid) { return(Forbid()); } var rng = new Random(); return(Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray())); }
public async Task <IActionResult> Post(string groupId, string resourceId, string actionname, uint?duration = null) { ScampResource res = await _resourceRepository.GetResource(resourceId); if (res == null) { return(new HttpStatusCodeResult(404)); // not found } ResourceAction action = WebJobController.GetAction(actionname); ResourceState newState = ResourceState.Unknown; switch (action) { case ResourceAction.Start: newState = ResourceState.Starting; break; case ResourceAction.Stop: newState = ResourceState.Stopping; break; } if (await CanManageResource(res, action)) { await _volatileStorageController.UpdateResourceState(resourceId, newState); _webJobController.SubmitActionInQueue(resourceId, action, duration); } return(new HttpStatusCodeResult(204)); }
public static void DoWithScreenResources(IntPtr display, ResourceAction <ScreenResources> func) { foreach (ScreenResources res in ScreenResources(display)) { func(res); } }
public void DoWith(int id, ResourceAction <T> func) { IntPtr ptr = getF(id); func(Structure <T> (ptr)); freeF(ptr); }
public static IEnumerable <object[]> GetIncompatibleRoleDataForAction(ResourceAction action) { var testData = new List <object>(); testData.Add(GetClaimsPrincipalForRoles("role1", "role2")); testData.Add(GetAuthorizationConfigurationForRoles(new List <ResourceAction> { action }, "role3")); testData.Add(action); yield return(testData.ToArray()); testData.Add(GetClaimsPrincipalForRoles("role2")); testData.Add(GetAuthorizationConfigurationForRoles(new List <ResourceAction> { action, ResourceAction.Write }, "role6")); testData.Add(action); yield return(testData.TakeLast(3).ToArray()); testData.Add(GetClaimsPrincipalForRoles("role1", "role2")); testData.Add(GetAuthorizationConfigurationForRoles(new List <ResourceAction> { action, ResourceAction.HardDelete }, "role3", "role4")); testData.Add(action); yield return(testData.TakeLast(3).ToArray()); testData.Add(GetClaimsPrincipalForRoles("role3")); testData.Add(GetAuthorizationConfigurationForRoles(new List <ResourceAction> { action }, "role1", "role2", "role5")); testData.Add(action); yield return(testData.TakeLast(3).ToArray()); }
public static void DoWithDefaultDisplay(ResourceAction <IntPtr> func) { foreach (IntPtr display in DefaultDisplay()) { func(display); } }
private static List <ResourceAction> GetActionsFromRule(XacmlRule rule, List <RoleGrant> roles) { List <ResourceAction> actions = new List <ResourceAction>(); foreach (XacmlAnyOf anyOf in rule.Target.AnyOf) { foreach (XacmlAllOf allOf in anyOf.AllOf) { AttributeMatch actionAttributeMatch = new AttributeMatch(); foreach (XacmlMatch xacmlMatch in allOf.Matches) { if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Action)) { actionAttributeMatch.Id = xacmlMatch.AttributeDesignator.AttributeId.OriginalString; actionAttributeMatch.Value = xacmlMatch.AttributeValue.Value; ResourceAction resourceAction = new ResourceAction { Match = actionAttributeMatch, RoleGrants = new List <RoleGrant>(), Title = xacmlMatch.AttributeValue.Value }; resourceAction.RoleGrants.AddRange(roles); if (!actions.Contains(resourceAction)) { actions.Add(resourceAction); } } } } } return(actions); }
public void TestDisplayResourceUsage() { FillTestData("TestFormsData.xml", "TestResourcesData.xml"); ChooseWithGridForm.UnitTestMode = true; ResourceAction ret = DesktopResourceUsage.DisplayResourceUsage("form 1", "View №1 of form №1", "resFile1", "resource №1", "resource №1", "TestFormsData.xml", "TestResourcesData.xml"); Assert.AreEqual(ResourceAction.Split, ret); }
private void LogEvent(IResource resource, IResourceRequest irr, ResourceAction action) { ResourceEventRecord rer = new ResourceEventRecord(m_model.Executive.Now, resource, irr, action); if (m_rerFilter != null && m_rerFilter(rer)) { m_record.Add(rer); } }
public ValidationResult <ResourceAction> ValidateAction(ResourceAction action) { var found = this.storage.AllActions().FirstOrDefault(a => a == action); if (found != default(ResourceAction)) { return(ValidationResult <ResourceAction> .Valid(action)); } return(ValidationResult <ResourceAction> .Invalid(action, ActionNotFound)); }
private PermissionGrant ToModel(Persistance.Models.PermissionGrant entity) { return(new PermissionGrant() { Id = entity.PermissionGrantId, Principal = CPN.FromValue(entity.Principal.CanonicalName), Schema = CSN.FromValue(entity.Schema.CanonicalName), Actions = entity.Actions.Select(a => ResourceAction.FromValue(a.Action.CanonicalName)).ToList(), Resource = entity.Resources.Select(r => CRN.FromValue(r.Resource.CanonicalName)).ToList() }); }
public void SubmitActionInQueue(string resourceId, string actionname, uint?duration = null) { ResourceAction action = GetAction(actionname); if (action == ResourceAction.Undefined) { throw new Exception("Action not defined"); } this.SubmitActionInQueue(resourceId, action, duration); }
private static void AssertResourceActionEqual(ResourceAction expected, ResourceAction actual) { Assert.Equal(expected.Title, actual.Title); AssertAttributeMatchEqual(expected.Match, actual.Match); AssertCollections(expected.RoleGrants, actual.RoleGrants, AssertRoleGrantEqual); if (expected.Description != null && actual.Description != null) { Assert.Equal(expected.Description, actual.Description); } }
public bool HasPermission(ClaimsPrincipal user, ResourceAction action) { EnsureArg.IsNotNull(user, nameof(user)); IEnumerable <ResourceAction> actions = GetRolesAndActions(user); if (actions == null) { return(false); } return(actions.Contains(action)); }
/* public static NdEffect LoadEffect(string path, string name, Vector3 EffectPos,Transform Parent ) * { * GameObject go = GameObjectLoader.LoadPath(path, name) as GameObject; * if(go != null) * { * go.transform.parent = Parent; * go.transform.position = EffectPos; * NdEffect effect = go.AddComponent<NdEffect>(); * return effect; * } * return null; * }*/ /// <summary> /// 加载特效 /// </summary> /// <param name="path">特效路径</param> /// <param name="name">特效名称</param> /// <param name="pos">特效加载相对位置</param> /// <param name="Parent">特效挂载点</param> public static ResourceAction LoadResouceEffect(string path, string name, Vector3 EffectPos, Transform Parent) { GameObject go = GameObjectLoader.LoadPath(path, name, Parent) as GameObject; if (go != null) { go.transform.position = EffectPos; ResourceAction effect = go.AddComponent <ResourceAction>(); return(effect); } return(null); }
public void AddAction(ResourceAction action) { var toAdd = new Persistance.Models.Action() { Category = action.Category, Name = action.Action, CanonicalName = action.ToString() }; this.context.Add(toAdd); this.context.SaveChanges(); }
public void AllActionsValidForResources(CRN resource, ResourceAction action) { // Arrange var storage = new MockResourceStorage().Setup(); var resourceValidator = new ResourceValidator(storage); // Act var result = resourceValidator.Validate(resource, action); // Assert result.IsValid.Should().BeTrue(); }
public override Resource ReadJson(JsonReader reader, Type objectType, Resource existingValue, bool hasExistingValue, JsonSerializer serializer) { var token = JToken.Load(reader); if (token.Type == JTokenType.Object) { CRN identifier = null; ResourceAction[] actions = null; foreach (var t in token.Children()) { if (t.Path == "identifier") { identifier = CRN.FromValue(t.First.Value <string>()); continue; } if (t.Path == "action") { var values = t.Values(); actions = values.Select(v => ResourceAction.FromValue(v.Value <string>())).ToArray(); continue; } } if (actions != null) { return(Resource.FromIdentifier(identifier).WithActions(actions)); } return(Resource.FromIdentifier(identifier)); } if (token.Type == JTokenType.String) { var value = serializer.Deserialize <CRN>(token.CreateReader()); return(Resource.FromIdentifier(value)); } try { if (token.Value <CRN>() == default) { return(null); } var value = serializer.Deserialize <CRN>(reader); return(Resource.FromIdentifier(value)); } catch { return(null); } }
public IActionResult Post([FromBody] ResourceAction resource) { var toAdd = new Persistance.Models.Action() { Category = resource.Category, Name = resource.Action, CanonicalName = resource.ToString() }; this.context.Actions.Add(toAdd); this.context.SaveChanges(); return(Ok(resource)); }
/// <summary> /// Calls ClaimsAuthorizationManager. /// </summary> /// <param name="action">The action.</param> /// <param name="resource">The resource.</param> /// <param name="additionalResources">Additional resources.</param> /// <returns>True when access is granted. Otherwise false.</returns> public static bool CheckAccess(string action, string resource, params Claim[] additionalResources) { var resourceAction = new ResourceAction( ResourceType, resource, ActionType, action); var context = CreateAuthorizationContext(ClaimsPrincipal.Current, resourceAction); additionalResources.ToList().ForEach(claim => context.Resource.Add(claim)); var claimsAuthorizationManager = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthorizationManager; return claimsAuthorizationManager.CheckAccess(context); }
public IActionResult Delete(string resource) { var actionName = ResourceAction.FromValue(HttpUtility.UrlDecode(resource)); var found = this.context.Actions.FirstOrDefault(a => a.CanonicalName == actionName); if (found == null) { return(NotFound()); } this.context.Actions.Remove(found); return(Ok(resource)); }
static Division() { var standardActions = new ResourceAction[] { ResourceAction.CreateVoucher, ResourceAction.CancelVoucher, ResourceAction.SubmitVoucher, ResourceAction.ReadVoucher, ResourceAction.CreateLoadCarrierReceipt, ResourceAction.CancelLoadCarrierReceipt, ResourceAction.ReadLoadCarrierReceipt, ResourceAction.CreateOrder, ResourceAction.UpdateOrder, ResourceAction.CancelOrder, ResourceAction.ReadOrder, ResourceAction.CreateBalanceTransfer, ResourceAction.ReadBalanceTransfer, ResourceAction.CancelBalanceTransfer, ResourceAction.CancelOrderLoad, ResourceAction.ReadOrderLoad, ResourceAction.CancelOrderLoad, ResourceAction.ReadOrderLoad, ResourceAction.ReadAccountingRecords, ResourceAction.CreateLivePoolingSearch, ResourceAction.ReadLivePoolingOrders, ResourceAction.CreateSorting, }; Standard = standardActions; var adminActions = new ResourceAction[] { ResourceAction.Create, ResourceAction.Update, ResourceAction.Delete, ResourceAction.Read, }.Concat(standardActions).Distinct().ToArray(); Admin = adminActions; }
/// <summary> /// Constructs a record of a resource transaction. /// </summary> /// <param name="when">The time (model time) that the transaction took place.</param> /// <param name="resourceGuid">The GUID of the resource against which this transaction took place.</param> /// <param name="desired">The quantity that was desired of the specified resource.</param> /// <param name="obtained">The quantity that was obtained of the specified resource.</param> /// <param name="capacity">The capacity of the specified resource after this transaction took place.</param> /// <param name="available">The amount available of the specified resource after this transaction took place.</param> /// <param name="requesterGuid">The GUID of the requester.</param> /// <param name="action">The type of <see cref="Highpoint.Sage.Resources.ResourceAction"/> that took place.</param> public ResourceEventRecord(DateTime when, Guid resourceGuid, double desired, double obtained, double capacity, double available, Guid requesterGuid, ResourceAction action) { When = when; m_resource = null; ResourceGuid = resourceGuid; m_quantityDesired = desired; m_quantityObtained = obtained; m_capacity = capacity; Available = available; Requester = null; RequesterGuid = requesterGuid; Action = action; m_tag = null; m_tagGuid = Guid.Empty; SerialNumber = Utility.SerialNumberService.GetNext(); }
/// <summary> /// Constructs a record of a resource transaction. /// </summary> /// <param name="when">The time (model time) that the transaction took place.</param> /// <param name="resource">The resource against which this transaction took place.</param> /// <param name="irr">The resource request that initiated this transaction.</param> /// <param name="action">The type of <see cref="Highpoint.Sage.Resources.ResourceAction"/> that took place.</param> public ResourceEventRecord(DateTime when, IResource resource, IResourceRequest irr, ResourceAction action) { m_resource = resource; ResourceGuid = resource.Guid; When = when; m_quantityDesired = irr.QuantityDesired; m_quantityObtained = irr.QuantityObtained; m_capacity = resource.Capacity; Available = resource.Available; Requester = irr.Requester; RequesterGuid = irr.Requester?.Guid ?? Guid.Empty; Action = action; m_tag = null; m_tagGuid = Guid.Empty; SerialNumber = Utility.SerialNumberService.GetNext(); }
/// <summary> /// Calls ClaimsAuthorizationManager. /// </summary> /// <param name="action">The action.</param> /// <param name="resource">The resource.</param> /// <param name="additionalResources">Additional resources.</param> /// <returns>True when access is granted. Otherwise false.</returns> public static bool CheckAccess(string action, string resource, params Claim[] additionalResources) { var resourceAction = new ResourceAction( ResourceType, resource, ActionType, action); var context = CreateAuthorizationContext(Thread.CurrentPrincipal.AsClaimsPrincipal(), resourceAction); additionalResources.ToList().ForEach(claim => context.Resource.Add(claim)); var claimsAuthorizationManager = IdentityModelConfiguration.ServiceConfiguration.ClaimsAuthorizationManager; return(claimsAuthorizationManager.CheckAccess(context)); }
public void AddOrUpdateAction(ResourceAction action) { var entity = _resourceActionRepository.GetByID(action.Id); if (entity != null) { _resourceActionRepository.Detach(entity); _resourceActionRepository.Update(action); } else { _resourceActionRepository.Insert(action); } _resourceActionRepository.Save(); }
public static bool ValidatePermissions <T>( this T controller, CRN resource, ResourceAction action, CSN schema) where T : ControllerBase { var principal = controller.User; // parse out resources var resourceClaims = principal.Claims.Where(c => c.Type.StartsWith("resource")); var resourcesAllowed = resourceClaims.Select(c => { var base64 = c.Value; var json = base64.FromBase64Encoded(); return(JsonConvert.DeserializeObject <PermissionTicketResource>(json)); }); // find resources matching schema var forSchema = resourcesAllowed.Where(r => r.Schema == schema).ToList(); if (!forSchema.Any()) { return(false); } // find resources matching either wildcard or direct match var matching = forSchema.Where(r => { if (resource.IncludesWildcard) { return(resource.IsWildcardMatch(r.Identifier)); } return(resource == r.Identifier); }).ToList(); if (!matching.Any()) { return(false); } // find resources matching required action var withAction = matching.Where(r => r.Actions.Contains(action)); return(withAction.Any()); }
public static string GetResourcesPath(Object target, ResourceAction action = ResourceAction.None, string path ="" ) { if (target == null) return string.Empty; string resourcePath = AssetDatabase.GetAssetPath(target); if(resourcePath.Contains(assetPath)) { resourcePath = resourcePath.Replace(assetPath, string.Empty); resourcePath = resourcePath.Replace(Path.GetExtension(resourcePath), string.Empty); return resourcePath; } //Debug.LogError(target.name + " Not found in resources, please move the object into your Assets/Resources folder"); return string.Empty; string validation = ""; switch (action) { case ResourceAction.None: //Debug.LogWarning(target.name + " Does not exist in resource databse"); return string.Empty; case ResourceAction.CopyToResources: validation = AssetDatabase.ValidateMoveAsset(resourcePath, assetPath + path); if (validation == string.Empty) { AssetDatabase.CopyAsset(resourcePath, assetPath + path); return path; } //Debug.LogError(validation); break; case ResourceAction.MoveToResources: validation = AssetDatabase.ValidateMoveAsset(resourcePath, assetPath + path); if(validation == string.Empty) { AssetDatabase.CopyAsset(resourcePath, assetPath + path); return path; } //Debug.LogError(validation); break; } return string.Empty; }
private static AuthorizationContext CreateAuthorizationContext(ClaimsPrincipal currentPrincipal, ResourceAction resourceAction) { var resourceClaim = new Claim(resourceAction.ResourceType, resourceAction.Resource); var actionClaim = new Claim(resourceAction.ActionType, resourceAction.Action); return new AuthorizationContext( currentPrincipal, new Collection<Claim> { resourceClaim }, new Collection<Claim> { actionClaim }); }
/// <summary> /// Calls ClaimsAuthorizationManager. /// </summary> /// <param name="action">The action.</param> /// <param name="resource">The resource.</param> /// <param name="additionalResources">Additional resources.</param> /// <returns>True when access is granted. Otherwise false.</returns> public static bool CheckAccess(string action, string resource, params Claim[] additionalResources) { var resourceAction = new ResourceAction( ResourceType, resource, ActionType, action); var context = CreateAuthorizationContext(Thread.CurrentPrincipal as ClaimsPrincipal, resourceAction); additionalResources.ToList().ForEach(claim => context.Resource.Add(claim)); var claimsAuthorizationManager = FederatedAuthentication.ServiceConfiguration.ClaimsAuthorizationManager; return claimsAuthorizationManager.CheckAccess(context); }
// this method will see if the requesting user has permissions to take the action on the // specified resource private async Task<bool> CanManageResource(ScampResource resource, ResourceAction action) { ScampUser currentUser = await _securityHelper.GetOrCreateCurrentUser(); // System admin can do everything EXCEPT create a resource // to create a resource, you must be a group admin if (action != ResourceAction.Create && currentUser.IsSystemAdmin) return true; //Sysadmin can do everything // Resource owner can also do anything to their resource except create var owner = resource.Owners.Find(user => user.Id == currentUser.Id); // if current user is in list of resource owners, allow action if (action != ResourceAction.Create && owner != null) return true; // Resource's Group Managers can do anything to the resources in groups // they manage var rscGroup = currentUser.GroupMembership.Find(grp => grp.Id == resource.ResourceGroup.Id); // if current user is a manager of the group that owns the resource, allow action if (rscGroup != null && rscGroup.isManager) return true; // if no positive results, default to false and deny action return false; }