Ejemplo n.º 1
0
 public async Task <IdentityResult> CreateAsync(IdentityRole role, CancellationToken cancellationToken)
 {
     role.RoleId = role.RoleId.ToLower();
     //TODO: Add check to avoid duplicates
     service.Insert(collection, JObject.FromObject(role));
     return(IdentityResult.Success);
 }
Ejemplo n.º 2
0
        public RestMessage <bool> Post(string collection, [FromBody] JObject value)
        {
            RestMessage <bool> response = new RestMessage <bool>(false);

            try
            {
                service.Insert(collection, value);
                response.Data = true;
                return(response);
            }
            catch (ValidationException err)
            {
                response.Errors = err.Errors;
            }
            catch (Exception untrapped)
            {
                //TODO: log here
                response.Errors.Add(new Library.Core.Error()
                {
                    Code        = "UNEXPEXTED",
                    Title       = $"{collection} produces an unexpexted error",
                    Description = untrapped.Message,
                });
            }
            return(response);
        }
Ejemplo n.º 3
0
        public RestMessage <JObject> Post(string collection, [FromBody] JObject value, bool omitPayload = false)
        {
            RestMessage <JObject> response = new RestMessage <JObject>(new JObject());

            try
            {
                var added = service.Insert(collection, value);
                if (omitPayload)
                {
                    response.Data["_id"] = added["_id"];
                }
                else
                {
                    response.Data = added;
                }
                return(response);
            }
            catch (ValidationException err)
            {
                response.Errors = err.Errors;
            }
            catch (Exception untrapped)
            {
                //TODO: log here
                response.Errors.Add(new Library.Core.Error()
                {
                    Code        = "UNEXPEXTED",
                    Title       = $"{collection} produces an unexpexted error",
                    Description = untrapped.Message,
                });
            }
            return(response);
        }
Ejemplo n.º 4
0
        public override void Execute(string collection, ref JObject item, ref Dictionary <string, object> dataContext)
        {
            if (collection == "_users")
            {
                if (dataContext.ContainsKey("NewPassword"))
                {
                    string  id = item["_id"].Value <string>();
                    JObject o  = new JObject
                    {
                        ["UserId"]       = id,
                        ["PasswordHash"] = RawUserStore.ComputePasswordHash(dataContext["NewPassword"] as string)
                    };

                    //Password cant' be changed during update
                    if (item.ContainsKey("_id") && !string.IsNullOrWhiteSpace(item["_id"].Value <string>()))
                    {
                        DataQuery query = new DataQuery()
                        {
                            RawQuery = JsonConvert.SerializeObject(new { UserId = id })
                        };

                        ItemList password = service.Query(collection, query);

                        if (password.Items.HasValues)
                        {
                            o["_id"] = password.Items[0]["_id"].Value <string>();
                            //patch password only
                            service.Update("_credentials", o, false);
                        }
                        else
                        {
                            service.Insert("_credentials", o);
                        }
                    }
                    else
                    {
                        service.Insert("_credentials", o);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private void LoadPluginSettings(List <Type> pluginTypes, IConfigurationRoot configuration, IServiceCollection services)
        {
            _logger.LogDebug($"LoadPluginSettings");

            MongoSettings instance   = MongoSettings.GetMongoSettings(configuration);
            var           tmpService = new CRUDService(new MongoService(instance, _logger), instance, this);

            foreach (var plugin in pluginTypes)
            {
                _logger.LogDebug($"checking {plugin.FullName}");
                Type confitf = plugin.GetInterface("IConfigurablePlugin`1");//TODO: remove hardcoded reference to generic
                if (confitf != null)
                {
                    _logger.LogDebug($" {plugin.FullName} need a configuration");
                    Type confType = confitf.GetGenericArguments()[0];

                    ItemList confItem = tmpService.Query("_configuration", new DataQuery()
                    {
                        PageNumber = 1,
                        PageSize   = 1,
                        RawQuery   = @"{""plugin_name"":""" + plugin.FullName + @"""}"
                    });

                    JObject confToSave = null;

                    if (confItem.TotalCount == 0)
                    {
                        _logger.LogDebug($" {plugin.FullName} no persisted configuration found. Using default");
                        confToSave = new JObject
                        {
                            ["plugin_name"] = plugin.FullName,
                            ["data"]        = JToken.FromObject(Activator.CreateInstance(confType))
                        };
                        tmpService.Insert("_configuration", confToSave);
                        _logger.LogDebug($" {plugin.FullName} default config saved to database");
                    }
                    else
                    {
                        confToSave = confItem.Items.First as JObject;
                        _logger.LogDebug($" {plugin.FullName} configuration found");
                    }

                    object objData = confToSave["data"].ToObject(confType);

                    _logger.LogDebug($" {plugin.FullName} configuration added to container");
                    services.AddSingleton(confType, objData);
                }
            }
        }
Ejemplo n.º 6
0
        private void SetConfiguration(Plugin plugin, CRUDService crudService)
        {
            Type confitf = plugin.GetType().GetInterface("IConfigurablePlugin`1");

            if (confitf != null)
            {
                Type confType   = confitf.GetGenericArguments()[0];
                Type pluginType = plugin.GetType();

                ItemList confItem = crudService.Query("_configuration", new DataQuery()
                {
                    PageNumber = 1,
                    PageSize   = 1,
                    RawQuery   = @"{""plugin_name"":""" + pluginType.FullName + @"""}"
                });

                JObject confToSave = null;

                if (confItem.TotalCount == 0)
                {
                    confToSave = new JObject
                    {
                        ["plugin_name"] = plugin.GetType().FullName,
                        ["data"]        = JToken.FromObject(pluginType.GetMethod("GetDefaultConfig").Invoke(plugin, new object[] { }))
                    };
                    crudService.Insert("_configuration", confToSave);
                }
                else
                {
                    confToSave = confItem.Items.First as JObject;
                }

                object objData = confToSave["data"].ToObject(confType);

                pluginType.GetMethod("SetActualConfig").Invoke(plugin, new object[] { objData });
            }
        }
Ejemplo n.º 7
0
 public async Task <IdentityResult> CreateAsync(IdentityUser user, CancellationToken cancellationToken)
 {
     user.NormalizedUserName = user.UserName.ToUpper();
     service.Insert(collection, JObject.FromObject(user));
     return(IdentityResult.Success);
 }
Ejemplo n.º 8
0
        public static AuthenticationBuilder AddJwtProvider(this AuthenticationBuilder builder, ExternalProvider configuration, CRUDService cRUDService)
        {
            builder.AddJwtBearer(configuration.SchemaName, x =>
            {
                x.Authority = configuration.Authority;
                x.Audience  = configuration.Audience;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType = configuration.RoleClaimType
                };
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async ctx =>
                    {
                        var accessToken = ctx.SecurityToken as JwtSecurityToken;
                        if (accessToken != null)
                        {
                            var client  = new HttpClient();
                            var request = new HttpRequestMessage
                            {
                                Method     = HttpMethod.Post,
                                RequestUri = new Uri(configuration.UserInfoEndpoint)
                            };
                            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken.RawData);
                            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                            var message = await client.SendAsync(request);
                            if (message.IsSuccessStatusCode)
                            {
                                var response = await message.Content.ReadAsStringAsync();
                                var userInfo = JsonConvert.DeserializeObject <JObject>(response);
                                if (ctx.Principal.Identity is ClaimsIdentity identity)
                                {
                                    foreach (var cl in userInfo.Properties())
                                    {
                                        if (identity.Claims.Where(y => y.Type == cl.Name).Count() == 0)
                                        {
                                            identity.AddClaim(new Claim(cl.Name, cl.Value.Value <string>()));
                                        }
                                    }

                                    var user = cRUDService.Query("_users", new DataQuery()
                                    {
                                        PageNumber = 1,
                                        PageSize   = 1,
                                        RawQuery   = @"{""Email"":""" + identity.Claims.FirstOrDefault(y => y.Type == "email")?.Value + @"""}"
                                    });

                                    if (user.TotalCount == 0)
                                    {
                                        var userToSave = new JObject
                                        {
                                            ["UserName"]   = identity.Claims.FirstOrDefault(y => y.Type == "name")?.Value,
                                            ["Email"]      = identity.Claims.FirstOrDefault(y => y.Type == "email")?.Value,
                                            ["IsExternal"] = true,
                                        };
                                        user.Items.Add(cRUDService.Insert("_users", userToSave));
                                    }

                                    string perm   = ctx.Principal.FindFirstValue(configuration.RoleClaimType);
                                    var claimRole = identity.Claims.Where(y => y.Type == ClaimTypes.Role).FirstOrDefault() ?? new Claim(ClaimTypes.Role, string.Empty);
                                    var roles     = string.Join(',', claimRole.Value, perm);

                                    if (user.Items.First["Roles"] != null)
                                    {
                                        roles = string.Join(',', roles, user.Items.First["Roles"].Values <string>()?.ToList());
                                    }
                                    identity.AddClaim(new Claim(ClaimTypes.Role, roles));
                                }
                            }
                        }
                    }
                };

                x.Validate();
            });
            return(builder);
        }