Ejemplo n.º 1
0
        public static void AuthorizeForRole(string role)
        {
            var pctx = ContextRegistry.ContextsOf("Principal").FirstOrDefault();

            if (null == pctx)
            {
                throw new AuthenticationException("No authenticated identity");
            }

            var id = pctx.Segments.First();

            ApplicationPrincipal pr;

            if (!_cachedPrincipals.MaybeGetItem(id, out pr))
            {
                using (
                    var dc =
                        DocumentStoreLocator.ResolveOrRoot(
                            ContextualAuthorizationConfiguration.PrincipalsStore))
                {
                    pr = dc.Load <ApplicationPrincipal>(id);
                    _cachedPrincipals.Add(id, pr);
                }
            }

            if (!pr.IsInRole(role))
            {
                throw new SecurityException(string.Format("principal {0} is not in role {1}", id, role));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Get all registered items using the given document session
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        private static IEnumerable <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration> GetAll(IDocumentSession session)
        {
            var tenancy = ContextRegistry.ContextsOf("Tenancy").First().Segments[1];
            var query   = from entity in session.Query <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration>() where entity.TenancyId == tenancy select entity;

            return(query);
        }
        public static IDocumentStore ContextualResolveStore(out string dbName)
        {
            var storeType   = GetStoreType();
            var tenancyUris = ContextRegistry.ContextsOf("Tenancy");
            var tenancyUri  = tenancyUris.LastOrDefault();

            var cf  = Catalog.Factory.Resolve <IConfig>();
            var uri = new Uri(cf.Get(CommonConfiguration.CoreDatabaseRoute, RootLocation));

            string tenancy = null;

            if (null != tenancyUri)
            {
                tenancy = tenancyUri.Segments.Count() > 1 ? tenancyUri.Segments[1] : string.Empty;
            }

            if (!tenancyUris.Any() || null == tenancy)
            {
                dbName = _rootDatabase;
                return(ResolveStorePath(CommonConfiguration.CoreDatabaseRoute));
            }

            var path = string.Format("{0}{1}/{2}", SchemeRavenRoute, storeType, tenancy);

            uri = new Uri(path);
            var retval = ResolveStorePath(path);

            dbName = IsRootLocation(uri) ? _rootDatabase : _routes[uri].Database;

            return(retval);
        }
Ejemplo n.º 4
0
        public static string MakeContextualSpecKey(string key)
        {
            var appCtx     = ContextRegistry.ContextsOf("ApplicationType").First();
            var cultureCtx = ContextRegistry.ContextsOf("Culture").First();

            return(MakeSpecKey(key, appCtx.Segments.First(), cultureCtx.Segments.First()));
        }
Ejemplo n.º 5
0
        public static void CreateIndexes()
        {
            using (var nctxs = ContextRegistry.NamedContextsFor(typeof(DeviceManager)))
            {
                using (var session = DocumentStoreLocator.ContextualResolve())
                {
                    var config = Catalog.Factory.Resolve <IConfig>();
                    var dbName = config[CommonConfiguration.DefaultDataDatabase];

                    var tenancyUris = ContextRegistry.ContextsOf("Tenancy");
                    if (tenancyUris.Any())
                    {
                        var tenancyUri = tenancyUris.First();
                        var tenancy    = tenancyUri.Segments.Count() > 1 ? tenancyUri.Segments[1] : string.Empty;

                        if (!string.IsNullOrEmpty(tenancy)
                            &&
                            !tenancy.Equals(Tenants.SystemOwner, StringComparison.InvariantCultureIgnoreCase))
                        {
                            dbName = tenancy;
                        }
                    }

                    var store = session.Advanced.DocumentStore;
                    IndexesManager.CreateIndexes(store, dbName, typeof(AllDeviceIndex));
                }
            }
        }
        public static string GetContextualTenancy()
        {
            var tenancy     = string.Empty;
            var tenancyUris = ContextRegistry.ContextsOf("Tenancy");

            if (tenancyUris.Any())
            {
                var tenancyUri = tenancyUris.Last();
                tenancy = tenancyUri.Segments.Count() > 1 ? tenancyUri.Segments[1] : string.Empty;
            }
            return(tenancy);
        }
Ejemplo n.º 7
0
        public IEnumerable <Invitation> GetInvitationsFrom(string id)
        {
            var tenancy     = string.Empty;
            var tenancyUris = ContextRegistry.ContextsOf("Tenancy");
            var invitations = new List <Invitation>();

            if (tenancyUris.Any())
            {
                tenancy = tenancyUris.First().Segments.LastOrDefault();
            }

            if (!string.IsNullOrEmpty(tenancy)
                &&
                tenancy.Equals(
                    DefaultRoles.SuperAdmin.ToString(CultureInfo.InvariantCulture),
                    StringComparison.InvariantCultureIgnoreCase))
            {
                using (var session = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute))
                {
                    var q =
                        session.Query <Invitation>().Where(
                            invitation =>
                            invitation.Status != InvitationStatus.Deleted && invitation.InvitingUserId == id);
                    invitations.AddRange(q);
                }

                var tenantCollection = new TenantManager().GetAllTenants();
                foreach (var tenant in tenantCollection)
                {
                    using (var globalSession = DocumentStoreLocator.Resolve(tenant.Site))
                    {
                        var q =
                            globalSession.Query <Invitation>().Where(
                                invitation =>
                                invitation.Status != InvitationStatus.Deleted && invitation.InvitingUserId == id);
                        invitations.AddRange(q);
                    }
                }

                return(invitations);
            }

            using (var session = ReturnContext(tenancy))
            {
                var q =
                    session.Query <Invitation>().Where(
                        invitation => invitation.Status != InvitationStatus.Deleted && invitation.InvitingUserId == id);
                return(q.ToArray());
            }
        }
Ejemplo n.º 8
0
        public bool AddItemRegistration(string name, string passcode, IList <Tag> itemTags)
        {
            var item = new ItemRegistration {
                PassCode = passcode, Name = name
            };

            if (itemTags != null)
            {
                item.Tags = itemTags;
            }
            var tenancy = ContextRegistry.ContextsOf("Tenancy").First().Segments[1];

            item.TenancyId = tenancy;
            return(_itemRegistrationManager.SaveItemRegistration(item));
        }
Ejemplo n.º 9
0
        private void SignIn(string userName, bool createPersistentCookie, string tenantName)
        {
            //retrieve the last validated user by principalId
            var list        = ContextRegistry.ContextsOf("Principal");
            var principalId = list.Single().LocalPath.TrimStart('/');

            //create forms authentication ticket taking into account the tenant name
            this.SetAuthCookie(principalId, createPersistentCookie, tenantName);

            //reset menu for current session
            Session["DefaultMenu"] = null;

            //registering last validated or created user as IPrincipal
            Thread.CurrentPrincipal =
                HttpContext.User    =
                    System.Web.HttpContext.Current.User = _accountBusinessLogic.GetUserFromPrincipalId(principalId);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Invitations can be made by the system owner or a manager of a tenant. Then invitations made by system owner will go to the core db
        /// and other invitations to the tenant db. Tenant will be acquired from the current logged user. Without a tenant core db will be used.
        /// </summary>
        /// <returns></returns>
        private IDocumentSession ReturnContext()
        {
            string tenancy       = null;
            var    tenanciesUris = ContextRegistry.ContextsOf("Tenancy");

            if (tenanciesUris.Any())
            {
                tenancy = tenanciesUris.First().Segments.LastOrDefault();
            }

            using (var ctx = ContextRegistry.NamedContextsFor(GetType()))
            {
                return(string.IsNullOrEmpty(tenancy) ||
                       DefaultRoles.SuperAdmin.Equals(tenancy, StringComparison.InvariantCultureIgnoreCase)
                           ? DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute)
                           : DocumentStoreLocator.ContextualResolve());
            }
        }
Ejemplo n.º 11
0
        public static string GetStoreType()
        {
            var    contexts = ContextRegistry.ContextsOf(ContextRegistry.Kind);
            string storeType;

            if (contexts != null && contexts.Any())
            {
                var storeTypeUri = contexts.First();
                storeType = storeTypeUri.Segments.Count() > 1 ? storeTypeUri.Segments[1] : string.Empty;
            }
            else
            {
                var config           = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Safe);
                var defaultStoreType = config.Get(CommonConfiguration.StoreType, string.Empty);
                storeType = defaultStoreType;
            }
            return(storeType);
        }
Ejemplo n.º 12
0
        public HealthStatus EvaluateDevice(IDevice device, IEnumerable<object> data)
        {
            var tenancyUris = ContextRegistry.ContextsOf("Tenancy");
            if (!tenancyUris.Any())
            {
                return HealthStatus.Unknown;
            }

            var tenancyUri = tenancyUris.First();
            var tenancy = tenancyUri.Segments.Count() > 1 ? tenancyUri.Segments[1] : string.Empty;

            var typeGrouped = from d in data
                              group d by d.GetType()
                                  into items
                                  select new { Key = items.Key, Items = items };

            List<Alert> alerts = new List<Alert>();

            foreach (var tg in typeGrouped)
            {
                var rules = this._rulesRepository.LoadRulesForType(tg.Key, tenancy);

                if (rules.Any())
                {
                    foreach (var r in rules)
                    {
                        var newAlerts = r.Apply(device, tg.Items);
                        if (newAlerts.Any())
                        {
                            alerts.AddRange(newAlerts);
                        }
                    }
                }

            }

            var retval = this.ProcessAlerts(device, alerts);

            return retval;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets item registrations with tags matching the given criteria and time category
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public IEnumerable <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration> Get(string criteria = null, TimeCategories time = TimeCategories.All)
        {
            var filteredItemRegistrationList = new List <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration>();

            using (var session = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute))
            {
                var tenancy = ContextRegistry.ContextsOf("Tenancy").First().Segments[1];
                if (!string.IsNullOrEmpty(criteria))
                {
                    var query = from entity in session.Query <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration>()
                                where
                                entity.TenancyId == tenancy && entity.Tags.Any(tag => tag.Id.ToString() == criteria)
                                select entity;

                    filteredItemRegistrationList.AddRange(query);
                }

                //filter by criteria over registered time
                if (time != TimeCategories.All)
                {
                    var registrations = from entity in session.Query <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration>()
                                        where entity.TenancyId == tenancy
                                        select entity;

                    var aFunction = TimeFilterManager.GetTimeFilterDateComparison(time);

                    return((from itemRegistration in registrations.ToArray()
                            let dateCreation = itemRegistration.TimeRegistered
                                               where aFunction(dateCreation)
                                               select itemRegistration).ToArray());
                }

                if (string.IsNullOrEmpty(criteria) && time == TimeCategories.All)
                {
                    return(GetAll(session));
                }
            }

            return(filteredItemRegistrationList);
        }
Ejemplo n.º 14
0
        public Invitation CreateInvitationEntityFromModel(OwnerInvitationModel model, DateTime expirationTime, ApplicationUser creatorPrincipal)
        {
            var email       = model.SentTo;
            var userInvited = userBusinessLogic.GetByEmail(email);

            if (userInvited == null)
            {
                userInvited = new Lok.Unik.ModelCommon.Client.User
                {
                    AppUser =
                        new ApplicationUser
                    {
                        Tenancy      = model.Tenancy,
                        ContactEmail = model.SentTo,
                        Status       = UserStatus.Invited,
                        DateCreated  = DateTime.UtcNow,
                        PrincipalId  = string.Format("formsauthentication/{0}", Guid.NewGuid())
                    }
                };

                userBusinessLogic.CreateNewUser(userInvited, creatorPrincipal);
            }

            var list        = ContextRegistry.ContextsOf("Principal");
            var principalId = list.Single().LocalPath.TrimStart('/');

            var invitation = this.ModelToEntity(model);

            invitation.AcceptingUser = userInvited.AppUser;
            if (invitation.AuthorizationCode != null)
            {
                invitation.AuthorizationCode.ExpirationTime = expirationTime;
            }

            invitation.InvitingUserId = principalId;

            return(invitation);
        }
Ejemplo n.º 15
0
        public IList <Tag> GetAllTagByItemRegistrationNonDefault()
        {
            var bag = new List <Tag>();

            try
            {
                using (var session = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute))
                {
                    var tenancy       = ContextRegistry.ContextsOf("Tenancy").First().Segments[1];
                    var aTagsListList =
                        session.Query <ItemRegistration>().Where(entity => entity.TenancyId == tenancy).ToList();

                    foreach (var aTag in
                             aTagsListList.Select(entity => entity.Tags).SelectMany(
                                 aTagsList =>
                                 aTagsList.Where(aTag => aTag.Category.Color != KnownColor.Transparent && !bag.Contains(aTag))))
                    {
                        bag.Add(aTag);
                    }
                }
            }

            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    _log.Error(ex + " InnerException: " + ex.InnerException);
                }
                else
                {
                    _log.Error(ex.Message);
                }
            }

            return(bag);
        }
Ejemplo n.º 16
0
        private static string GetTenancy()
        {
            string tenancy = null;

            var tenancyUris = ContextRegistry.ContextsOf("Tenancy");

            if (tenancyUris.Any())
            {
                var tenancyUri = tenancyUris.First();
                tenancy = tenancyUri.Segments.Count() > 1 ? tenancyUri.Segments[1] : string.Empty;
            }
            else
            {
                var context = HttpContext.Current;
                if (context != null &&
                    context.Request.RequestContext.RouteData.Values.ContainsKey(TenantConstants.TenantRouteName))
                {
                    tenancy = context.Request.RequestContext.RouteData.GetRequiredString(
                        TenantConstants.TenantRouteName);
                }
            }

            return(tenancy);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// saves the item registration with tags
        /// </summary>
        /// <param name="name"> </param>
        /// <param name="passcode"></param>
        /// <param name="type"></param>
        /// <param name="newTags"></param>
        /// <param name="selectTag"></param>
        /// <param name="facilityId"> </param>
        /// <returns></returns>
        public bool SaveItemRegistration(
            string name, string passcode,
            string type, IList <Tag> newTags,
            IList <string> selectTag, string facilityId = null)
        {
            using (var session = DocumentStoreLocator.Resolve(DocumentStoreLocator.RootLocation))
            {
                var tenancy = ContextRegistry.ContextsOf("Tenancy").First().Segments[1];

                var query = from entity in session.Query <Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration>()
                            where entity.TenancyId == tenancy
                            select entity;

                // all item registrations in the tenant
                var dRegistration = query.ToArray();

                var oldTag = new List <Tag>();

                // list of existing tags matching the selection
                var oldTagFind = new List <Tag>();

                if (null != selectTag && selectTag.Count > 0)
                {
                    // record all distinct tags used for all registered items
                    oldTag.AddRange(dRegistration.SelectMany(deviceRegistration => deviceRegistration.Tags));
                    oldTag = oldTag.Distinct().ToList();

                    // for every tag selected
                    foreach (var tag2 in selectTag.Where(tag => !string.IsNullOrEmpty(tag)))
                    {
                        var tag3 = tag2;

                        // find all recorded tags matching the selection tags
                        foreach (var tag1 in oldTag.Where(tag1 => tag3.Equals(tag1.Value)))
                        {
                            oldTagFind.Add(tag1);
                            break;
                        }
                    }
                }

                oldTagFind = oldTagFind.Distinct().ToList();

                foreach (var old in oldTagFind)
                {
                    newTags.Add(old);
                }

                // retain all old tags, add in a grouping tag
                var dr = new Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration
                {
                    Id             = Guid.NewGuid(),
                    TenancyId      = tenancy,
                    PassCode       = passcode,
                    Name           = name,
                    Tags           = newTags,
                    TimeRegistered = DateTime.UtcNow,
                    Type           = type,
                    FacilityId     = facilityId
                };

                //Add Default Tag for Grouping.
                dr.Tags.Add(
                    new Tag
                {
                    Id         = Guid.NewGuid(),
                    Type       = TagType.ItemRegistration,
                    Attribute  = dr.Name,
                    Value      = dr.PassCode,
                    CreateDate = DateTime.UtcNow,
                    Category   = new TagCategory {
                        Name = TagType.ItemRegistration.EnumName(), Color = KnownColor.Transparent
                    }
                });

                session.Store(dr);
                session.SaveChanges();
                return(true);
            }
        }