internal static void ProcessInventoryItemUpdate(NancyBlackDatabase db, InventoryItem req) { if (req.IsFullfilled == false) { // Serial Number is missing - we will not auto process it if (string.IsNullOrEmpty(req.SerialNumber)) { return; } lock (BaseModule.GetLockObject("InventoryPurchase")) { var available = db.Query <InventoryPurchase>() .Where(i => i.InventoryItemId == 0 && i.ProductId == req.ProductId) .OrderBy(i => i.Id) .FirstOrDefault(); if (available == null) { // we actually dont have inventory, but serial number was keyed in // so we try the average cost instead dynamic price = db.Query("SELECT ProductId, AVG(BuyingPrice) as AvgCost FROM InventoryPurchase WHERE ProductId=? GROUP BY ProductId", new { ProductId = 1, AvgCost = 0M }, new object[] { req.ProductId }).FirstOrDefault(); if (price != null) { req.BuyingCost = (Decimal)price.AvgCost; } req.IsFullfilled = true; req.FulfilledDate = DateTime.Now; db.Connection.Update(req); } else { req.BuyingCost = available.BuyingPrice; req.BuyingTax = available.BuyingTax; req.InventoryPurchaseId = available.Id; req.IsFullfilled = true; req.FulfilledDate = DateTime.Now; available.InventoryItemId = req.Id; db.Connection.RunInTransaction(() => { db.Connection.Update(req); db.Connection.Update(available); }); } } } }
/// <summary> /// Re-add role from DB to MemCache /// </summary> private void RefreshRoleInCache(NancyBlackDatabase siteDb) { MemoryCache.Default.Remove("Membership-RolesByName"); var roleByName = siteDb.Query <NcbRole>().ToDictionary(r => r.Name.ToLowerInvariant()); MemoryCache.Default.Add("Membership-RolesByName", roleByName, DateTimeOffset.Now.AddMinutes(5)); MemoryCache.Default.Remove("Membership-Roles"); var roleById = siteDb.Query <NcbRole>().ToDictionary(r => r.Id); MemoryCache.Default.Add("Membership-Roles", roleById, DateTimeOffset.Now.AddMinutes(5)); }
/// <summary> /// Handles the case when sale order is using credit /// </summary> /// <param name="db"></param> /// <param name="so"></param> internal static void HandleCreditRequest(NancyBlackDatabase db, SaleOrder saleorder) { if (saleorder.PaymentStatus != PaymentStatus.Credit) { return; } // only create one receivable per sale order var existingReceivable = db.Query <AccountingEntry>().Where(e => e.SaleOrderId == saleorder.Id && e.IncreaseAccount == "Receivable").FirstOrDefault(); if (existingReceivable != null) { // update amount if changed if (existingReceivable.IncreaseAmount != saleorder.TotalAmount) { existingReceivable.IncreaseAmount = saleorder.TotalAmount; db.UpsertRecord(existingReceivable); } return; } AccountingEntry receivableEntry = new AccountingEntry(); receivableEntry.TransactionDate = DateTime.Now; receivableEntry.DueDate = DateTime.Now.Date.AddDays(30); receivableEntry.TransactionType = "newaccount"; receivableEntry.DebtorLoanerName = "Receivable From Sales"; receivableEntry.IncreaseAccount = "Receivable"; receivableEntry.IncreaseAmount = saleorder.TotalAmount; receivableEntry.SaleOrderId = saleorder.Id; db.UpsertRecord(receivableEntry); }
/// <summary> /// Pull serial numbers into ItemsDetail Serial Number Attribute /// </summary> public void EnsuresSerialNumberVisible(NancyBlackDatabase db) { if (this.Status == SaleOrderStatus.Delivered || this.Status == SaleOrderStatus.Shipped || this.Status == SaleOrderStatus.ReadyToShip || this.Status == SaleOrderStatus.Testing) { if (this.ItemsDetail.Any(p => p.Attributes == null || p.Attributes.Serial == null)) { var ivt = db.Query <InventoryItem>().Where(row => row.SaleOrderId == this.Id).ToLookup(row => row.ProductId); foreach (var item in this.ItemsDetail) { if (item.Attributes == null) { item.Attributes = new JObject(); } item.Attributes.Serial = string.Join(",", ivt[item.Id].Select(row => row.SerialNumber)); } db.UpsertRecord(this); } } }
/// <summary> /// Find User's Claim /// </summary> /// <param name="siteDb"></param> /// <param name="user"></param> private void AssignClaims(NancyBlackDatabase siteDb, NcbUser user) { var enroll = siteDb.Query <NcbEnroll>() .Where(e => e.IsActive && e.NcbUserId == user.Id) .ToList(); if (enroll.Count > 0) { var claims = new List <string>(); foreach (var item in enroll) { var _claims = GetRoleById(siteDb, item.NcbRoleId).Claims; if (_claims == null) { continue; } claims.AddRange(from c in GetRoleById(siteDb, item.NcbRoleId).Claims select c); } user.Claims = claims; } else { user.Claims = new string[0]; } }
private void UpdateTag_ObjectUpdate(NancyBlackDatabase db, string table, dynamic obj) { if (!(obj is IContent)) { return; } IContent content = obj; var type = content.GetType().Name; var existTags = db.Query <Tag>().Where(tag => tag.ContentId == content.Id && tag.Type == type); if (content.Tags != null) { var source = string.Join(",", content.Tags.Split(',').Distinct().OrderBy(s => s)).ToLowerInvariant(); var inDb = string.Join(",", existTags.ToList().Select(tag => tag.Name).OrderBy(s => s)).ToLowerInvariant(); // return when there is nothing change in tags if (source == inDb) { return; } } db.Transaction(() => { // delete exist tags for re-add new tags foreach (var tag in existTags) { db.DeleteRecord(tag); } // re-insert tag this.InsertTag(db, content); }); }
/// <summary> /// Get child content of given url /// </summary> /// <param name="db">Reference to the database</param> /// <param name="url">Base Url</param> /// <param name="levels">Level of items to get, 0 means unlimited.</param> /// <returns></returns> public static IEnumerable <Page> GetChildPages(NancyBlackDatabase db, string url, int levels = 0) { if (url.StartsWith("/") == false) { url = "/" + url; } url = url.ToLowerInvariant() + "/"; var query = db.Query <Page>() .Where(p => p.Url.StartsWith(url)) .Where(p => p.DisplayOrder >= 0) .OrderBy(p => p.DisplayOrder) .OrderByDescending(p => p.__createdAt); if (levels == 0) { return(query); } else { var finishQuery = query.AsEnumerable(); // hit the database return(finishQuery.Where(p => { var urlParts = p.Url.Split('/'); return (urlParts.Length - 2) == levels; })); } }
/// <summary> /// Find Ancestor of given affiliate code /// </summary> /// <param name="code"></param> /// <param name="db"></param> /// <returns></returns> private static List <string> DiscoverUpline(string code, NancyBlackDatabase db) { var ancestorList = new List <string>(); var currentCode = code; while (true) { var parent = db.Query <AffiliateRegistration>() .Where(r => r.AffiliateCode == currentCode) .FirstOrDefault(); if (parent == null || string.IsNullOrEmpty(parent.AffiliateCode) || parent.AffiliateCode == ancestorList.LastOrDefault() || // BUG in previous version of website ancestorList.Contains(parent.AffiliateCode)) // BUG in previous version of website { break; } ancestorList.Add(parent.AffiliateCode); currentCode = parent.RefererAffiliateCode; } return(ancestorList); }
public IEnumerable <object> GetRowVersions(NancyBlackDatabase db) { var rows = db.Query <RowVersion>() .Where(row => row.DataType == "SaleOrder" && row.RowId == this.Id) .ToList(); return(rows.Select(row => JsonConvert.DeserializeObject(row.js_Row))); }
/// <summary> /// See status of user opt-in /// </summary> /// <param name="db"></param> /// <param name="type"></param> /// <returns></returns> public static bool IsOptInActive(NancyBlackDatabase db, int userId, string type) { var optin = db.Query <FacebookMessengerOptIn>() .Where(o => o.NcbUserId == userId && o.OptInType == type) .FirstOrDefault(); return(optin != null); }
/// <summary> /// Load variable from database, this will only load once per application start up /// </summary> /// <param name="db"></param> public void Load(NancyBlackDatabase db) { if (_Variables != null) { return; } _Variables = db.Query <GlobalVarEntry>().ToDictionary(gv => gv.Key, gv => gv); }
/// <summary> /// Get Content which match the same Tag /// </summary> /// <param name="db"></param> /// <param name="url"></param> /// <returns></returns> public static IEnumerable <object> GetContentByTag(NancyBlackDatabase db, Tag tag, int skip, int take) { var tags = db.Query <Tag>() .Where(rec => rec.Url == tag.Url && rec.Type == tag.Type && rec.Name == tag.Name); foreach (var rec in tags) { yield return(db.GetById(rec.Type, rec.ContentId)); } }
/// <summary> /// Set Receipt Index /// </summary> /// <param name="db"></param> /// <param name="month"></param> public static void SetReceiptIdentifier(NancyBlackDatabase db, DateTime month) { db.Transaction(() => { // now, find all payment log of this month var startOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0, DateTimeKind.Utc); // this is temporary fix for receipt number to be in order as they created // because datetime in db are store in utc tick and we cannot use .ToLocalTime() in db.Query().Where() as it unsuported // so we use startOfMonth - thaiTimeZone (7 hours) instead var thaiTimeZone = TimeZoneInfo.FindSystemTimeZoneById("SE Asia Standard Time"); startOfMonth = startOfMonth.AddTicks(thaiTimeZone.BaseUtcOffset.Ticks * -1); var endOfMonth = startOfMonth.AddMonths(1).AddMilliseconds(-1); var paymentsThisMonth = db.Query <PaymentLog>() .Where(l => l.__createdAt >= startOfMonth && l.__createdAt <= endOfMonth) .OrderBy(l => l.Id).ToList(); int counter = 1; foreach (var l in paymentsThisMonth) { var receipt = db.Query <Receipt>().Where(r => r.PaymentLogId == l.Id).FirstOrDefault(); if (receipt == null) { // payment is not successful - so no receipt } else { if (string.IsNullOrWhiteSpace(receipt.Identifier)) { // our company is in Thailand so, we only publish doc in Thailand Time var receiptPublishedDate = l.__createdAt.ToUniversalTime().Add(thaiTimeZone.BaseUtcOffset); receipt.Identifier = receiptPublishedDate.ToString("RCyyyyMM-", System.Globalization.CultureInfo.InvariantCulture) + string.Format("{0:0000}", counter); db.UpsertRecord(receipt); } counter++; } } }); }
/// <summary> /// Discovers down line of current user /// </summary> /// <param name="reg"></param> /// <param name="maxLevel"></param> /// <returns></returns> public static IEnumerable <DownLineInformation> DiscoverDownLine(NancyBlackDatabase db, string topCode, int maxLevel = 2) { var cache = MemoryCache.Default["AffiliateCache"] as ILookup <string, dynamic>; if (cache == null) { cache = db.Query <AffiliateRegistration>() .AsEnumerable().ToLookup(r => r.RefererAffiliateCode, r => (new { AffiliateName = r.AffiliateName, NcbUserId = r.NcbUserId, AffiliateCode = r.AffiliateCode }) as dynamic); MemoryCache.Default.Add("AffiliateCache", cache, DateTimeOffset.Now.AddMinutes(10)); } Queue <string> referer = new Queue <string>(); referer.Enqueue(topCode); int currentLevel = 1; while (referer.Count > 0) { var current = referer.Dequeue(); var downline = cache[current]; foreach (var item in downline) { var user = db.GetById <NcbUser>((int)item.NcbUserId); if (user == null) { continue; } yield return(new DownLineInformation() { level = currentLevel, name = (string)item.AffiliateName, facebookId = user.FacebookAppScopedId, parent = current, RegistrationDate = user.__createdAt }); referer.Enqueue((string)item.AffiliateCode); } currentLevel++; if (currentLevel > maxLevel) { yield break; } } }
/// <summary> /// See status of user opt-in /// </summary> /// <param name="db"></param> /// <param name="type"></param> /// <returns></returns> public static bool IsOptInActive(NancyBlackDatabase db, NancyContext ctx, string type) { NcbUser user = ctx.CurrentUser as NcbUser; if (user.IsAnonymous) { return(false); } var optin = db.Query <FacebookMessengerOptIn>() .Where(o => o.NcbUserId == user.Id && o.OptInType == type) .FirstOrDefault(); return(optin != null); }
/// <summary> /// Get Statistics that will be use to render reward dashboard /// </summary> /// <param name="db"></param> /// <param name=""></param> public static dynamic GetRewardStats(NancyBlackDatabase db, AffiliateRegistration reg) { var allDownline = AffiliateModule.DiscoverDownLine(db, reg.AffiliateCode).ToList(); return(new { UniqueVisitorCount = reg.TotalUniqueUser, PageViewsCount = reg.TotalPageView, DownlineCount = allDownline.Count, DirectDownlineCount = allDownline.Where(d => d.level == 1).Count(), SalesCount = db.Query <SaleOrder>() .Where(so => so.PaymentStatus == PaymentStatus.PaymentReceived) .Count() }); }
/// <summary> /// Get User from login information /// </summary> /// <param name="db"></param> /// <param name="email"></param> /// <param name="passwordHash"></param> /// <returns></returns> public NcbUser GetUserFromLogin(NancyBlackDatabase db, string email, string passwordHash) { var user = db.Query <NcbUser>() .Where(u => u.Email == email && u.PasswordHash == passwordHash) .FirstOrDefault(); if (user == null) { return(null); } user.PasswordHash = null; AssignClaims(db, user); return(user); }
/// <summary> /// Handles Query Request (Get /tables/{tableName}?...) /// </summary> /// <param name="db"></param> /// <param name="arg"></param> /// <returns></returns> protected dynamic HandleQueryRequest_WithoutCountSupport(NancyBlackDatabase db, dynamic arg) { var entityName = (string)arg.table_name; if (this.Request.Query["$select"] == null) { var rows = db.Query(entityName, this.Request.Query["$filter"], this.Request.Query["$orderby"], this.Request.Query["$skip"], this.Request.Query["$top"]); return(rows); } else { var toInclude = ((string)this.Request.Query["$select"]).Split(','); if (toInclude.Length == 1 && toInclude[0] == "$select") { return(400); } if (toInclude.Length == 0) { return(400); } var rows = db.QueryAsJObject(entityName, (string)this.Request.Query["$filter"], (string)this.Request.Query["$orderby"], (string)this.Request.Query["$skip"], (string)this.Request.Query["$top"]).ToList(); foreach (JObject item in rows) { foreach (var property in item.Properties().ToList()) { if (toInclude.Contains(property.Name) == false) { property.Remove(); } } } return(rows); } }
/// <summary> /// Refreshes current global variable from database /// </summary> /// <param name="db"></param> public void Load(NancyBlackDatabase db) { lock ("GVLoad") { // persist current values first this.Persist(db); var list = db.Query <GlobalVarEntry>().OrderBy(gv => gv.Id).ToList(); var result = new Dictionary <string, GlobalVarEntry>(); foreach (var item in list) { result[item.Key] = item; } _Variables = result; } }
/// <summary> /// Get TagName and Tag's child count /// </summary> /// <param name="db"></param> /// <param name="url"></param> /// <returns></returns> public static IEnumerable <TagGroup> GetTagGroupByName(NancyBlackDatabase db, string categoryUrl, string type) { if (categoryUrl.StartsWith("/") == false) { categoryUrl = "/" + categoryUrl; } categoryUrl = categoryUrl.ToLowerInvariant() + "/"; return(db.Query <Tag>() .Where(tag => tag.Url == categoryUrl && tag.Type == type) .Select(tag => tag.Name) .GroupBy(tagName => tagName) .Select(group => new TagGroup() { Count = group.Count(), Name = group.Key })); }
public void Static_Query() { var temp = Path.GetTempFileName(); SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(temp, true); NancyBlackDatabase db = new NancyBlackDatabase(conn); var instance = new TestClass(); instance.Name = "Test Query"; db.UpsertRecord(instance); var check = db.Query<TestClass>().Where(i => i.Name == "Test Query").FirstOrDefault(); Assert.IsTrue(check.Name == "Test Query", "Query got wrong item"); conn.Dispose(); File.Delete(temp); }
/// <summary> /// Get content of given url and optionally creates the content /// </summary> /// <param name="url"></param> /// <returns></returns> public static Page GetPage(NancyBlackDatabase db, string url, bool create = false) { if (url.StartsWith("/") == false) { url = "/" + url; } url = url.ToLowerInvariant(); var page = db.Query <Page>() .Where(p => p.Url == url) .FirstOrDefault(); if (page == null && create == true) { page = ContentModule.CreatePage(db, url); } return(page); }
public static AffiliateRegistration ApplyAffiliate(NancyBlackDatabase db, int userId, string refererCode = null) { AffiliateRegistration reg = null; // whether user already registered var existing = db.Query <AffiliateRegistration>() .Where(r => r.NcbUserId == userId) .FirstOrDefault(); // dont replace existing code if (existing == null) { reg = new AffiliateRegistration(); reg.NcbUserId = userId; reg.Commission = 0.01M; // start at 1 percent // automatic code var bytes = Encoding.ASCII.GetBytes(userId.ToString()); reg.AffiliateCode = Crc32.ComputeChecksumString(bytes); var user = db.GetById <NcbUser>(userId); if (user.Profile != null && user.Profile.first_name != null) { reg.AffiliateName = user.Profile.first_name; } if (reg.AffiliateName == null) { reg.AffiliateName = "SQUAD51#" + userId; } reg.RefererAffiliateCode = refererCode; db.UpsertRecord(reg); return(reg); } else { return(existing); } }
/// <summary> /// Registers /// </summary> /// <param name="db"></param> /// <param name="registerParameters"></param> /// <returns></returns> public NcbUser Register(NancyBlackDatabase db, string email, string passwordHash, bool genCode = false, bool returnExisting = false, dynamic initialProfile = null) { var existing = db.Query <NcbUser>() .Where(u => u.Email == email) .FirstOrDefault(); if (existing != null) { if (returnExisting == true) { // Update the profile if (initialProfile != null) { existing.Profile = initialProfile; db.UpsertRecord(existing); } return(existing); } throw new InvalidOperationException("Email already in use"); } var user = new NcbUser(); user.Email = email; user.PasswordHash = passwordHash; user.Guid = Guid.NewGuid(); user.Profile = initialProfile; if (genCode == true) { user.Code = Guid.NewGuid().ToString(); user.CodeRequestDate = DateTime.Now; } db.UpsertRecord(user); user.PasswordHash = null; return(user); }
/// <summary> /// Registers /// </summary> /// <param name="db"></param> /// <param name="registerParameters"></param> /// <returns></returns> public NcbUser Reset(NancyBlackDatabase db, string email, string passwordHash, string code) { var existing = db.Query <NcbUser>() .Where(u => u.Email == email) .FirstOrDefault(); if (existing == null) { throw new InvalidOperationException("Not a valid user"); } if (existing.Code != code) { throw new InvalidOperationException("Invalid Code"); } existing.PasswordHash = passwordHash; db.UpsertRecord <NcbUser>(existing); return(existing); }
/// <summary> /// Find the role by Name, roles are cached for 5 minutes /// </summary> /// <param name="siteDb"></param> /// <param name="id"></param> /// <returns></returns> private NcbRole GetRoleByName(NancyBlackDatabase siteDb, string name) { var roles = MemoryCache.Default["Membership-RolesByName"] as Dictionary <string, NcbRole>; if (roles == null) { roles = siteDb.Query <NcbRole>().ToDictionary(r => r.Name.ToLowerInvariant()); MemoryCache.Default.Add("Membership-RolesByName", roles, DateTimeOffset.Now.AddMinutes(5)); } name = name.ToLowerInvariant(); NcbRole role; if (roles.TryGetValue(name, out role)) { return(role); } // Make sure admin is available if (name == "admin") { role = new NcbRole() { Claims = new string[] { "admin" }, Name = "admin" }; siteDb.UpsertRecord(role); MemoryCache.Default.Remove("Membership-RolesByName"); MemoryCache.Default.Remove("Membership-Roles"); return(role); } RefreshRoleInCache(siteDb); throw new InvalidOperationException("Invalid Role Name: " + name); }
public IEnumerable <object> GetPaymentLogs(NancyBlackDatabase db) { var query = db.Query <PaymentLog>() .Where(log => log.SaleOrderId == this.Id) .OrderBy(log => log.__createdAt); if (query.Count() == 0) { yield break; } foreach (var log in query) { yield return(new { PaymentDate = log.PaymentDate, Amount = log.Amount, ApCode = log.FormResponse != null ? (string)log.FormResponse.apCode : null, IsPaymentSuccess = log.IsPaymentSuccess, PaymentMethod = log.PaymentSource }); } }
/// <summary> /// Find the role by ID, roles are cached for 5 minutes /// </summary> /// <param name="siteDb"></param> /// <param name="id"></param> /// <returns></returns> private NcbRole GetRoleById(NancyBlackDatabase siteDb, int id) { var roles = MemoryCache.Default["Membership-Roles"] as Dictionary <int, NcbRole>; if (roles == null) { roles = siteDb.Query <NcbRole>().ToDictionary(r => r.Id); MemoryCache.Default.Add("Membership-Roles", roles, DateTimeOffset.Now.AddMinutes(5)); } NcbRole role; int _CountRetry = 0; try { if (roles.TryGetValue(id, out role)) { return(role); } _CountRetry++; throw new InvalidOperationException("Invalid Role Id:" + id); } catch (InvalidOperationException e) { // Retry only one time if (_CountRetry > 1) { throw e; } RefreshRoleInCache(siteDb); } return(new NcbRole()); }
private static void Initialize() { if (_Database != null || _Translations != null) { return; } lock (BaseModule.GetLockObject("TranslateHelper-Initialize")) { if (_Database != null || _Translations != null) { return; } var database = Path.Combine(BootStrapper.RootPath, "Site", "data.sqlite"); _Database = new NancyBlackDatabase(new SQLiteConnection(database, true)); _Translations = new Dictionary <string, string>(); foreach (var item in _Database.Query <TranslateEntry>().AsEnumerable()) { _Translations[item.Language + "-" + item.Primary.Trim()] = item.Translated; } } }
/// <summary> /// Get User from login information /// </summary> /// <param name="db"></param> /// <param name="email"></param> /// <param name="passwordHash"></param> /// <returns></returns> public NcbUser GetUserFromLogin( NancyBlackDatabase db, string email, string passwordHash ) { var user = db.Query<NcbUser>() .Where(u => u.Email == email && u.PasswordHash == passwordHash) .FirstOrDefault(); if (user == null) { return null; } user.PasswordHash = null; this.AssignClaims(db, user); return user; }
/// <summary> /// Get child content of given url /// </summary> /// <param name="url"></param> /// <returns></returns> public static dynamic GetContent(NancyBlackDatabase db, string url) { if (url.StartsWith("/") == false) { url = "/" + url; } return db.Query("Content", string.Format("Url eq '{0}'", url.ToLowerInvariant())).FirstOrDefault(); }
/// <summary> /// Get Root Content /// </summary> /// <param name="url"></param> /// <returns></returns> public static IEnumerable <Page> GetRootPages(NancyBlackDatabase db) { return(db.Query <Page>() .Where(p => p.Url.StartsWith("/") && p.Url.Substring(1).IndexOf('/') < 0) .OrderBy(p => p.DisplayOrder)); }
/// <summary> /// Find the role by ID, roles are cached for 5 minutes /// </summary> /// <param name="siteDb"></param> /// <param name="id"></param> /// <returns></returns> private NcbRole GetRoleById(NancyBlackDatabase siteDb, int id ) { var roles = MemoryCache.Default["Membership-Roles"] as Dictionary<int, NcbRole>; if (roles == null) { roles = siteDb.Query<NcbRole>().ToDictionary(r => r.Id); MemoryCache.Default.Add("Membership-Roles", roles, DateTimeOffset.Now.AddMinutes(5)); } NcbRole role; if (roles.TryGetValue( id, out role)) { return role; } throw new InvalidOperationException("Invalid Role Id:" + id); }
/// <summary> /// Registers /// </summary> /// <param name="db"></param> /// <param name="registerParameters"></param> /// <returns></returns> public NcbUser Register( NancyBlackDatabase db, string email, string passwordHash ) { var existing = db.Query<NcbUser>() .Where(u => u.Email == email) .FirstOrDefault(); if (existing != null) { throw new InvalidOperationException("Email already in use"); } var user = new NcbUser(); user.Email = email; user.PasswordHash = passwordHash; user.Guid = Guid.NewGuid(); db.UpsertRecord(user); user.PasswordHash = null; return user; }
/// <summary> /// Find User's Claim /// </summary> /// <param name="siteDb"></param> /// <param name="user"></param> private void AssignClaims(NancyBlackDatabase siteDb, NcbUser user ) { var enroll = siteDb.Query<NcbEnroll>() .Where(e => e.IsActive && e.NcbUserId == user.Id) .ToList(); if (enroll.Count > 0) { var claims = new List<string>(); foreach (var item in enroll) { claims.AddRange(from c in this.GetRoleById(siteDb, item.NcbRoleId).Claims select c); } user.Claims = claims; } else { user.Claims = new string[0]; } }
/// <summary> /// Find the role by Name, roles are cached for 5 minutes /// </summary> /// <param name="siteDb"></param> /// <param name="id"></param> /// <returns></returns> private NcbRole GetRoleByName(NancyBlackDatabase siteDb, string name) { var roles = MemoryCache.Default["Membership-RolesByName"] as Dictionary<string, NcbRole>; if (roles == null) { roles = siteDb.Query<NcbRole>().ToDictionary(r => r.Name.ToLowerInvariant()); MemoryCache.Default.Add("Membership-RolesByName", roles, DateTimeOffset.Now.AddMinutes(5)); } name = name.ToLowerInvariant(); NcbRole role; if (roles.TryGetValue(name, out role)) { return role; } // Make sure admin is available if (name == "admin") { role = new NcbRole() { Claims = new string[] { "admin" }, Name = "admin" }; siteDb.UpsertRecord( role ); MemoryCache.Default.Remove("Membership-RolesByName"); MemoryCache.Default.Remove("Membership-Roles"); return role; } throw new InvalidOperationException("Invalid Role Name: " + name ); }
/// <summary> /// Registers /// </summary> /// <param name="db"></param> /// <param name="registerParameters"></param> /// <returns></returns> public NcbUser Register(NancyBlackDatabase db, string userName, string email, string passwordHash, bool genCode = false, bool returnExisting = false, dynamic initialProfile = null, Guid?existingGuid = null) { var existing = db.Query <NcbUser>() .Where(u => u.UserName == userName) .FirstOrDefault(); if (existing != null) { if (returnExisting == true) { // try to get email if user specified one in facebook if (initialProfile != null) { bool save = false; // this will allow admin to add Email to User and have the profile updated if (existing.Email != null && initialProfile.email == null && existing.Email.StartsWith("fb_") == false) { existing.Profile.email = existing.Email; save = true; } // if user has set the email, we extract the email into email field if (initialProfile.email != null && existing.Email.StartsWith("fb_")) { existing.Email = initialProfile.email; save = true; } if (save) { db.UpsertRecord(existing); } } return(existing); } throw new InvalidOperationException("Email already in use"); } var user = new NcbUser(); user.UserName = userName; user.Email = email; user.PasswordHash = passwordHash; user.Profile = initialProfile; if (existingGuid != null) { user.Guid = existingGuid.Value; } else { user.Guid = Guid.NewGuid(); } if (genCode == true) { user.Code = Guid.NewGuid().ToString(); user.CodeRequestDate = DateTime.Now; } // if user is facebook user, keep the id from profile too if (user.UserName.StartsWith("fb_") && user.Profile != null) { user.FacebookAppScopedId = user.Profile.id; } db.UpsertRecord(user); user.PasswordHash = null; return(user); }