Esempio n. 1
0
        /// <summary>
        /// Adds a "required" constraint to the TenantId string property and
        /// sets the query filter for the entity on TenantId.
        /// </summary>
        /// <remarks>
        ///     <list type="bullet">
        ///         <item><description>This method is called from OnModelCreating of the derived DbContext.</description></item>
        ///         <item><description>If no TenantId string property exists, a shadow property is created.</description></item>
        ///         <item><description>The query filter has no effect when calling DbSet.Find.</description></item>
        ///     </list>
        /// </remarks>
        /// <param name="modelBuilder"></param>
        /// <param name="tenantInfo"></param>
        public static void SetupModel(ModelBuilder modelBuilder, TenantInfo tenantInfo)
        {
            foreach (var t in modelBuilder.Model.GetEntityTypes().
                     Where(t => HasMultiTenantAttribute(t.ClrType)))

            {
                var r = modelBuilder.Entity(t.ClrType);

                try
                {
                    r.Property <string>("TenantId").IsRequired().HasMaxLength(Constants.TenantIdMaxLength);
                }
                catch (Exception e)
                {
                    throw new MultiTenantException($"{t.ClrType} unable to add TenantId property", e);
                }

                // build expression tree for e => EF.Property<string>(e, "TenantId") == tenantId
                // where e is one of our entity types
                // will need this ParameterExpression for next step and for final step
                var entityParamExp = Expression.Parameter(t.ClrType, "e");

                // build up expression tree for EF.Property<string>(e, "TenantId")
                var tenantIdExp   = Expression.Constant("TenantId", typeof(string));
                var efPropertyExp = Expression.Call(typeof(EF), "Property", new[] { typeof(string) }, entityParamExp, tenantIdExp);
                var leftExp       = efPropertyExp;

                // build expression tree for EF.Property<string>(e, "TenantId") == tenantId
                var rightExp = Expression.Constant(tenantInfo?.Id, typeof(string));
                var equalExp = Expression.Equal(leftExp, rightExp);

                // build the final expression tree
                var delegateType = Expression.GetDelegateType(t.ClrType, typeof(bool));
                var lambdaExp    = Expression.Lambda(delegateType, equalExp, entityParamExp);

                // set the filter
                r.HasQueryFilter(lambdaExp);
            }
        }
Esempio n. 2
0
    public void AddUserLoginIndex()
    {
        var tenant1 = new TenantInfo
        {
            Id               = "abc",
            Identifier       = "abc",
            Name             = "abc",
            ConnectionString = "DataSource=testdb.db"
        };
        var c = new NonDerivedIdenityDbContext(tenant1, _options);

        var props = new List <IProperty>();

        props.Add(c.Model.FindEntityType(typeof(IdentityUserLogin <string>)).FindProperty("LoginProvider"));
        props.Add(c.Model.FindEntityType(typeof(IdentityUserLogin <string>)).FindProperty("ProviderKey"));
        props.Add(c.Model.FindEntityType(typeof(IdentityUserLogin <string>)).FindProperty("TenantId"));

        var index = c.Model.FindEntityType(typeof(IdentityUserLogin <string>)).FindIndex(props);

        Assert.NotNull(index);
        Assert.True(index.IsUnique);
    }
Esempio n. 3
0
    void ThrowsIfExistingTenantIdWrongType()
    {
        try
        {
            _connection.Open();
            var tenant1 = new TenantInfo("abc", "abc", "abc",
                                         "DataSource=testdb.db", null);

            var _options = new DbContextOptionsBuilder <TestWrongTenantIdTypeDbContext>()
                           .UseSqlite(_connection)
                           .Options;

            using (var db = new TestWrongTenantIdTypeDbContext(tenant1, _options))
            {
                Assert.Throws <MultiTenantException>(() => db.Database.EnsureCreated());
            }
        }
        finally
        {
            _connection.Close();
        }
    }
Esempio n. 4
0
    public void ClearOptionsForTenantIdOnly()
    {
        var ti = new TenantInfo("test-id-123", null, null, null, null);
        var tc = new MultiTenantContext();

        tc.TenantInfo = ti;
        var tca   = new TestMultiTenantContextAccessor(tc);
        var cache = new MultiTenantOptionsCache <CookieAuthenticationOptions>(tca);

        var options = new CookieAuthenticationOptions();

        // Add new options.
        var result = cache.TryAdd("", options);

        Assert.True(result);

        // Add under a different tenant.
        ti.Id  = "diff_id";
        result = cache.TryAdd("", options);
        Assert.True(result);

        // Clear options on first tenant.
        cache.Clear("test-id-123");

        // Assert options cleared on this tenant.
        var tenantCache = (ConcurrentDictionary <string, IOptionsMonitorCache <CookieAuthenticationOptions> >)cache.GetType().
                          GetField("map", BindingFlags.NonPublic | BindingFlags.Instance).
                          GetValue(cache);

        dynamic tenantInternalCache = tenantCache[ti.Id].GetType().GetField("_cache", BindingFlags.NonPublic | BindingFlags.Instance)
                                      .GetValue(tenantCache["test-id-123"]);

        Assert.True(tenantInternalCache.IsEmpty);

        // Assert options still exist on other tenant.
        tenantInternalCache = tenantCache["diff_id"].GetType().GetField("_cache", BindingFlags.NonPublic | BindingFlags.Instance)
                              .GetValue(tenantCache["diff_id"]);
        Assert.False(tenantInternalCache.IsEmpty);
    }
    public void SetMultiTenantContextAcccessor()
    {
        var services = new ServiceCollection();

        services.AddMultiTenant <TenantInfo>();
        var sp = services.BuildServiceProvider();

        var httpContextMock = new Mock <HttpContext>();

        httpContextMock.Setup(c => c.RequestServices).Returns(sp);
        var context = httpContextMock.Object;

        var ti2 = new TenantInfo {
            Id = "tenant2"
        };
        var res      = context.TrySetTenantInfo(ti2, false);
        var mtc      = context.GetMultiTenantContext <TenantInfo>();
        var accessor = context.RequestServices.GetRequiredService <IMultiTenantContextAccessor <TenantInfo> >();

        Assert.True(res);
        Assert.Same(mtc, accessor.MultiTenantContext);
    }
Esempio n. 6
0
        public void InitTree()
        {
            mListRootItems.Clear();
            mRoot.Children.Clear();

            for (int i = 0; i < ListTenant.Count; i++)
            {
                TenantInfo TI       = ListTenant[i];
                NodeData   RootNode = new NodeData();
                RootNode.Parent      = mRoot;
                RootNode.Data        = TI;
                RootNode.Name        = TI.RentName;
                RootNode.Description = TI.ToString();
                RootNode.ObjID       = TI.RentID;
                RootNode.Type        = S1111Consts.Rent;
                RootNode.Icon        = "Images/root.ico";
                //mRoot.AddChild(RootNode);
                Dispatcher.Invoke(new Action(() => mRoot.AddChild(RootNode)));
                InitResourceName(RootNode, TI.RentID);
                mListRootItems.Add(RootNode);
            }
        }
Esempio n. 7
0
        //public MultiTenancyMiddleware(
        //    RequestDelegate next,
        //    ITenantResolver tenantResolver,
        //    ICurrentTenant currentTenant,
        //    ITenantResolveResultAccessor tenantResolveResultAccessor)
        //{
        //    _next = next;
        //    _tenantResolver = tenantResolver;
        //    _currentTenant = currentTenant;
        //    _tenantResolveResultAccessor = tenantResolveResultAccessor;
        //}

        public async Task InvokeAsync(HttpContext httpContext, ITenantStore tenantStore)
        {
            var resolveResult = _tenantResolver.ResolveTenantIdOrName();

            _tenantResolveResultAccessor.Result = resolveResult;

            TenantInfo tenant = null;

            if (resolveResult.TenantIdOrName != null)
            {
                tenant = await tenantStore.FindAsync(resolveResult.TenantIdOrName);

                if (tenant == null)
                {
                    throw new LinFxException("There is no tenant with given tenant id or name: " + resolveResult.TenantIdOrName);
                }
            }

            using (_currentTenant.Change(tenant?.Id, tenant?.Name))
            {
                await _next(httpContext);
            }
        }
Esempio n. 8
0
        public void TeamsChannelDataInits()
        {
            var channel      = new ChannelInfo("general", "General");
            var eventType    = "eventType";
            var team         = new TeamInfo("supportEngineers", "Support Engineers");
            var notification = new NotificationInfo(true);
            var tenant       = new TenantInfo("uniqueTenantId");
            var meeting      = new TeamsMeetingInfo("BFSE Stand Up");

            var channelData = new TeamsChannelData(channel, eventType, team, notification, tenant)
            {
                Meeting = meeting
            };

            Assert.NotNull(channelData);
            Assert.IsType <TeamsChannelData>(channelData);
            Assert.Equal(channel, channelData.Channel);
            Assert.Equal(eventType, channelData.EventType);
            Assert.Equal(team, channelData.Team);
            Assert.Equal(notification, channelData.Notification);
            Assert.Equal(tenant, channelData.Tenant);
            Assert.Equal(meeting, channelData.Meeting);
        }
        public void AdjustRoleIndex()
        {
            var tenant1 = new TenantInfo
            {
                Id               = "abc",
                Identifier       = "abc",
                Name             = "abc",
                ConnectionString = "DataSource=testDb.db"
            };

            using var c = new TestIdentityDbContext(tenant1);

            var props = new List <IProperty>
            {
                c.Model.FindEntityType(typeof(IdentityRole))?.FindProperty("NormalizedName") !,
                c.Model.FindEntityType(typeof(IdentityRole))?.FindProperty("TenantId") !
            };

            var index = c.Model.FindEntityType(typeof(IdentityRole))?.FindIndex(props);

            Assert.NotNull(index);
            Assert.True(index !.IsUnique);
        }
Esempio n. 10
0
    public void NotResetScopeIfNotApplicable()
    {
        var httpContextMock = new Mock <HttpContext>();

        httpContextMock.SetupProperty(c => c.RequestServices);

        var services = new ServiceCollection();

        services.AddScoped <object>(_sp => DateTime.Now);
        services.AddMultiTenant <TenantInfo>();
        var sp = services.BuildServiceProvider();

        httpContextMock.Object.RequestServices = sp;

        var ti2 = new TenantInfo {
            Id = "tenant2"
        };
        var res = httpContextMock.Object.TrySetTenantInfo(ti2, false);

        Assert.Same(sp, httpContextMock.Object.RequestServices);
        Assert.StrictEqual <DateTime>((DateTime)sp.GetService <object>(),
                                      (DateTime)httpContextMock.Object.RequestServices.GetService <object>());
    }
Esempio n. 11
0
        public void CompileField(TenantInfo tenant, long calcFieldId, string calcFieldName)
        {
            using (tenant.GetTenantAdminContext( ))
                using (new MemoryGuard(2 * TenantHealthHelpers.OneGb, ClearSelectedCaches))
                    using (new MemoryGuard(3 * TenantHealthHelpers.OneGb, TenantHealthHelpers.ClearAllCaches))
                        using (new MemoryLogger(new KeyValuePair <string, object>("Tenant", tenant.TenantName), new KeyValuePair <string, object>("Calculated Field Id", calcFieldId)))
                        {
                            CalculatedFieldMetadata staticResult;
                            long [] fields = new [] { calcFieldId };

                            // Perform static calculation
                            staticResult = Factory.CalculatedFieldMetadataProvider.GetCalculatedFieldMetadata(fields, CalculatedFieldSettings.Default).Single( );

                            // We got a result (assert true)
                            Assert.That(staticResult, Is.Not.Null, "CalculatedFieldMetadata is not null");

                            // It has no errors
                            Assert.That(staticResult.Exception, Is.Null, $"{staticResult.Exception}");

                            // And we have an expression (assert true, if no error)
                            Assert.That(staticResult.Expression, Is.Not.Null, "CalculatedFieldMetadata.Expression is not null.");
                        }
        }
Esempio n. 12
0
        }// End ConfigureServices method

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseForwardedHeaders(); // from old config, remove ???
            if (env.EnvironmentName == "Development")
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseRouting();
            app.UseMultiTenant();

            var ti = new TenantInfo("finbuckle", "finbuckle-id1", "finbuckle-name", "Server=localhost;Port=5432;Uid=postgres;Pwd=pwd123;Database=Tenant1", null);

            SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope().ServiceProvider, ti);
            ti = new TenantInfo("megacorp", "megacorp-id2", "megacorp-name", "Server=localhost;Port=5432;Uid=postgres;Pwd=pwd123;Database=Tenant2", null);
            SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope().ServiceProvider, ti);
            ti = new TenantInfo("initech", "initech-id3", "Initech LLC", "Server=localhost;Port=5432;Uid=postgres;Pwd=pwd123;Database=Tenant3", null);
            SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope().ServiceProvider, ti);

            app.UseAuthentication();
            app.UseHttpsRedirection();
        } //end Configure method
Esempio n. 13
0
    public void SetTenantInfo()
    {
        var services = new ServiceCollection();

        services.AddMultiTenant().WithInMemoryStore().WithStaticStrategy("initech");
        var sp = services.BuildServiceProvider();
        var ti = new TenantInfo("initech", "initech", null, null, null);

        sp.GetService <IMultiTenantStore>().TryAddAsync(ti).Wait();

        var context = CreateHttpContextMock(sp).Object;

        var mw = new MultiTenantMiddleware(null);

        mw.Invoke(context).Wait();

        var resolvedTenantContext = (MultiTenantContext)context.Items[Finbuckle.MultiTenant.AspNetCore.Constants.HttpContextMultiTenantContext];

        Assert.NotNull(resolvedTenantContext.TenantInfo);
        Assert.Equal("initech", resolvedTenantContext.TenantInfo.Id);
        Assert.Equal("initech", resolvedTenantContext.TenantInfo.Identifier);
        Assert.NotNull(resolvedTenantContext.TenantInfo.MultiTenantContext);
    }
        private List <int> GetQuotationsInfo(TenantInfo tenantInfo)
        {
            var tenantType = tenantInfo.Tenant.TenantType;

            var assetsOwned = _assetOwnershipRepository.GetAll()
                              .Include(a => a.AssetFk)
                              .WhereIf(tenantType == "A", a => a.AssetOwnerId == tenantInfo.AssetOwner.Id) // Filter out any Assets that are not relevant to the AssetOwener
                              .Where(a => !a.IsDeleted)
                              .Select(a => a.AssetId)
                              .ToList();

            var quotationsInLastTwoMonths = _quotationRepository.GetAll()
                                            .Include(q => q.AssetFk)
                                            .Where(q => q.CreationTime > DateTime.Now.AddDays(-60))
                                            .Where(q => !q.IsDeleted)
                                            .Where(q => q.SupportContractFk.AssetOwnerId == tenantInfo.AssetOwner.Id || assetsOwned.Contains(q.AssetId))
                                            .ToList();

            decimal quotationsThisMonthDec = quotationsInLastTwoMonths
                                             .Where(q => q.CreationTime > DateTime.Now.AddDays(-30))
                                             .Count();

            decimal previousMonth = quotationsInLastTwoMonths.Count() - quotationsThisMonthDec;

            quotationsThisMonthDec = (quotationsThisMonthDec == 0) ? (decimal)0.001 : quotationsThisMonthDec;
            previousMonth          = (previousMonth == 0) ? (decimal)0.001 : previousMonth;

            decimal changeDec = (quotationsThisMonthDec > previousMonth) ? (previousMonth / quotationsThisMonthDec) : -(quotationsThisMonthDec / previousMonth);

            int change = (int)Math.Round(changeDec);
            int quotationsThisMonth = (int)Math.Round(quotationsThisMonthDec);

            return(new List <int>()
            {
                quotationsThisMonth, change
            });
        }
Esempio n. 15
0
        /// <summary>
        /// Returns the <see cref="CultureInfo"/> based on <see cref="GenerateMarkupArguments"/>.
        /// Throws an exception if not one of the supported cultures in the provided <see cref="TenantInfo"/>
        /// </summary>
        public static CultureInfo GetCulture(GenerateMarkupArguments args, TenantInfo tenantInfo)
        {
            // Some validation
            if (args.Culture != null && tenantInfo.PrimaryLanguageId != args.Culture && tenantInfo.SecondaryLanguageId != args.Culture && tenantInfo.TernaryLanguageId != args.Culture)
            {
                throw new BadRequestException($"Culture {args.Culture} is not supported in this company");
            }

            var culture = CultureInfo.CurrentUICulture;

            if (!string.IsNullOrWhiteSpace(args.Culture))
            {
                try
                {
                    culture = new CultureInfo(args.Culture, false);
                }
                catch (CultureNotFoundException)
                {
                    throw new BadRequestException($"Culture {args.Culture} does not exist");
                }
            }

            return(culture);
        }
    void SetTenantIdMaxLength()
    {
        try
        {
            _connection.Open();
            var tenant1 = new TenantInfo("abc", "abc", "abc",
                                         "DataSource=testdb.db", null);

            var _options = new DbContextOptionsBuilder <TestTenantIdConstraintsTypeDbContext>()
                           .UseSqlite(_connection)
                           .Options;

            using (var db = new TestTenantIdConstraintsTypeDbContext(tenant1, _options))
            {
                var entityType = db.Model.GetEntityTypes().Where(e => e.ClrType == typeof(Post)).Single();
                var maxLength  = entityType.FindProperty("TenantId").GetMaxLength();
                Assert.Equal(Constants.TenantIdMaxLength, maxLength);

                entityType = db.Model.GetEntityTypes().Where(e => e.ClrType == typeof(ThingWithTenantId)).Single();
                maxLength  = entityType.FindProperty("TenantId").GetMaxLength();
                Assert.Equal(Constants.TenantIdMaxLength, maxLength);

                entityType = db.Model.GetEntityTypes().Where(e => e.ClrType == typeof(ThingWithHigherTenantIdMaxLength)).Single();
                maxLength  = entityType.FindProperty("TenantId").GetMaxLength();
                Assert.Equal(Constants.TenantIdMaxLength, maxLength);

                entityType = db.Model.GetEntityTypes().Where(e => e.ClrType == typeof(ThingWithLowerTenantIdMaxLength)).Single();
                maxLength  = entityType.FindProperty("TenantId").GetMaxLength();
                Assert.Equal(Constants.TenantIdMaxLength, maxLength);
            }
        }
        finally
        {
            _connection.Close();
        }
    }
Esempio n. 17
0
        public void CompileWorkflow(TenantInfo tenant, long workflowId, string workflowName)
        {
            using (tenant.GetTenantAdminContext( ))
                using (new MemoryGuard(2 * TenantHealthHelpers.OneGb, ClearSelectedCaches))
                    using (new MemoryGuard(3 * TenantHealthHelpers.OneGb, TenantHealthHelpers.ClearAllCaches))
                        using (new MemoryLogger(new KeyValuePair <string, object>("Tenant", tenant.TenantName), new KeyValuePair <string, object>("Workflow Id", workflowId)))
                        {
                            // Load workflow
                            Workflow workflow = Factory.EntityRepository.Get <Workflow>(workflowId);
                            Assert.That(workflow, Is.Not.Null, "Workflow entity not null");

                            // Compile workflow
                            var metadata = new WorkflowMetadata(workflow);

                            // Check for validation errors
                            string messages = null;
                            if (metadata.ValidationMessages != null)
                            {
                                messages = string.Join("\r\n", metadata.ValidationMessages);
                            }

                            Assert.That(metadata.HasViolations, Is.False, messages);
                        }
        }
        public void AddUserLoginIndex()
        {
            var tenant1 = new TenantInfo
            {
                Id               = "abc",
                Identifier       = "abc",
                Name             = "abc",
                ConnectionString = "DataSource=testDb.db"
            };

            using var c = new TestIdentityDbContext(tenant1);

            var props = new List <IProperty>
            {
                c.Model.FindEntityType(typeof(IdentityUserLogin <string>))?.FindProperty("LoginProvider") !,
                c.Model.FindEntityType(typeof(IdentityUserLogin <string>))?.FindProperty("ProviderKey") !,
                c.Model.FindEntityType(typeof(IdentityUserLogin <string>))?.FindProperty("TenantId") !
            };

            var index = c.Model.FindEntityType(typeof(IdentityUserLogin <string>))?.FindIndex(props);

            Assert.NotNull(index);
            Assert.True(index !.IsUnique);
        }
Esempio n. 19
0
    public void GetTenantContextIfExists()
    {
        var ti = new TenantInfo {
            Id = "test"
        };
        var tc = new MultiTenantContext <TenantInfo>();

        tc.TenantInfo = ti;

        var services = new ServiceCollection();

        services.AddScoped <IMultiTenantContextAccessor <TenantInfo> >(_ => new MultiTenantContextAccessor <TenantInfo> {
            MultiTenantContext = tc
        });
        var sp = services.BuildServiceProvider();

        var httpContextMock = new Mock <HttpContext>();

        httpContextMock.Setup(c => c.RequestServices).Returns(sp);

        var mtc = httpContextMock.Object.GetMultiTenantContext <TenantInfo>();

        Assert.Same(tc, mtc);
    }
Esempio n. 20
0
    public void CreateOptionsWithTenantAction(string name)
    {
        var ti = new TenantInfo("test-id-123", null, null, null, null);
        var tc = new MultiTenantContext();

        tc.TenantInfo = ti;
        var tca = new TestMultiTenantContextAccessor(tc);

        var services = new ServiceCollection();

        services.AddTransient <IMultiTenantContextAccessor>(_sp => tca);
        services.Configure <InMemoryStoreOptions>(name, o => o.DefaultConnectionString      = $"{name}_begin");
        services.PostConfigure <InMemoryStoreOptions>(name, o => o.DefaultConnectionString += "end");
        var sp = services.BuildServiceProvider();

        Action <InMemoryStoreOptions, TenantInfo> tenantConfig = (o, _ti) => o.DefaultConnectionString += $"_{_ti.Id}_";

        var factory = ActivatorUtilities.
                      CreateInstance <MultiTenantOptionsFactory <InMemoryStoreOptions> >(sp, new [] { tenantConfig });

        var options = factory.Create(name);

        Assert.Equal($"{name}_begin_{ti.Id}_end", options.DefaultConnectionString);
    }
        public async Task <bool> TryAddAsync(TenantInfo tenantInfo)
        {
            var result = tenantMap.TryAdd(tenantInfo.Identifier, tenantInfo);

            return(await Task.FromResult(result));
        }
Esempio n. 22
0
 public BlogContext(TenantInfo tenantInfo, DbContextOptions options) : base(tenantInfo, options)
 {
 }
Esempio n. 23
0
 public BlogContext(TenantInfo tenantInfo) : base(tenantInfo)
 {
 }
Esempio n. 24
0
 public NonDerivedIdenityDbContext(TenantInfo tenantInfo, DbContextOptions options)
     : base(options)
 {
     TenantInfo = tenantInfo;
 }
Esempio n. 25
0
        /*
         * Callback function when an authorization code is received
         */

        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            notification.AuthenticationTicket.Properties.ExpiresUtc   = DateTime.UtcNow.AddMinutes(AuthTicketExpiresInMinutes);
            notification.AuthenticationTicket.Properties.AllowRefresh = AuthTicketAllowRefresh;

            HttpContext.Current.User = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            // Extract the code from the response notification
            var    code           = notification.Code;
            string signedInUserId = notification.AuthenticationTicket.Identity.FindFirst("userId").Value;

            //ClaimTypes.NameIdentifier).Value;

            TokenCache userTokenCache = new MSALSessionCache(signedInUserId, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); //CacheFactoryFunc().Invoke();//
            //TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();

            ConfidentialClientApplication context = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null);
            AuthenticationResult          user    = await context.AcquireTokenByAuthorizationCodeAsync(code, new[] { Scopes });

            //HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] = notification.OwinContext.Environment["System.Web.HttpContextBase"];


            //check policy
            string fullPatch  = notification.AuthenticationTicket.Properties.RedirectUri;
            string tenantName = fullPatch.Split('/').Where(x => x.Length > 0).ToList()[2];
            Tenant tenant     = _dbContext.Tenants.FirstOrDefault(x => x.DomainName.ToLower() == tenantName.ToLower());

            if (tenant == null)
            {
                return;
            }

            if (tenant.DomainName.ToLower() == "Admin".ToLower())
            {
                _serviceId = ConfigurationManager.AppSettings["ServiceId"];
            }
            else
            {
                TenantInfo tenantInfo = _dbContext.TenantInfos.FirstOrDefault(x => x.TenantId == tenant.Id && x.Key == "MyDNVGLServiceId");
                if (tenantInfo != null && !string.IsNullOrEmpty(tenantInfo.Value))
                {
                    _serviceId = tenantInfo.Value;
                }
            }

            if (string.IsNullOrEmpty(_serviceId))
            {
                return;
            }

            var policy = new Policy();

            try
            {
                policy = await _veracityApiHelper.GetPolicyModel(user.AccessToken, _serviceId);
            }
            catch
            {
                notification.OwinContext.Authentication.SignOut();
                return;
            }

            if ((HttpStatusCode)policy.statusCode == HttpStatusCode.NoContent)
            {
                //add local roles
                var     ctx         = HttpContext.Current.GetOwinContext();
                string  myDnvglId   = ctx.Authentication.User.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;
                var     tenantId    = _dbContext.Tenants.FirstOrDefault(x => x.DomainName.ToLower() == tenantName.ToLower())?.Id;
                AppUser loginedUser = _dbContext.AppUsers.FirstOrDefault(u => u.MyDnvglUserId == myDnvglId && u.TenantId == tenantId);
                if (loginedUser == null)
                {
                    return;
                }
                var roles = _dbContext.AppUsers.FirstOrDefault(u => u.Id == loginedUser.Id && u.TenantId == loginedUser.TenantId)?.Roles.Select(r => r.RoleId).ToList();

                var claims = notification.AuthenticationTicket.Identity;
                foreach (var role in roles)
                {
                    claims.AddClaim(new Claim(ClaimTypes.Role, role));
                }

                //Replace claim's 'userId' from MyDnvglId to local UserID
                claims.RemoveClaim(claims.FindFirst(ClaimTypes.NameIdentifier));
                claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginedUser.Id));

                //add access token into claims
                claims.AddClaim(new Claim("AccessToken", user.AccessToken));

                notification.OwinContext.Authentication.SignIn(new AuthenticationProperties {
                    IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10)
                }, claims);
            }
            else
            {
                notification.OwinContext.Authentication.SignOut();
                string strRedirectUrl         = policy.url;
                bool   isHaveEmptyRedirectUrl =
                    strRedirectUrl.Split(new string[] { "?", "&" }, StringSplitOptions.None)
                    .Any(x => x.Equals("returnUrl="));
                if (isHaveEmptyRedirectUrl)
                {
                    strRedirectUrl = strRedirectUrl.Replace("returnUrl=", "returnUrl=" + fullPatch);
                }
                HttpContext.Current.Response.Redirect(strRedirectUrl);
            }

            //AppUser testUser = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<AppUser>>().FindByName(notification.Request.User.GetPowerBIAppAuthenticationIdentity().GetUserName());

            //try
            //{
            //    //await ClientFactory.CreateClient(RedirectUri).My.ValidatePolicies();
            //    notification.OwinContext.Authentication.SignIn(notification.AuthenticationTicket.Identity);
            //}
            //catch (ServerException ex)
            //{
            //    //if (ex.Status == HttpStatusCode.NotAcceptable)
            //    //{
            //    //    notification.Response.Redirect(ex.GetErrorData<ValidationError>().Url); //Getting the redirect url from the error message.
            //    //    notification.HandleResponse(); //Mark the notification as handled to allow the redirect to happen.
            //    //}
            //}
        }
 public TestDbContextWithExistingGlobalFilter(TenantInfo tenantInfo, DbContextOptions options) : base(tenantInfo, options)
 {
 }
 public TestDbContextWithExistingGlobalFilter(TenantInfo tenantInfo) : base(tenantInfo)
 {
 }
 public TestBlogDbContext(TenantInfo tenantInfo) : base(tenantInfo)
 {
 }
 public StoreDbContext(DbContextOptions options, TenantInfo tenantInfo) : base(options)
 {
     this.tenantInfo = tenantInfo;
 }
 public Task <bool> TryAddAsync(TenantInfo tenantInfo)
 {
     throw new NotImplementedException();
 }