private async Task <IdentityUser> AddPasswordHash(IdentityUser user) { DataQuery query = new DataQuery() { RawQuery = JsonConvert.SerializeObject(new { UserId = user.Id }) }; ItemList password = service.Query("_credentials", query); user.PasswordHash = password.Items.Single()["PasswordHash"].Value <string>(); return(user); }
private void InitSchema() { JArray dbEntities = service.Query("_schema", new DataModel.DataQuery() { PageNumber = 1, PageSize = int.MaxValue, RawQuery = null }).Items; foreach (JToken item in dbEntities) { CollectionSchema schema = item.ToObject <CollectionSchema>(); if (schema.CollectionName != null && !string.IsNullOrEmpty(schema.CollectionName.ToString())) { var haveIdField = schema.FieldSettings.Where(x => x.Name.Equals("_id")).Count() > 0; if (!haveIdField) { var field = new Field(); field.Name = "_id"; field.BaseType = FieldBaseType.String; field.Type = "ObjectId"; field.Required = true; schema.FieldSettings.Add(field); } entities[schema.CollectionName] = schema; } } }
public RestMessage <ItemList> Get(string collection, string rawQuery = null, int pageNumber = 1, int pageSize = 20) { // CRUDService service = new CRUDService(new MongoService(new MongoSettings() { })); ItemList result = service.Query(collection, new Library.DataModel.DataQuery() { PageNumber = pageNumber, PageSize = pageSize, RawQuery = rawQuery }); return(new RestMessage <ItemList>(result)); }
public async Task <IdentityRole> FindByIdAsync(string roleId, CancellationToken cancellationToken) { DataQuery query = new DataQuery { //TODO: Check if serialization esclude null values RawQuery = JsonConvert.SerializeObject(new IdentityRole() { RoleId = roleId }) }; //TODO: check for result count return(service.Query(collection, query).Items.First.First.ToObject <IdentityRole>()); }
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); } } }
public RestMessage <ItemList> Get(string collection, string rawQuery = null, string[] expando = null, int pageNumber = 1, int pageSize = 20, string sort = "") { var sortValue = Newtonsoft.Json.JsonConvert.DeserializeObject <List <SortOption> >(sort); // CRUDService service = new CRUDService(new MongoService(new MongoSettings() { })); ItemList result = service.Query(collection, new Library.DataModel.DataQuery() { PageNumber = pageNumber, PageSize = pageSize, RawQuery = rawQuery, Sort = sortValue, Expando = new List <string>(expando) }); return(new RestMessage <ItemList>(result)); }
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); } } } }
public JObject Post(string lambda, [FromBody] JObject input) { Library.DataModel.ItemList result = crudService.Query("_js", new Library.DataModel.DataQuery() { PageNumber = 1, PageSize = 1, RawQuery = $"{{\"Path\":\"{lambda}\"}}" }); JToken js = result.Items[0]; string code = js["Code"].ToString(); Dictionary <string, object> tmpIn = input.ToObject <Dictionary <string, object> >(); Dictionary <string, object> tmpOur = new Dictionary <string, object>(); Engine add = new Engine() .SetValue("input", tmpIn) .SetValue("output", tmpOur) .Execute(code); return(JObject.FromObject(tmpOur)); }
public JObject Post(string lambda, [FromBody] JObject input) { Library.DataModel.ItemList result = crudService.Query("_js", new Library.DataModel.DataQuery() { PageNumber = 1, PageSize = 1, RawQuery = $"{{\"Path\":\"{lambda}\"}}" }); JToken js = result.Items[0]; string code = js["Code"].ToString(); Dictionary <string, object> tmpIn = input.ToObject <Dictionary <string, object> >(); Dictionary <string, object> tmpOut = new Dictionary <string, object>(); Engine engine = new Engine((x) => { x.AllowClr(typeof(JavascriptRestClient).Assembly); x.AllowClr(typeof(JavascriptRestClientRequest).Assembly); }); engine.SetValue("input", tmpIn); engine.SetValue("RAWCMSRestClient", Jint.Runtime.Interop.TypeReference.CreateTypeReference(engine, typeof(JavascriptRestClient))); engine.SetValue("RAWCMSRestClientRequest", Jint.Runtime.Interop.TypeReference.CreateTypeReference(engine, typeof(JavascriptRestClientRequest))); engine.SetValue("output", tmpOut); try { logger.LogDebug($"calling lambda: {lambda}"); engine.Execute(code); } catch (Exception e) { logger.LogError($"Error on lambda javascript script: {e.Message} "); tmpOut.Add("Error", e.Message); } logger.LogDebug($"Lambda response: {tmpOut}"); return(JObject.FromObject(tmpOut)); }
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 }); } }
public override JObject EnrichMetadata(string collection, JObject item, Dictionary <string, object> dataContext) { JObject result = new JObject(); Schema.CollectionSchema schema = entityService.GetByName(collection); if (schema != null && dataContext.TryGetValue("expando", out object relationsObj) && relationsObj is List <string> relations) { foreach (string relName in relations) { Schema.Field field = schema.FieldSettings.FirstOrDefault(x => x.Type == "relation" && x.Name == relName); if (field != null) { RelationInfo relationInfo = relationInfoService.GetFromOptions(field, item); var hasRefAttached = relationInfo.Values.Count >= 1; if (!hasRefAttached) { result[field.Name] = relationInfo.IsMultiple ? new JArray() : null; continue; } DataQuery dq = new DataQuery() { PageNumber = 1, PageSize = 999// make it parametric }; BsonDocument b = new BsonDocument(); if (relationInfo.IsMultiple) { BsonDocument inc = new BsonDocument { ["$in"] = new BsonArray(relationInfo.Values) }; b["_id"] = inc; } else { b["_id"] = relationInfo.Values.FirstOrDefault(); } dq.RawQuery = b.ToJson(); ItemList subitems = crudService.Query(relationInfo.LookupCollection, dq); if (relationInfo.IsMultiple) { result[field.Name] = subitems.Items; } else { result[field.Name] = subitems.Items.FirstOrDefault(); } } } } return(result); }
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); }