Example #1
0
        private async Task <SignInResult> ExternalLoginSignInAsync(IUser user, ExternalLoginInfo info)
        {
            var claims    = info.Principal.GetSerializableClaims();
            var userRoles = await _userManager.GetRolesAsync(user);

            var context = new UpdateRolesContext(user, info.LoginProvider, claims, userRoles);

            string[] rolesToAdd    = new string[0];
            string[] rolesToRemove = new string[0];

            var loginSettings = (await _siteService.GetSiteSettingsAsync()).As <LoginSettings>();

            if (loginSettings.UseScriptToSyncRoles)
            {
                try
                {
                    var jsonSerializerSettings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    var     script           = $"js: function syncRoles(context) {{\n{loginSettings.SyncRolesScript}\n}}\nvar context={JsonConvert.SerializeObject(context, jsonSerializerSettings)};\nsyncRoles(context);\nreturn context;";
                    dynamic evaluationResult = _scriptingManager.Evaluate(script, null, null, null);
                    rolesToAdd    = (evaluationResult.rolesToAdd as object[]).Select(i => i.ToString()).ToArray();
                    rolesToRemove = (evaluationResult.rolesToRemove as object[]).Select(i => i.ToString()).ToArray();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error Syncing Roles From External Provider {0}", info.LoginProvider);
                }
            }
            else
            {
                foreach (var item in _externalLoginHandlers)
                {
                    try
                    {
                        await item.UpdateRoles(context);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "{externalLoginHandler} - IExternalLoginHandler.UpdateRoles threw an exception", item.GetType());
                    }
                }
                rolesToAdd    = context.RolesToAdd;
                rolesToRemove = context.RolesToRemove;
            }

            await _userManager.AddToRolesAsync(user, rolesToAdd.Distinct());

            await _userManager.RemoveFromRolesAsync(user, rolesToRemove.Distinct());

            return(await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true));
        }
        /// <summary>
        /// Traverse all the nodes of the json document and replaces their value if they are scripted.
        /// </summary>
        private void EvaluateJsonTree(IScriptingManager scriptingManager, JToken node)
        {
            switch (node.Type)
            {
            case JTokenType.Array:
                var array = (JArray)node;
                for (var i = 0; i < array.Count; i++)
                {
                    EvaluateJsonTree(scriptingManager, array[i]);
                }
                break;

            case JTokenType.Object:
                foreach (var property in (JObject)node)
                {
                    EvaluateJsonTree(scriptingManager, property.Value);
                }
                break;

            case JTokenType.String:

                var value = node.Value <string>();

                // Evaluate the expression while the result is another expression
                while (value.StartsWith("[") && value.EndsWith("]"))
                {
                    value = value.Trim('[', ']');
                    value = (scriptingManager.Evaluate(value) ?? "").ToString();
                    ((JValue)node).Value = value;
                }
                break;
            }
        }
Example #3
0
        /// <summary>
        /// Traverse all the nodes of the json document and replaces their value if they are scripted.
        /// </summary>
        private void EvaluateJsonTree(IScriptingManager scriptingManager, RecipeExecutionContext context, JToken node)
        {
            switch (node.Type)
            {
            case JTokenType.Array:
                var array = (JArray)node;
                for (var i = 0; i < array.Count; i++)
                {
                    EvaluateJsonTree(scriptingManager, context, array[i]);
                }
                break;

            case JTokenType.Object:
                foreach (var property in (JObject)node)
                {
                    EvaluateJsonTree(scriptingManager, context, property.Value);
                }
                break;

            case JTokenType.String:

                var value = node.Value <string>();

                // Evaluate the expression while the result is another expression
                while (value.StartsWith('[') && value.EndsWith(']'))
                {
                    value = value.Trim('[', ']');
                    value = (scriptingManager.Evaluate(value, context.RecipeDescriptor.FileProvider, context.RecipeDescriptor.BasePath, null) ?? "").ToString();
                    ((JValue)node).Value = value;
                }
                break;
            }
        }
Example #4
0
        public async Task <string> GenerateUserName(string provider, IEnumerable <SerializableClaim> claims)
        {
            var registrationSettings = (await _siteService.GetSiteSettingsAsync()).As <RegistrationSettings>();

            if (registrationSettings.UseScriptToGenerateUsername)
            {
                var context = new { userName = String.Empty, loginProvider = provider, externalClaims = claims };

                var script = $"js: function generateUsername(context) {{\n{registrationSettings.GenerateUsernameScript}\n}}\nvar context = {JsonConvert.SerializeObject(context, _jsonSettings)};\ngenerateUsername(context);\nreturn context;";

                dynamic evaluationResult = _scriptingManager.Evaluate(script, null, null, null);
                if (evaluationResult?.userName != null)
                {
                    return(evaluationResult.userName);
                }
            }
            return(String.Empty);
        }
Example #5
0
        public async Task <T> EvaluateAsync <T>(WorkflowExpression <T> expression, WorkflowExecutionContext workflowContext, params IGlobalMethodProvider[] scopedMethodProviders)
        {
            var workflowType      = workflowContext.WorkflowType;
            var directive         = $"js:{expression}";
            var expressionContext = new WorkflowExecutionScriptContext(workflowContext);

            await _workflowContextHandlers.InvokeAsync(async x => await x.EvaluatingScriptAsync(expressionContext), _logger);

            var methodProviders = scopedMethodProviders.Concat(expressionContext.ScopedMethodProviders);

            return((T)_scriptingManager.Evaluate(directive, null, null, methodProviders));
        }
Example #6
0
        /// <summary>
        /// Traverse all the nodes of the json document and replaces their value if they are scripted.
        /// </summary>
        private void EvaluateJsonTree(IScriptingManager scriptingManager, RecipeExecutionContext context, JToken node)
        {
            switch (node.Type)
            {
            case JTokenType.Array:
                var array = (JArray)node;
                for (var i = 0; i < array.Count; i++)
                {
                    EvaluateJsonTree(scriptingManager, context, array[i]);
                }

                break;

            case JTokenType.Object:
                foreach (var property in (JObject)node)
                {
                    EvaluateJsonTree(scriptingManager, context, property.Value);
                }

                break;

            case JTokenType.String:
                const char scriptSeparator = ':';
                var        value           = node.Value <string>();

                // Evaluate the expression while the result is another expression
                while (value.StartsWith('[') && value.EndsWith(']'))
                {
                    var scriptSeparatorIndex = value.IndexOf(scriptSeparator);
                    // Only remove brackets if this is a valid script expression, e.g. '[js:xxx]', or '[file:xxx]'
                    if (!(scriptSeparatorIndex > -1 && value[1..scriptSeparatorIndex].All(c => Char.IsLetter(c))))
                    {
                        break;
                    }

                    value = value.Trim('[', ']');

                    value = (scriptingManager.Evaluate(
                                 value,
                                 context.RecipeDescriptor.FileProvider,
                                 context.RecipeDescriptor.BasePath,
                                 _methodProviders[context.ExecutionId])
                             ?? "").ToString();

                    ((JValue)node).Value = value;
                }

                break;
            }
        }
        public async Task <T> EvaluateAsync <T>(WorkflowExpression <T> expression, WorkflowExecutionContext workflowContext, params IGlobalMethodProvider[] scopedMethodProviders)
        {
            if (String.IsNullOrWhiteSpace(expression.Expression))
            {
                return(await Task.FromResult <T>(default(T)));
            }

            var workflowType      = workflowContext.WorkflowType;
            var directive         = $"js:{expression}";
            var expressionContext = new WorkflowExecutionScriptContext(workflowContext);

            await _workflowContextHandlers.InvokeAsync((h, expressionContext) => h.EvaluatingScriptAsync(expressionContext), expressionContext, _logger);

            var methodProviders = scopedMethodProviders.Concat(expressionContext.ScopedMethodProviders);

            return((T)_scriptingManager.Evaluate(directive, null, null, methodProviders));
        }
Example #8
0
        /// <summary>
        /// Traverse all the nodes of the json document and replaces their value if they are scripted.
        /// </summary>
        private void EvaluateJsonTree(IScriptingManager scriptingManager, JToken node)
        {
            var items = node as IEnumerable <JToken>;

            switch (node.Type)
            {
            case JTokenType.Array:
                foreach (var token in (JArray)node)
                {
                    EvaluateJsonTree(scriptingManager, token);
                }
                break;

            case JTokenType.Object:
                foreach (var property in (JObject)node)
                {
                    if (property.Value.Type == JTokenType.String)
                    {
                        var value = property.Value.Value <string>();

                        // Evaluate the expression while the result is another expression
                        while (value.StartsWith("[") && value.EndsWith("]"))
                        {
                            value = value.Trim('[', ']');
                            value = (scriptingManager.Evaluate(value) ?? "").ToString();
                            node[property.Key] = new JValue(value);
                        }
                    }
                    else
                    {
                        EvaluateJsonTree(scriptingManager, property.Value);
                    }
                }
                break;
            }
        }
Example #9
0
        /// <summary>
        /// Executes javascript by prefixing the script .
        /// </summary>
        /// <param name="script">The script to evaluate</param>
        /// <param name="scopedMethodProviders">A list of method providers scoped to the script evaluation.</param>
        /// <returns>The result of the script if any.</returns>
        public static object EvaluateJs(this IScriptingManager scriptingManager, string script, params IGlobalMethodProvider[] scopedMethodProviders)
        {
            var directive = $"js:{script}";

            return(scriptingManager.Evaluate(directive, null, null, scopedMethodProviders));
        }