コード例 #1
0
ファイル: MixinInjectNode.cs プロジェクト: mirannda/Jade4Net
        private void writeVariables(JadeModel model, MixinNode mixin, JadeTemplate template)
        {
            List <String> names  = mixin.getArguments();
            List <String> values = arguments;

            if (names == null)
            {
                return;
            }
            for (int i = 0; i < names.Count; i++)
            {
                String key   = names[i];
                Object value = null;
                if (i < values.Count)
                {
                    value = values[i];
                }
                if (value != null)
                {
                    try
                    {
                        value = ExpressionHandler.evaluateExpression(values[i], model);
                    }
                    catch (Exception e)
                    {
                        throw new JadeCompilerException(this, template.getTemplateLoader(), e);
                    }
                }
                if (key != null)
                {
                    model.put(key, value);
                }
            }
        }
コード例 #2
0
ファイル: ExpressionNode.cs プロジェクト: mirannda/Jade4Net
        public override void execute(IndentWriter writer, JadeModel model, JadeTemplate template) //throws JadeCompilerException
        {
            try
            {
                Object result = ExpressionHandler.evaluateStringExpression(getValue(), model);
                if (result == null || !buffer)
                {
                    return;
                }
                String str = result.ToString();
                if (escape)
                {
                    str = Utils.escapeHTML(str);
                }
                writer.append(str);

                if (hasBlock())
                {
                    writer.increment();
                    block.execute(writer, model, template);
                    writer.decrement();
                    writer.newline();
                }
            }
            catch (ExpressionException e)
            {
                throw new JadeCompilerException(this, template.getTemplateLoader(), e);
            }
        }
コード例 #3
0
ファイル: Utils.cs プロジェクト: mirannda/Jade4Net
        public static string interpolate(List <Object> prepared, JadeModel model)
        {
            StringBuilder result = new StringBuilder();

            foreach (Object entry in prepared)
            {
                if (entry is String)
                {
                    result.Append(entry);
                }
                else if (entry is ExpressionString)
                {
                    ExpressionString expression  = (ExpressionString)entry;
                    string           stringValue = "";
                    string           value       = ExpressionHandler.evaluateStringExpression(expression.getValue(), model);
                    if (value != null)
                    {
                        stringValue = value;
                    }
                    if (expression.isEscape())
                    {
                        stringValue = escapeHTML(stringValue);
                    }
                    result.Append(stringValue);
                }
            }

            return(result.ToString());
        }
コード例 #4
0
        /// <summary>
        /// Removes rules based on field filters from the current policy.
        /// </summary>
        /// <param name="sec"></param>
        /// <param name="ptype"></param>
        /// <param name="fieldIndex"></param>
        /// <param name="fieldValues"></param>
        /// <returns></returns>
        protected async Task <bool> InternalRemoveFilteredPolicyAsync(string sec, string ptype, int fieldIndex, params string[] fieldValues)
        {
            if (adapter is not null && autoSave)
            {
                try
                {
                    await adapter.RemoveFilteredPolicyAsync(sec, ptype, fieldIndex, fieldValues);
                }
                catch (NotImplementedException)
                {
                    // error intentionally ignored
                }
            }

            bool ruleRemoved = model.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues);

            if (ruleRemoved is false)
            {
                return(false);
            }

            if (sec.Equals(PermConstants.Section.RoleSection))
            {
                BuildRoleLinks();
                ExpressionHandler.SetGFunctions();
            }

            await NotifyPolicyChangedAsync();

            return(true);
        }
コード例 #5
0
        /// <summary>
        /// Maps the given generic eventtype to the expressed handler.
        /// </summary>
        /// <typeparam name="T">This should always be a <see cref="ISourcedEvent"/>.</typeparam>
        /// <returns>An <see cref="ExpressionHandler{T}"/>which allows us to define the mapping to a handler.</returns>
        protected ExpressionHandler <T> Map <T>() where T : ISourcedEvent
        {
            var handler = new ExpressionHandler <T>();

            _mappinghandlers.Add(handler);

            return(handler);
        }
コード例 #6
0
 public void setCaching(bool cache)
 {
     if (cache != this.caching)
     {
         ExpressionHandler.setCache(cache);
         this.caching = cache;
     }
 }
コード例 #7
0
        /// <summary>
        /// Maps the given generic eventtype to the expressed handler.
        /// </summary>
        /// <typeparam name="T">This should always be a <see cref="ISourcedEvent"/>.</typeparam>
        /// <returns>An <see cref="ExpressionHandler{T}"/>which allows us to define the mapping to a handler.</returns>
        protected ExpressionHandler <T> Map <T>()
        {
            var handler = new ExpressionHandler <T>();

            _mappinghandlers.Add(handler);

            return(handler);
        }
コード例 #8
0
ファイル: ExpressionMutator.cs プロジェクト: radtek/vita
        static void AddHandler <T>(Func <T, IList <Expression> > getter, Func <T, IList <Expression>, T> mutator) where T : Expression
        {
            var handler = new ExpressionHandler()
            {
                OperandGetter = e => getter((T)e),
                Mutator       = (e, ops) => mutator((T)e, ops)
            };

            _handlers.Add(typeof(T), handler);
        }
コード例 #9
0
        public static void ObjectNotNull(Expression <Func <object> > propertyExpression)
        {
            var func = propertyExpression.Compile();
            var obj  = func();

            if (obj == null)
            {
                var propertyName = ExpressionHandler.GetPropertyName(propertyExpression);
                throw new ArgumentException($"Object {propertyName} must not be null.");
            }
        }
コード例 #10
0
        public static void StringNotNullorEmpty(Expression <Func <string> > propertyExpression)
        {
            var func        = propertyExpression.Compile();
            var stringValue = func();

            if (string.IsNullOrEmpty(stringValue))
            {
                var propertyName = ExpressionHandler.GetPropertyName(propertyExpression);
                throw new ArgumentException($"String {propertyName} must not be null or empty.");
            }
        }
コード例 #11
0
ファイル: TagNode.cs プロジェクト: mirannda/Jade4Net
        private Object evaluateExpression(ExpressionString attribute, JadeModel model) //throws ExpressionException
        {
            String expression = ((ExpressionString)attribute).getValue();
            Object result     = ExpressionHandler.evaluateExpression(expression, model);

            if (result is ExpressionString)
            {
                return(evaluateExpression((ExpressionString)result, model));
            }
            return(result);
        }
コード例 #12
0
        /// <summary>
        /// Sets the current model.
        /// </summary>
        /// <param name="model"></param>
        public void SetModel(Model.Model model)
        {
            this.model        = model;
            ExpressionHandler = new ExpressionHandler(model);
            if (autoCleanEnforceCache)
            {
                EnforceCache?.Clear();
#if !NET45
                Logger?.LogInformation("Enforcer Cache, Cleared all enforce cache.");
#endif
            }
        }
コード例 #13
0
        private void NoticePolicyChanged(string section)
        {
            if (autoBuildRoleLinks && section.Equals(PermConstants.Section.RoleSection))
            {
                BuildRoleLinks();
                ExpressionHandler.SetGFunctions();
            }

            if (autoNotifyWatcher)
            {
                watcher?.Update();
            }
        }
コード例 #14
0
        private async Task NoticePolicyChangedAsync(string section)
        {
            if (autoBuildRoleLinks && section.Equals(PermConstants.Section.RoleSection))
            {
                BuildRoleLinks();
                ExpressionHandler.SetGFunctions();
            }

            if (autoNotifyWatcher && watcher is not null)
            {
                await watcher.UpdateAsync();
            }
        }
コード例 #15
0
        public static void ObjectNotNull(Expression <Func <object> > propertyExpression)
        {
            var func = propertyExpression.Compile();
            var obj  = func();

            if (obj != null)
            {
                return;
            }

            var propertyName     = ExpressionHandler.GetPropertyName(propertyExpression);
            var exceptionMessage = string.Format(NullObjectExceptionMessage, propertyName);

            throw new ArgumentException(exceptionMessage);
        }
コード例 #16
0
        public static void StringNotNullOrEmpty(Expression <Func <string> > propertyExpression)
        {
            var func        = propertyExpression.Compile();
            var stringValue = func();

            if (!string.IsNullOrEmpty(stringValue))
            {
                return;
            }

            var propertyName     = ExpressionHandler.GetPropertyName(propertyExpression);
            var exceptionMessage = string.Format(StringNullOrEmptyExceptionMessage, propertyName);

            throw new ArgumentException(exceptionMessage);
        }
コード例 #17
0
        public override void execute(IndentWriter writer, JadeModel model, JadeTemplate template)
        //throws JadeCompilerException
        {
            Object result;

            try
            {
                result = ExpressionHandler.evaluateExpression(value, model);
            }
            catch (ExpressionException e)
            {
                throw new JadeCompilerException(this, template.getTemplateLoader(), e);
            }
            model.put(name, result);
        }
コード例 #18
0
 public override void execute(IndentWriter writer, JadeModel model, JadeTemplate template)
 //throws JadeCompilerException
 {
     try
     {
         model.pushScope();
         while (ExpressionHandler.evaluateBooleanExpression(value, model).Value)
         {
             block.execute(writer, model, template);
         }
         model.popScope();
     }
     catch (ExpressionException e)
     {
         throw new JadeCompilerException(this, template.getTemplateLoader(), e);
     }
 }
コード例 #19
0
        private bool TryHandler(string match, ExpressionHandler handler, ref string expression, out object result)
        {
            int len;

            if (!MatchExpression(match, expression, out len))
            {
                result = null;
                return(false);
            }

            expression = expression.Substring(len).TrimStart();
            if (expression.Length == 0)
            {
                throw new Exception("Expression did not end in '}'");
            }
            result = handler(ref expression);
            return(true);
        }
コード例 #20
0
        public override void execute(IndentWriter writer, JadeModel model, JadeTemplate template)
        //throws JadeCompilerException
        {
            Object result;

            try
            {
                result = ExpressionHandler.evaluateExpression(getCode(), model);
            }
            catch (ExpressionException e)
            {
                throw new JadeCompilerException(this, template.getTemplateLoader(), e);
            }
            if (result == null)
            {
                throw new JadeCompilerException(this, template.getTemplateLoader(), "[" + code + "] has to be iterable but was null");
            }
            model.pushScope();
            run(writer, model, result, template);
            model.popScope();
        }
コード例 #21
0
        /// <summary>
        /// Removes rules from the current policy.
        /// </summary>
        /// <param name="sec"></param>
        /// <param name="ptype"></param>
        /// <param name="rules"></param>
        /// <returns></returns>
        protected async Task <bool> InternalRemovePoliciesAsync(string sec, string ptype, IEnumerable <List <string> > rules)
        {
            var ruleArray = rules as List <string>[] ?? rules.ToArray();

            if (model.HasPolicies(sec, ptype, ruleArray) is false)
            {
                return(false);
            }

            if (adapter is not null && autoSave)
            {
                try
                {
                    await adapter.RemovePoliciesAsync(sec, ptype, ruleArray);
                }
                catch (NotImplementedException)
                {
                    // error intentionally ignored
                }
            }

            bool ruleRemoved = model.RemovePolicies(sec, ptype, ruleArray);

            if (ruleRemoved is false)
            {
                return(false);
            }

            if (sec.Equals(PermConstants.Section.RoleSection))
            {
                model.BuildIncrementalRoleLinks(roleManager, PolicyOperation.PolicyRemove,
                                                sec, ptype, ruleArray);
                ExpressionHandler.SetGFunctions();
            }

            await NotifyPolicyChangedAsync();

            return(true);
        }
コード例 #22
0
        /// <summary>
        /// Adds rules to the current policy.
        /// </summary>
        /// <param name="sec"></param>
        /// <param name="ptype"></param>
        /// <param name="rules"></param>
        /// <returns></returns>
        protected bool InternalAddPolicies(string sec, string ptype, IEnumerable <List <string> > rules)
        {
            var ruleArray = rules as List <string>[] ?? rules.ToArray();

            if (model.HasPolicies(sec, ptype, ruleArray))
            {
                return(false);
            }

            if (adapter is not null && autoSave)
            {
                try
                {
                    adapter.AddPolicies(sec, ptype, ruleArray);
                }
                catch (NotImplementedException)
                {
                    // error intentionally ignored
                }
            }

            bool ruleAdded = model.AddPolicies(sec, ptype, ruleArray);

            if (ruleAdded is false)
            {
                return(false);
            }

            if (sec.Equals(PermConstants.Section.RoleSection))
            {
                model.BuildIncrementalRoleLinks(PolicyOperation.PolicyAdd,
                                                sec, ptype, ruleArray);
                ExpressionHandler.SetGFunctions();
            }

            NotifyPolicyChanged();
            return(true);
        }
コード例 #23
0
        /// <summary>
        /// Adds a rule to the current policy.
        /// </summary>
        /// <param name="sec"></param>
        /// <param name="ptype"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        protected async Task <bool> InternalAddPolicyAsync(string sec, string ptype, List <string> rule)
        {
            if (model.HasPolicy(sec, ptype, rule))
            {
                return(false);
            }

            if (adapter is not null && autoSave)
            {
                try
                {
                    await adapter.AddPolicyAsync(sec, ptype, rule);
                }
                catch (NotImplementedException)
                {
                    // error intentionally ignored
                }
            }

            bool ruleAdded = model.AddPolicy(sec, ptype, rule);

            if (ruleAdded is false)
            {
                return(false);
            }

            if (sec.Equals(PermConstants.Section.RoleSection))
            {
                model.BuildIncrementalRoleLink(roleManager, PolicyOperation.PolicyAdd,
                                               sec, ptype, rule);
                ExpressionHandler.SetGFunctions();
            }

            await NotifyPolicyChangedAsync();

            return(true);
        }
コード例 #24
0
ファイル: Variable.cs プロジェクト: Spectere/ThreadsLegacy
        public override void Activate()
        {
            var data   = Engine.Story.Data;
            var oldVar = data.GetVariable(Name);
            var eval   = ExpressionHandler.EvaluateNumeric(Expression, data);

            switch (Operation)
            {
            case VariableAction.Set:
                data.SetVariable(Name, eval);
                break;

            case VariableAction.Add:
                data.SetVariable(Name, oldVar + eval);
                break;

            case VariableAction.Subtract:
                data.SetVariable(Name, oldVar - eval);
                break;

            case VariableAction.Multiply:
                data.SetVariable(Name, oldVar * eval);
                break;

            case VariableAction.Divide:
                data.SetVariable(Name, oldVar / eval);
                break;

            case VariableAction.Modulus:
                data.SetVariable(Name, oldVar % eval);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #25
0
        /// <summary>
        /// Removes a rule from the current policy.
        /// </summary>
        /// <param name="sec"></param>
        /// <param name="ptype"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        protected bool InternalRemovePolicy(string sec, string ptype, List <string> rule)
        {
            if (model.HasPolicy(sec, ptype, rule) is false)
            {
                return(false);
            }

            if (adapter is not null && autoSave)
            {
                try
                {
                    adapter.RemovePolicy(sec, ptype, rule);
                }
                catch (NotImplementedException)
                {
                    // error intentionally ignored
                }
            }

            bool ruleRemoved = model.RemovePolicy(sec, ptype, rule);

            if (ruleRemoved is false)
            {
                return(false);
            }

            if (sec.Equals(PermConstants.Section.RoleSection))
            {
                model.BuildIncrementalRoleLink(PolicyOperation.PolicyRemove,
                                               sec, ptype, rule);
                ExpressionHandler.SetGFunctions();
            }

            NotifyPolicyChanged();
            return(true);
        }
コード例 #26
0
 public static void RegisterExpressionHandler <T>(string keyword, ExpressionHandler <T> handler) where T : IComparable
 {
     _exprHandlers[keyword] = (expression, args, quiet) => handler(expression, args, quiet);
 }
コード例 #27
0
 /// <summary>
 /// Adds a customized function.
 /// </summary>
 /// <param name="name">The name of the new function.</param>
 /// <param name="function">The function.</param>
 public void AddFunction(string name, Delegate function)
 {
     ExpressionHandler.SetFunction(name, function);
 }
コード例 #28
0
 public void clearCache()
 {
     ExpressionHandler.clearCache();
     cache.Clear();
 }
コード例 #29
0
        private bool TryHandler(string match, ExpressionHandler handler, ref string expression, out object result)
        {
            int len;
            if (!MatchExpression(match, expression, out len))
            {
                result = null;
                return false;
            }

            expression = expression.Substring(len).TrimStart();
            if (expression.Length == 0)
                throw new Exception("Expression did not end in '}'");
            result = handler(ref expression);
            return true;
        }
コード例 #30
0
 /// <summary>
 /// Adds a customized function.
 /// </summary>
 /// <param name="name">The name of the new function.</param>
 /// <param name="function">The function.</param>
 public void AddFunction(string name, AbstractFunction function)
 {
     ExpressionHandler.SetFunction(name, function);
 }
コード例 #31
0
        /// <summary>
        /// Decides whether a "subject" can access a "object" with the operation
        /// "action", input parameters are usually: (sub, obj, act).
        /// </summary>
        /// <param name="explains"></param>
        /// <param name="requestValues">The request needs to be mediated, usually an array of strings,
        /// can be class instances if ABAC is used.</param>
        /// <returns>Whether to allow the request.</returns>
        private bool Enforce(IReadOnlyList <object> requestValues, ICollection <IEnumerable <string> > explains = null)
        {
            if (_enabled is false)
            {
                return(true);
            }

            bool   explain          = explains is not null;
            string effect           = model.Model[PermConstants.Section.PolicyEffectSection][PermConstants.DefaultPolicyEffectType].Value;
            var    policyList       = model.Model[PermConstants.Section.PolicySection][PermConstants.DefaultPolicyType].Policy;
            int    policyCount      = model.Model[PermConstants.Section.PolicySection][PermConstants.DefaultPolicyType].Policy.Count;
            string expressionString = model.Model[PermConstants.Section.MatcherSection][PermConstants.DefaultMatcherType].Value;

            int requestTokenCount = ExpressionHandler.RequestTokens.Count;

            if (requestTokenCount != requestValues.Count)
            {
                throw new ArgumentException($"Invalid request size: expected {requestTokenCount}, got {requestValues.Count}.");
            }
            int policyTokenCount = ExpressionHandler.PolicyTokens.Count;

            ExpressionHandler.SetRequestParameters(requestValues);

            bool hasEval = Utility.HasEval(expressionString);

            bool           finalResult     = false;
            IChainEffector chainEffector   = _effector as IChainEffector;
            bool           isChainEffector = chainEffector is not null;

            if (isChainEffector)
            {
                chainEffector.StartChain(effect);

                if (policyCount is not 0)
                {
                    foreach (var policyValues in policyList)
                    {
                        if (policyTokenCount != policyValues.Count)
                        {
                            throw new ArgumentException($"Invalid policy size: expected {policyTokenCount}, got {policyValues.Count}.");
                        }

                        ExpressionHandler.SetPolicyParameters(policyValues);

                        bool expressionResult;

                        if (hasEval)
                        {
                            string expressionStringWithRule = RewriteEval(expressionString, ExpressionHandler.PolicyTokens, policyValues);
                            expressionResult = ExpressionHandler.Invoke(expressionStringWithRule, requestValues);
                        }
                        else
                        {
                            expressionResult = ExpressionHandler.Invoke(expressionString, requestValues);
                        }

                        var nowEffect = GetEffect(expressionResult);

                        if (nowEffect is not Effect.Effect.Indeterminate && ExpressionHandler.Parameters.TryGetValue("p_eft", out Parameter parameter))
                        {
                            string policyEffect = parameter.Value as string;
                            nowEffect = policyEffect switch
                            {
                                "allow" => Effect.Effect.Allow,
                                "deny" => Effect.Effect.Deny,
                                _ => Effect.Effect.Indeterminate
                            };
                        }

                        bool chainResult = chainEffector.TryChain(nowEffect);

                        if (explain && chainEffector.HitPolicy)
                        {
                            explains.Add(policyValues);
                        }

                        if (chainResult is false || chainEffector.CanChain is false)
                        {
                            break;
                        }
                    }

                    finalResult = chainEffector.Result;
                }
                else
                {
                    if (hasEval)
                    {
                        throw new ArgumentException("Please make sure rule exists in policy when using eval() in matcher");
                    }

                    IReadOnlyList <string> policyValues = Enumerable.Repeat(string.Empty, policyTokenCount).ToArray();
                    ExpressionHandler.SetPolicyParameters(policyValues);
                    var nowEffect = GetEffect(ExpressionHandler.Invoke(expressionString, requestValues));

                    if (chainEffector.TryChain(nowEffect))
                    {
                        finalResult = chainEffector.Result;
                    }

                    if (explain && chainEffector.HitPolicy)
                    {
                        explains.Add(policyValues);
                    }
                }

#if !NET45
                if (explain)
                {
                    Logger?.LogEnforceResult(requestValues, finalResult, explains);
                }
                else
                {
                    Logger?.LogEnforceResult(requestValues, finalResult);
                }
#endif
                return(finalResult);
            }

            int hitPolicyIndex;
            if (policyCount != 0)
            {
                Effect.Effect[] policyEffects = new Effect.Effect[policyCount];

                for (int i = 0; i < policyCount; i++)
                {
                    IReadOnlyList <string> policyValues = policyList[i];

                    if (policyTokenCount != policyValues.Count)
                    {
                        throw new ArgumentException($"Invalid policy size: expected {policyTokenCount}, got {policyValues.Count}.");
                    }

                    ExpressionHandler.SetPolicyParameters(policyValues);

                    bool expressionResult;

                    if (hasEval)
                    {
                        string expressionStringWithRule = RewriteEval(expressionString, ExpressionHandler.PolicyTokens, policyValues);
                        expressionResult = ExpressionHandler.Invoke(expressionStringWithRule, requestValues);
                    }
                    else
                    {
                        expressionResult = ExpressionHandler.Invoke(expressionString, requestValues);
                    }

                    var nowEffect = GetEffect(expressionResult);

                    if (nowEffect is Effect.Effect.Indeterminate)
                    {
                        policyEffects[i] = nowEffect;
                        continue;
                    }

                    if (ExpressionHandler.Parameters.TryGetValue("p_eft", out Parameter parameter))
                    {
                        string policyEffect = parameter.Value as string;
                        nowEffect = policyEffect switch
                        {
                            "allow" => Effect.Effect.Allow,
                            "deny" => Effect.Effect.Deny,
                            _ => Effect.Effect.Indeterminate
                        };
                    }

                    policyEffects[i] = nowEffect;

                    if (effect.Equals(PermConstants.PolicyEffect.Priority))
                    {
                        break;
                    }
                }

                finalResult = _effector.MergeEffects(effect, policyEffects, null, out hitPolicyIndex);
            }
            else
            {
                if (hasEval)
                {
                    throw new ArgumentException("Please make sure rule exists in policy when using eval() in matcher");
                }

                IReadOnlyList <string> policyValues = Enumerable.Repeat(string.Empty, policyTokenCount).ToArray();
                ExpressionHandler.SetPolicyParameters(policyValues);
                var nowEffect = GetEffect(ExpressionHandler.Invoke(expressionString, requestValues));
                finalResult = _effector.MergeEffects(effect, new[] { nowEffect }, null, out hitPolicyIndex);
            }

            if (explain && hitPolicyIndex is not - 1)
            {
                explains.Add(policyList[hitPolicyIndex]);
            }

#if !NET45
            if (explain)
            {
                Logger?.LogEnforceResult(requestValues, finalResult, explains);
            }
            else
            {
                Logger?.LogEnforceResult(requestValues, finalResult);
            }
#endif
            return(finalResult);
        }