Esempio n. 1
0
        private static void InitializeLocalDatabases()
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"InitializeLocalDatabases.");

            ContextMaster.Initialize();
            ContextDesktop.Initialize(AffinityConfigurationDesktop.GetDatabaseConnectionStringBuilder(AffinityConfiguration.DeploymentLocation).ConnectionString);

            using (var contextDesktop = new ContextDesktop(AffinityConfigurationDesktop.GetDatabaseConnectionStringBuilder(AffinityConfiguration.DeploymentLocation).ConnectionString))
            {
            }

            using (var contextMaster = new ContextMaster())
            {
                var tenants = contextMaster.Tenants.ToList();

                foreach (var tenant in tenants)
                {
                    ContextTenant.Initialize(tenant.DatabaseConnectionString, true);

                    using (var contextTenant = new ContextTenant(tenant.DatabaseConnectionString))
                    {
                        contextTenant.Cultures.ToString();
                    }
                }
            }
        }
Esempio n. 2
0
        public static bool GetTenants(out List <Tenant> tenants, out Exception exception)
        {
            var result = false;

            tenants   = null;
            exception = null;

            try
            {
                //if (AffinityConfiguration.IsConfigurationDebug) { Debugger.Break(); }

                using (var context = new ContextMaster())
                {
                    tenants = context
                              .Tenants
                              .AsNoTracking()
                              .Include(t => t.TenantSubscriptions)
                              .Where(t => (t.TenantSubscriptions.Any(ts => ts.IsActive)))
                              .ToList()
                              .Where(t => t.TenantSubscriptions.Any(ts => ts.NumberOfPagesRemaining > 0))
                              .ToList();
                }

                result = true;
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 3
0
        public static bool GetTenantByDomain(string domain, out Tenant tenant, out Exception exception)
        {
            var result = false;

            tenant    = null;
            exception = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    tenant = context.Tenants.AsNoTracking().Include(t => t.TenantSubscriptions).SingleOrDefault(t => t.Domain == domain);

                    if (tenant == null)
                    {
                        throw (new DomainNotFoundException());
                    }

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
        public static bool GetTenantSubscriptionById(MasterUserSession MasterUserSession, long id, out TenantSubscription tenantsubscription, out Exception exception)
        {
            var result = false;

            tenantsubscription = null;
            exception          = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    tenantsubscription = context.TenantSubscriptions.AsNoTracking().SingleOrDefault(t => t.Id == id);

                    if (tenantsubscription == null)
                    {
                        throw (new RowNotFoundException());
                    }

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
        public static bool GetTenantSubscriptionById(MasterUserSession MasterUserSession, long id, out List <TenantSubscription> tenantsubscription, out Exception exception)
        {
            var result = false;

            tenantsubscription = null;
            exception          = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    tenantsubscription = context.TenantSubscriptions.AsNoTracking().Where(x => x.Id == id).OrderByDescending(x => x.Id).ToList();
                    if (tenantsubscription == null)
                    {
                        throw (new RowNotFoundException());
                    }
                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 6
0
        //public static bool UpdateUser(MasterUserSession masterUserSession, MasterUser masteruser, out Exception exception)
        //{
        //    bool result = false;
        //    exception = null;
        //    try
        //    {
        //        using (var context = new ContextMaster())
        //        {
        //            context.Users.Attach(masteruser);
        //            context.Entry(masteruser).State = System.Data.Entity.EntityState.Modified;
        //            context.SaveChanges();
        //            context.Dispose();
        //            result = true;
        //        }
        //    }
        //    catch (Exception ex) {
        //        exception = ex;
        //    }
        //    return (result);

        //}
        public static bool AddUser(MasterUserSession masterUserSession, MasterUser masteruser, out Exception exception)
        {
            bool result = false;

            exception = null;
            try
            {
                using (var context = new ContextMaster())
                {
                    if (masteruser.DateTimeCreated != null)
                    {
                        masteruser.DateTimeCreated = DateTime.UtcNow;
                    }
                    context.Users.Add(masteruser);
                    context.SaveChanges();
                    context.Dispose();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 7
0
        public static bool UpdateUserRoles(MasterUserSession masterUserSession, long userid, List <MasterRoleType> roletypes, out Exception exception)
        {
            bool result = false;

            exception = null;
            try
            {
                var context = new ContextMaster();
                List <MasterUserRole> userroles = context.UserRoles.Where(item => item.UserId == userid).ToList();//context.UserRoles.Where(item=>item.UserId==((long)Convert.ToInt16(roletypes.Any()))).ToList();
                foreach (var item in userroles)
                {
                    //context.UserRoles.Remove(item);
                    context.Entry(item).State = System.Data.Entity.EntityState.Deleted;
                    context.SaveChanges();
                }
                context.Dispose();
                context = new ContextMaster();
                foreach (var item in roletypes)
                {
                    MasterUserRole userrole = new MasterUserRole();
                    userrole.UserId = userid;
                    userrole.RoleId = Convert.ToInt16(item);
                    context.UserRoles.Add(userrole);
                    context.SaveChanges();
                }
                context.Dispose();
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 8
0
        public static bool SignOut(string token, out Exception exception)
        {
            var result = false;

            exception = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    var session = context.Sessions.SingleOrDefault(s => s.Token == token);
                    if (session == null)
                    {
                        throw (new TokenInvalidException());
                    }

                    session.DateTimeExpiration = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(1));

                    context.SaveChanges();

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
        public static bool GetActiveTenantSubscriptionById(MasterUserSession MasterUserSession, long id, out TenantSubscription tenantsubscription, out Exception exception)
        {
            var result = false;

            tenantsubscription = null;
            exception          = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    tenantsubscription = context.TenantSubscriptions.AsNoTracking().Where(x => ((x.TenantId == id) && (x.IsActive == true))).FirstOrDefault();
                    if (tenantsubscription == null)
                    {
                        tenantsubscription = new TenantSubscription();
                    }                                                                                 //throw (new RowNotFoundException()); }
                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 10
0
        public static List <string> GetAllRole()
        {
            List <string> roles = new List <string>();

            using (var context = new ContextMaster())
            {
                var role = context.Roles.ToList();
            }
            return(roles);
        }
Esempio n. 11
0
 //TOBE DELETED
 public static void GetAllUsers()
 {
     using (var context = new ContextMaster())
     {
         var user = context.Users.First();
         user.Email = user.Email + " LOL";
         context.SaveChanges();
         //return context.Users.First().Email;
     }
 }
        public static bool UpdateTenantSubscription(MasterUserSession MasterUserSession, TenantSubscription tenantsubscription, out TenantSubscription outtenantsubscription, out Exception exception)
        {
            var result = false;

            outtenantsubscription = null;
            exception             = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    var temp = new TenantSubscription();

                    temp = context.TenantSubscriptions.FirstOrDefault(t => t.Id == tenantsubscription.Id);

                    temp.IsDemo   = tenantsubscription.IsDemo;
                    temp.IsActive = tenantsubscription.IsActive;

                    temp.DateTimeStart   = tenantsubscription.DateTimeStart;
                    temp.DateTimeExpires = tenantsubscription.DateTimeExpires;

                    temp.NumberOfFormsAllowed     = tenantsubscription.NumberOfFormsAllowed;
                    temp.NumberOfUsersAllowed     = tenantsubscription.NumberOfUsersAllowed;
                    temp.NumberOfPagesAllowed     = tenantsubscription.NumberOfPagesAllowed;
                    temp.NumberOfTemplatesAllowed = tenantsubscription.NumberOfTemplatesAllowed;

                    temp.NumberOfFormsUsed     = tenantsubscription.NumberOfFormsUsed;
                    temp.NumberOfPagesUsed     = tenantsubscription.NumberOfPagesUsed;
                    temp.NumberOfUsersUsed     = tenantsubscription.NumberOfUsersUsed;
                    temp.NumberOfTemplatesUsed = tenantsubscription.NumberOfTemplatesUsed;

                    temp.AllowScanning          = tenantsubscription.AllowScanning;
                    temp.AllowBranding          = tenantsubscription.AllowBranding;
                    temp.AllowTemplateWorkflows = tenantsubscription.AllowTemplateWorkflows;

                    context.TenantSubscriptions.Attach(temp);
                    context.Entry(temp).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                    outtenantsubscription = temp;
                }

                result = true;
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 13
0
        public static bool GetMasterUserByIdTemporaryFunction(out HouseOfSynergy.AffinityDms.Entities.Master.MasterUser user, out Exception exception)
        {
            user      = null;
            exception = null;
            bool result = false;

            try
            {
                var context = new ContextMaster();
                user   = context.Users.First();
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 14
0
        public static bool UpdateUser(MasterUserSession masterUserSession, MasterUser masteruser, out MasterUser outmasteruser, out Exception exception)
        {
            bool result = false;

            outmasteruser = null;
            exception     = null;
            try
            {
                using (var context = new ContextMaster())
                {
                    MasterUser user = new MasterUser();
                    user                   = context.Users.Where(x => x.Id == masteruser.Id).FirstOrDefault();
                    user.Address1          = masteruser.Address1;
                    user.Address2          = masteruser.Address2;
                    user.City              = masteruser.City;
                    user.Country           = masteruser.Country;
                    user.Email             = masteruser.Email;
                    user.NameFamily        = masteruser.NameFamily;
                    user.NameGiven         = masteruser.NameGiven;
                    user.PasswordHash      = masteruser.PasswordHash;
                    user.PasswordSalt      = masteruser.PasswordSalt;
                    user.PhoneMobile       = masteruser.PhoneMobile;
                    user.PhoneWork         = masteruser.PhoneWork;
                    user.ActiveDirectoryId = masteruser.ActiveDirectoryId;
                    // user.UserName = masteruser.UserName;
                    user.AuthenticationType = masteruser.AuthenticationType;
                    user.ZipOrPostCode      = masteruser.ZipOrPostCode;
                    context.Users.Attach(user);
                    context.Entry(user).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                    context.Dispose();
                    outmasteruser = user;
                    result        = true;
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 15
0
        public static bool GetAllUsers(MasterUserSession masterUserSession, out List <MasterUser> masteruser, out Exception exception)
        {
            masteruser = null;
            bool result = false;

            exception = null;
            try
            {
                using (var context = new ContextMaster())
                {
                    masteruser = context.Users.Include("UserRoles").Include("Roles").Select(x => x).ToList();
                    context.Dispose();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 16
0
        public static bool GetUserUserById(MasterUserSession masterUserSession, long id, out MasterUser masteruser, out Exception exception)
        {
            masteruser = null;
            bool result = false;

            exception = null;
            try
            {
                using (var context = new ContextMaster())
                {
                    masteruser = context.Users.Where(x => x.Id == id).Select(x => x).FirstOrDefault();
                    context.Dispose();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 17
0
        public static bool CreateSubscription(MasterUserSession MasterUserSession, Subscription subscription, out Subscription outsubscription, out Exception exception)
        {
            var result = false;

            //tenant = null;
            outsubscription = null;
            exception       = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            outsubscription = context.Subscriptions.Add(subscription);
                            context.SaveChanges();
                            subscription.MasterSubscriptionId = subscription.Id;
                            context.SaveChanges();

                            transaction.Commit();

                            result = true;
                        }
                        catch (Exception e)
                        {
                            exception = e;
                            transaction.Rollback();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 18
0
        public static bool GetSubcriptions(MasterUserSession MasterUserSession, out List <Subscription> subscriptions, out Exception exception)
        {
            var result = false;

            subscriptions = null;
            exception     = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    subscriptions = context.Subscriptions.AsNoTracking().ToList();

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 19
0
        public static bool GetTenants(out List <Tenant> tenants, out Exception exception)
        {
            var result = false;

            tenants   = null;
            exception = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    tenants = context.Tenants.AsNoTracking().Include(t => t.TenantSubscriptions).ToList();

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
        public static bool GetTenantSubcriptionsByTenantId(MasterUserSession MasterUserSession, long tenantid, out List <TenantSubscription> tenantsubscriptions, out Exception exception)
        {
            var result = false;

            tenantsubscriptions = null;
            exception           = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    //todo
                    tenantsubscriptions = context.TenantSubscriptions.AsNoTracking().ToArray().Where(t => t.TenantId == tenantid).OrderByDescending(x => x.Id).ToList();

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 21
0
        public static bool CreateTenant(MasterUserSession tenantUserSession, Tenant tenant, out Tenant tenantMaster, out Exception exception)
        {
            var    result           = false;
            Tenant tenantMasterTemp = null;

            exception    = null;
            tenantMaster = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            var count = context.Tenants.Count(t => t.Domain.ToLower() == tenant.Domain.ToLower());
                            if (count == 1)
                            {
                                throw (new Exception("The provided domain already exists in the system."));
                            }
                            else if (count > 1)
                            {
                                throw (new Exception("The provided domain exists multiple times in the system."));
                            }

                            tenant.DatabaseConnectionString = AzureDBConnectionStringBuilder(tenant.DatabaseConnectionString);
                            tenantMasterTemp = context.Tenants.Add(tenant);
                            context.SaveChanges();
                            tenantMasterTemp.MasterTenantId       = tenantMasterTemp.Id;
                            context.Entry(tenantMasterTemp).State = EntityState.Modified;
                            context.SaveChanges();
                            if (tenantMasterTemp != null)
                            {
                                var tenantTenant = tenantMasterTemp.Clone();

                                tenantTenant.Id                 = 0;
                                tenantTenant.MasterTenantId     = tenant.Id;
                                tenantTenant.TenantType         = EntityMasterTenantType.Tenant;
                                tenantTenant.AuthenticationType = AuthenticationType.None;
                                ContextTenant.Initialize(tenantTenant.DatabaseConnectionString);

                                // Commented out by Raheel to find a better way to automate the process.
                                //using (var contexttenant = new ContextTenant (tenantTenant.DatabaseConnectionString))
                                //{
                                //	bool seederresult = DataLayer.Seeders.SeederTenant.Seed (contexttenant, tenantTenant, out exception);

                                //	if (seederresult)
                                //	{
                                //		transaction.Commit ();

                                //		tenantMaster = tenantMasterTemp;
                                //	}
                                //	else
                                //	{
                                //		transaction.Rollback ();
                                //	}
                                //}
                            }
                        }
                        catch (Exception ex)
                        {
                            exception = ex;
                            transaction.Rollback();
                            tenantMaster = tenant;
                        }
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                exception    = e;
                tenantMaster = tenant;
            }

            return(result);
        }
        public static bool CreateTenantSubscriptionAndDeactivateExistingTenantSubscription(MasterUserSession MasterUserSession, long existingtenantsubscriptionid, Subscription subscriptionMaster, TenantSubscription tenantsubscriptionMaster, out Exception exception)
        {
            var result = false;

            exception = null;
            //System.Data.Common.DbTransaction Tran = null;
            //ContextMaster context = new ContextMaster();
            //context.ObjectContext.Connection.Open();
            //Tran = context.ObjectContext.Connection.BeginTransaction();
            DbContextTransaction masterTrans = null;
            DbContextTransaction tenantTrans = null;

            using (var contextMaster = new ContextMaster())
            {
                try
                {
                    using (masterTrans = contextMaster.Database.BeginTransaction())
                    {
                        try
                        {
                            var existingSubscriptions = contextMaster.TenantSubscriptions.Where(x => (x.TenantId == existingtenantsubscriptionid) && (x.IsActive == true)).ToList();

                            foreach (var existingSubnscription in existingSubscriptions)
                            {
                                existingSubnscription.IsActive = false;
                                contextMaster.SaveChanges();
                            }

                            contextMaster.TenantSubscriptions.Add(tenantsubscriptionMaster);
                            contextMaster.SaveChanges();
                            tenantsubscriptionMaster.MasterTenantSubscriptionId = tenantsubscriptionMaster.Id;
                            contextMaster.Entry(tenantsubscriptionMaster).State = EntityState.Modified;
                            contextMaster.SaveChanges();

                            var tenant = contextMaster.Tenants.SingleOrDefault(x => x.Id == tenantsubscriptionMaster.TenantId);

                            if (tenant == null)
                            {
                                throw (new Exception("Unable to Find Tenant in the Master DB."));
                            }

                            using (var contextTenant = new ContextTenant(tenant.DatabaseConnectionString))
                            {
                                try
                                {
                                    using (tenantTrans = contextTenant.Database.BeginTransaction())
                                    {
                                        var existingtenantsubscriptionstenant = contextTenant.TenantSubscriptions.Where(x => (x.IsActive == true)).ToList();

                                        foreach (var existingSubscriptionTenant in existingtenantsubscriptionstenant)
                                        {
                                            existingSubscriptionTenant.IsActive = false;
                                            contextTenant.SaveChanges();
                                        }

                                        var subscriptionTenant = contextTenant.Subscriptions.SingleOrDefault(s => s.MasterSubscriptionId == subscriptionMaster.Id);

                                        if (subscriptionTenant == null)
                                        {
                                            subscriptionTenant    = subscriptionMaster.Clone();
                                            subscriptionTenant.Id = 0;
                                            subscriptionTenant.MasterSubscriptionId = subscriptionMaster.Id;
                                            subscriptionTenant.SubscriptionType     = EntityMasterTenantType.Tenant;
                                            contextTenant.Subscriptions.Add(subscriptionTenant);
                                            contextTenant.SaveChanges();
                                        }
                                        else
                                        {
                                            //subscriptionTenant = subscription.Clone();
                                            //subscriptionTenant.MasterTenantId = subscription.Id;//Yeh Maam Nay kerwaya hai.
                                            //contextTenant.Entry(subscriptionTenant).State = EntityState.Modified;
                                            //contextTenant.SaveChanges();
                                        }

                                        var count = contextTenant.Tenants.Count();
                                        if (count != 1)
                                        {
                                            throw (new Exception($"The number of tenant entries found in the Tenant database was {count} instead of 1."));
                                        }
                                        var tenantTenant = contextTenant.Tenants.Single();

                                        var tenantsubscriptionTenant   = tenantsubscriptionMaster;
                                        var masterTenantSubscriptionId = contextMaster.TenantSubscriptions.AsNoTracking().Where(x => x.IsActive == true).FirstOrDefault().Id;
                                        tenantsubscriptionTenant.MasterTenantSubscriptionId = tenantsubscriptionMaster.Id;
                                        tenantsubscriptionTenant.Id                     = 0;
                                        tenantsubscriptionTenant.SubscriptionId         = subscriptionTenant.Id;
                                        tenantsubscriptionTenant.Tenant                 = null;
                                        tenantsubscriptionTenant.TenantId               = tenantTenant.Id;
                                        tenantsubscriptionTenant.TenantSubscriptionType = EntityMasterTenantType.Tenant;
                                        contextTenant.TenantSubscriptions.Add(tenantsubscriptionTenant);
                                        contextTenant.SaveChanges();



                                        try

                                        {
                                            tenantTrans.Commit();
                                            masterTrans.Commit();
                                        }
                                        catch
                                        {
                                            tenantTrans.Rollback();
                                            masterTrans.Rollback();
                                        }

                                        result = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    exception = ex;
                                    throw;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            exception = ex;
                            throw;
                            //Tran.Rollback();
                            //Tran.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                    masterTrans.Rollback();
                    tenantTrans.Rollback();
                    masterTrans.Dispose();
                    tenantTrans.Dispose();
                }
            }

            return(result);
        }
Esempio n. 23
0
        public static bool UpdateTenant(MasterUserSession tenantUserSession, Tenant tenant, out Tenant outtenant, out Exception exception)
        {
            var result = false;

            outtenant = null;
            exception = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    var count = context.Tenants.Count(t => t.Id == tenant.Id);
                    if (count == 0)
                    {
                        throw (new Exception("The provided tenant Id was not found."));
                    }

                    count = context.Tenants.Count(t => ((t.Id != tenant.Id) && (t.Domain.ToLower() == tenant.Domain.ToLower())));
                    if (count == 1)
                    {
                        throw (new Exception("The provided domain already exists in the system."));
                    }
                    else if (count > 1)
                    {
                        throw (new Exception("The provided domain exists multiple times in the system."));
                    }

                    var tempTenant = context.Tenants.Single(t => t.Id == tenant.Id);

                    tempTenant.CompanyName                    = tenant.CompanyName;
                    tempTenant.Domain                         = tenant.Domain;
                    tempTenant.ContactOwnerNameGiven          = tenant.ContactOwnerNameGiven;
                    tempTenant.ContactOwnerNameFamily         = tenant.ContactOwnerNameFamily;
                    tempTenant.ContactOwnerAddress            = tenant.ContactOwnerAddress;
                    tempTenant.ContactOwnerCity               = tenant.ContactOwnerCity;
                    tempTenant.ContactOwnerState              = tenant.ContactOwnerState;
                    tempTenant.ContactOwnerZipCode            = tenant.ContactOwnerZipCode;
                    tempTenant.ContactOwnerCountry            = tenant.ContactOwnerCountry;
                    tempTenant.ContactOwnerPhone              = tenant.ContactOwnerPhone;
                    tempTenant.ContactOwnerFax                = tenant.ContactOwnerFax;
                    tempTenant.ContactOwnerEmail              = tenant.ContactOwnerEmail;
                    tempTenant.ContactAdministratorNameGiven  = tenant.ContactAdministratorNameGiven;
                    tempTenant.ContactAdministratorNameFamily = tenant.ContactAdministratorNameFamily;
                    tempTenant.ContactAdministratorAddress    = tenant.ContactAdministratorAddress;
                    tempTenant.ContactAdministratorCity       = tenant.ContactAdministratorCity;
                    tempTenant.ContactAdministratorState      = tenant.ContactAdministratorState;
                    tempTenant.ContactAdministratorZipCode    = tenant.ContactAdministratorZipCode;
                    tempTenant.ContactAdministratorCountry    = tenant.ContactAdministratorCountry;
                    tempTenant.ContactAdministratorPhone      = tenant.ContactAdministratorPhone;
                    tempTenant.ContactAdministratorFax        = tenant.ContactAdministratorFax;
                    tempTenant.ContactAdministratorEmail      = tenant.ContactAdministratorEmail;
                    tempTenant.ContactBillingNameGiven        = tenant.ContactBillingNameGiven;
                    tempTenant.ContactBillingNameFamily       = tenant.ContactBillingNameFamily;
                    tempTenant.ContactBillingAddress          = tenant.ContactBillingAddress;
                    tempTenant.ContactBillingCity             = tenant.ContactBillingCity;
                    tempTenant.ContactBillingState            = tenant.ContactBillingState;
                    tempTenant.ContactBillingZipCode          = tenant.ContactBillingZipCode;
                    tempTenant.ContactBillingCountry          = tenant.ContactBillingCountry;
                    tempTenant.ContactBillingPhone            = tenant.ContactBillingPhone;
                    tempTenant.ContactBillingFax              = tenant.ContactBillingFax;
                    tempTenant.ContactBillingEmail            = tenant.ContactBillingEmail;
                    tempTenant.ContactTechnicalNameGiven      = tenant.ContactTechnicalNameGiven;
                    tempTenant.ContactTechnicalNameFamily     = tenant.ContactTechnicalNameFamily;
                    tempTenant.ContactTechnicalAddress        = tenant.ContactTechnicalAddress;
                    tempTenant.ContactTechnicalCity           = tenant.ContactTechnicalCity;
                    tempTenant.ContactTechnicalState          = tenant.ContactTechnicalState;
                    tempTenant.ContactTechnicalZipCode        = tenant.ContactTechnicalZipCode;
                    tempTenant.ContactTechnicalCountry        = tenant.ContactTechnicalCountry;
                    tempTenant.ContactTechnicalPhone          = tenant.ContactTechnicalPhone;
                    tempTenant.ContactTechnicalFax            = tenant.ContactTechnicalFax;
                    tempTenant.ContactTechnicalEmail          = tenant.ContactTechnicalEmail;

                    context.Tenants.Attach(tempTenant);
                    //context.Entry(tempTenant).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                    outtenant = tempTenant;
                }

                result = true;
            }
            catch (Exception e)
            {
                exception = e;
                outtenant = tenant;
            }

            return(result);
        }
        public static bool CreateTenantSubscription(MasterUserSession MasterUserSession, TenantSubscription tenantsubscription, out TenantSubscription outtenantsubscription, out Exception exception)
        {
            var result = false;

            //tenant = null;
            outtenantsubscription = null;
            exception             = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    DbContextTransaction mastertrans = null;
                    DbContextTransaction tenanttrans = null;
                    try
                    {
                        using (mastertrans = context.Database.BeginTransaction())
                        {
                            outtenantsubscription = context.TenantSubscriptions.Add(tenantsubscription);
                            context.SaveChanges();
                            var tenant       = context.Tenants.Where(x => x.Id == tenantsubscription.TenantId).FirstOrDefault();
                            var subscription = context.Subscriptions.Where(x => x.Id == tenantsubscription.SubscriptionId).FirstOrDefault();
                            using (var contexttenant = new ContextTenant(tenant.DatabaseConnectionString))
                            {
                                try
                                {
                                    using (tenanttrans = contexttenant.Database.BeginTransaction())
                                    {
                                        var mastersubscriptionid = subscription.Id;
                                        subscription.Id = 0;
                                        contexttenant.Subscriptions.Add(subscription);
                                        contexttenant.SaveChanges();
                                        tenantsubscription.SubscriptionId = subscription.Id;
                                        contexttenant.TenantSubscriptions.Add(tenantsubscription);
                                        contexttenant.SaveChanges();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    exception = ex;
                                    throw ex;
                                }
                            }
                            tenanttrans.Commit();
                            mastertrans.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (mastertrans != null)
                        {
                            mastertrans.Rollback();
                            mastertrans.Dispose();
                        }
                        if (tenanttrans != null)
                        {
                            tenanttrans.Rollback();
                            tenanttrans.Dispose();
                        }
                        exception = ex;
                        throw ex;
                    }
                }
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            return(result);
        }
Esempio n. 25
0
        private static void GenerateDocuments()
        {
            Tenant tenant = null;
            var    random = new System.Random();

            try
            {
                using (var contextMaster = new ContextMaster())
                {
                    tenant = contextMaster
                             .Tenants
                             .AsNoTracking()
                             .Include(t => t.Users)
                             .First();
                }

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            //var countTemplates = 10;

                            //for (int i = 0; i < countTemplates; i++)
                            //{
                            //	var elements = new List<TemplateElement> ();
                            //	var template = new Template () { Title = "", Description = "", };
                            //	context.Templates.Add (template);
                            //	context.SaveChanges ();
                            //	template.Title = "Template " + template.Id.ToString ().PadLeft (long.MaxValue.ToString ().Length, '0');
                            //	context.SaveChanges ();

                            //	var file = PathUtilities.GetTempFile (".png", false);
                            //	using (var bitmap = new Bitmap (random.Next (500, 1000), random.Next (500, 1000), PixelFormat.Format32bppArgb))
                            //	{
                            //		using (var graphics = Graphics.FromImage (bitmap))
                            //		{
                            //			graphics.SetQualityHighest ();
                            //			graphics.Clear (Color.White);

                            //			var size = SizeF.Empty;
                            //			TemplateElement element = null;
                            //			var font = new Font (FontFamily.GenericMonospace, 12F);

                            //			element = new TemplateElement () { Name = "", Description = "", X = 0, Y = 0, X2 = 0, Y2 = 0, Width = "", Height = "", TemplateId = template.Id, };
                            //			template.Elements.Add (element);
                            //			context.SaveChanges ();
                            //			element.Name = "Element " + element.Id.ToString ().PadLeft (long.MaxValue.ToString ().Length, '0');
                            //			context.SaveChanges ();
                            //			element.Value = "INVOICE";
                            //			element.ElementIndexType = 1;
                            //			element.ElementType = (int) ElementType.Label;
                            //			size = graphics.MeasureString (element.Value, font);
                            //			element.X = 10;
                            //			element.Y = 10;
                            //			element.X2 = element.X + size.Width;
                            //			element.Y2 = element.X + size.Height;
                            //			//element.Width
                            //			context.SaveChanges ();
                            //			elements.Add (element);
                            //			graphics.DrawRectangle (Pens.Black, RectangleF.FromLTRB (element.X, element.Y, element.X2, element.Y2));
                            //			graphics.DrawString (element.Value, font, Brushes.Black, element.X, element.Y);

                            //			element = new TemplateElement () { Name = "", Description = "", X = 0, Y = 0, X2 = 0, Y2 = 0, Width = "", Height = "", TemplateId = template.Id, };
                            //			template.Elements.Add (element);
                            //			context.SaveChanges ();
                            //			element.Name = "Element " + element.Id.ToString ().PadLeft (long.MaxValue.ToString ().Length, '0');
                            //			context.SaveChanges ();
                            //			element.Value = "INV #:";
                            //			element.ElementIndexType = 1;
                            //			element.ElementType = (int) ElementType.Label;
                            //			size = graphics.MeasureString (element.Value, font);
                            //			element.X = 100;
                            //			element.Y = 50;
                            //			element.X2 = element.X + size.Width;
                            //			element.Y2 = element.X + size.Height;
                            //			//element.Width
                            //			context.SaveChanges ();
                            //			elements.Add (element);
                            //			graphics.DrawRectangle (Pens.Black, RectangleF.FromLTRB (element.X, element.Y, element.X2, element.Y2));
                            //			graphics.DrawString (element.Value, font, Brushes.Black, element.X, element.Y);
                            //		}

                            //		bitmap.Save (file.FullName, ImageFormat.Png);
                            //		Program.TemplateUpload (tenant, template, file);
                            //		//OcrTest.CreateTemplateFiles (tenant, template, file, elements);
                            //	}
                            //}

                            context.SaveChanges();
                            transaction.Commit();
                        }
                        catch (Exception exception)
                        {
                            transaction.Rollback();
                            Debug.Write(exception);
                            Debugger.Break();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Debug.Write(exception);
                Debugger.Break();
            }
        }
Esempio n. 26
0
        private static void TestDocumentAcl()
        {
            Exception         exception               = null;
            List <Document>   documentsRaheel         = null;
            List <Document>   documentsJunaid         = null;
            TenantUserSession tenantUserSessionRaheel = null;
            TenantUserSession tenantUserSessionJunaid = null;

            ContextMaster.Initialize();
            using (var context = new ContextMaster())
            {
                context.Tenants.ToList();
            }

            AuthenticationManagement.SignIn(SessionType.Mvc, "kloud-soft.com", "raheel.khan", Sha.GenerateHash("audience", GlobalConstants.EncodingCryptography, GlobalConstants.AlgorithmHashShaKind), IPAddress.Loopback.ToString(), "User Agent", 0, "Session Id", out tenantUserSessionRaheel, out exception);
            AuthenticationManagement.SignIn(SessionType.Mvc, "kloud-soft.com", "junaid.sayed", Sha.GenerateHash("audience", GlobalConstants.EncodingCryptography, GlobalConstants.AlgorithmHashShaKind), IPAddress.Loopback.ToString(), "User Agent", 0, "Session Id", out tenantUserSessionJunaid, out exception);

            documentsRaheel = DocumentManagement.GetDocuments
                              (
                tenantUserSession: tenantUserSessionRaheel,
                documentId: 23,
                documentIdType: DocumentIdType.Id,
                folderId: 3,
                documentResultVersionType: DocumentResultVersionType.All,
                includeDiscourse: false,
                includeDocumentElements: false,
                includeDocumentFragments: false,
                includeCreatorUser: false,
                includeCheckedOutUser: false,
                includeDocumentUsers: false,
                includeDocumentIndexes: false,
                includeDocumentTags: false,
                includeDocumentTagUsers: false,
                includeDocumentTemplates: false,
                includeDocumentCorrectiveIndexValues: false,
                isFinalized: null,
                skipRows: null,
                takeRows: null
                              );

            documentsJunaid = DocumentManagement.GetDocuments
                              (
                tenantUserSession: tenantUserSessionJunaid,
                documentId: 23,
                documentIdType: DocumentIdType.Id,
                folderId: 3,
                documentResultVersionType: DocumentResultVersionType.All,
                includeDiscourse: false,
                includeDocumentElements: false,
                includeDocumentFragments: false,
                includeCreatorUser: false,
                includeCheckedOutUser: false,
                includeDocumentUsers: false,
                includeDocumentIndexes: false,
                includeDocumentTags: false,
                includeDocumentTagUsers: false,
                includeDocumentTemplates: false,
                includeDocumentCorrectiveIndexValues: false,
                isFinalized: null,
                skipRows: null,
                takeRows: null
                              );

            Console.Write($"User: {tenantUserSessionRaheel.User.NameFull}:");
            foreach (var document in documentsRaheel)
            {
                Console.WriteLine();
                Console.Write($" - Name: {document.Name}");
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"User: {tenantUserSessionJunaid.User.NameFull}:");
            foreach (var document in documentsJunaid)
            {
                Console.WriteLine();
                Console.Write($" - Name: {document.Name}");
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Press any key to continue...");
            Console.ReadKey(true);
        }
Esempio n. 27
0
        private static void UpdateLiveTenantDatabases(IEnumerable <string> productionDomainsToBeUpdated)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"----------------------------------------------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"UpdateLiveTenantDatabases.");

            Uri uri;
            var encoding           = Encoding.UTF8;
            var tenantsMasterLive  = new List <Tenant>();
            var tenantsMasterLocal = new List <Tenant>();
            // var builderTenantLive = new SqlConnectionStringBuilder();
            var builderTenantLocal = new SqlConnectionStringBuilder();
            //var builderMasterLive = AffinityConfigurationMaster.GetDatabaseConnectionStringBuilder(DeploymentLocation.Live);
            var builderMasterLocal = AffinityConfigurationMaster.GetDatabaseConnectionStringBuilder(AffinityConfiguration.DeploymentLocation);

            if
            (
                (productionDomainsToBeUpdated.Any())
                &&
                (
                    productionDomainsToBeUpdated.All
                    (
                        d =>
                        (!string.IsNullOrWhiteSpace(d)) &&
                        (Uri.CheckHostName(d) == UriHostNameType.Dns) &&
                        (Uri.TryCreate(d, UriKind.RelativeOrAbsolute, out uri)) &&
                        (!uri.IsAbsoluteUri) &&
                        (!uri.UserEscaped)
                    )
                )
            )
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Domains selected to be updated:");
                Console.WriteLine();
                Console.Write(string.Join(Environment.NewLine, productionDomainsToBeUpdated.Select(d => $" - {d}")));
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Either no domains were passed in, or at least one of the domains");
                Console.WriteLine();
                Console.Write($"was empty, null or invalid. Domains should be in the form of: [xyz.com].");
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"The utility will now return.");

                return;
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"WARNING: This action cannot be undone!");
            Console.WriteLine();
            Console.Write($"Press [Y] to run the action, any other key to cancel: ");

            var consoleKeyInfo = Console.ReadKey(intercept: true);

            if (consoleKeyInfo.Key == ConsoleKey.Y)
            {
                Console.Write("Y");
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"WARNING: Once again, this action cannot be undone!");
                Console.WriteLine();
                Console.Write($"Press [Y] to run the action, any other key to cancel: ");

                consoleKeyInfo = Console.ReadKey(intercept: true);

                if (consoleKeyInfo.Key == ConsoleKey.Y)
                {
                    Console.Write("Y");
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.Write($"Well, you WERE warned! Continuing script execution...");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.Write($"Script execution cancelled. Phew!!!");

                    return;
                }
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Script execution cancelled. Phew!!!");

                return;
            }

            Program.InitializeLocalDatabases();

            var fileScript = new FileInfo(Assembly.GetExecutingAssembly().Location);

            fileScript = new FileInfo(Path.Combine(fileScript.Directory.FullName, @"..\..\..\HouseOfSynergy.AffinityDms.Library\Database\Script Schema Drop Create Data Insert.sql"));
            if (!fileScript.Exists)
            {
                throw (new FileNotFoundException($"File not found: {fileScript.FullName}.", fileScript.FullName));
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Getting live tenants from master...");
            using (var contextMasterLive = new ContextMaster(deploymentLocation: DeploymentLocation.Live))
            {
                tenantsMasterLive = contextMasterLive.Tenants.ToList();
            }

            var validDomains   = tenantsMasterLive.ConvertAll(t => t.Domain);
            var invalidDomains = productionDomainsToBeUpdated.Where(d => !validDomains.Contains(d));

            Console.WriteLine();
            Console.Write($"Domains found in the master database:");
            Console.WriteLine();
            Console.Write(string.Join(Environment.NewLine, validDomains.Select(d => $" - {d}")));

            if (invalidDomains.Any())
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"The following domains do not exist in the master database:");
                Console.WriteLine();
                Console.Write(string.Join(Environment.NewLine, invalidDomains.Select(d => $" - {d}")));
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"The utility will now return.");

                return;
            }

            tenantsMasterLive = tenantsMasterLive.Where(t => productionDomainsToBeUpdated.Contains(t.Domain)).ToList();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Updating live tenants...");
            foreach (var tenantMasterLive in tenantsMasterLive)
            {
                var tenantTenantLive       = tenantMasterLive.Clone();
                var databaseNameTenantLive = new SqlConnectionStringBuilder(tenantMasterLive.DatabaseConnectionString).InitialCatalog;

                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Tenant: [{tenantMasterLive.Domain}].");

                using (var contextMasterLocal = new ContextMaster())
                {
                    var tenantMasterLocal = contextMasterLocal.Tenants.SingleOrDefault(t => t.Domain.ToLower() == tenantMasterLive.Domain.ToLower());

                    builderTenantLocal = new SqlConnectionStringBuilder(tenantMasterLocal.DatabaseConnectionString);
                }

                // Generate Drop, Create & Seed Script.
                //builderTenantLocal = new SqlConnectionStringBuilder()
                //{
                //    DataSource = @"BENZFARAZ-PC\SQLEXPRESS",
                //    InitialCatalog = "AffinityDmsTenant_0000000000000000002",
                //    IntegratedSecurity = true,
                //    UserID = @"sa",
                //    Password = @"123456",
                //    MultipleActiveResultSets = false,
                //    PersistSecurityInfo = true
                //};

                // Generate Drop, Create & Seed Script.
                builderTenantLocal = new SqlConnectionStringBuilder()
                {
                    DataSource = @"Lenovo",
                    //DataSource = @"HOSLAPTOPHP\MSSQLS2016EXP",
                    InitialCatalog     = "AffinityDmsTenant_0000000000000000001",
                    IntegratedSecurity = true,
                    //UserID = @"",
                    //Password = @"",
                    //MultipleActiveResultSets = false,
                    PersistSecurityInfo = true
                };

                Program.GenerateScript(builderTenantLocal, databaseNameTenantLive, fileScript, encoding);

                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Execute script against the respective live tenant.");
                using (var contextTenantLive = new ContextTenant(tenantTenantLive.DatabaseConnectionString))
                {
                    var script = File.ReadAllText(fileScript.FullName, encoding);

                    var t = contextTenantLive.Tenants.ToList();

                    contextTenantLive.Database.CommandTimeout = 30 * 60;
                    contextTenantLive.Database.ExecuteSqlCommand(script);
                }

                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Correcting script parameters.");
                using (var contextTenantLive = new ContextTenant(tenantTenantLive.DatabaseConnectionString))
                {
                    tenantTenantLive.Id         = 1; // To update the single tenant row.
                    tenantTenantLive.TenantType = EntityMasterTenantType.Tenant;

                    contextTenantLive.Tenants.Attach(tenantTenantLive);
                    contextTenantLive.SaveChanges();
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Authentication using: [Salted password hashing with PBKDF2-SHA1].
        /// Implementation available at: [HouseOfSynergy.PowerTools.Library.Security.Cryptography.PasswordHash].
        /// The password should never reach here in plain text. It should b encrypted using Sha512 in TypeScript or JavaScript.
        /// A C# implementation of Sha512 is available at: [HouseOfSynergy.PowerTools.Library.Security.Cryptography.Sha].
        /// </summary>
        /// <param name="sessionType">The origin of the request.</param>
        /// <param name="username">Username in plain text.</param>
        /// <param name="passwordHash">Password from client hashed using Sha512.</param>
        /// <param name="token">The user object fetched.</param>
        /// <param name="exception">Populates an exception where applicable.</param>
        /// <returns></returns>
        public static bool SignIn
        (
            SessionType sessionType,
            string username,
            string passwordHash,
            string clientIpAddress,
            string userAgent,
            long ticks,
            string sessionId,
            out MasterUserSession masterUserSession,
            out Exception exception
        )
        {
            var           result          = false;
            var           now             = DateTime.UtcNow;
            MasterUser    userDatabase    = null;
            MasterSession sessionDatabase = null;

            exception         = null;
            masterUserSession = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    userDatabase = context.Users.SingleOrDefault(u => (u.UserName == username));
                    if (userDatabase == null)
                    {
                        throw (new UserNotFoundException());
                    }

                    if (!PasswordHash.ValidatePassword(passwordHash, userDatabase.PasswordHash))
                    {
                        throw (new AuthenticationException());
                    }

                    var token
                        = userDatabase.Id.ToString()
                          + EntityConstants.TokenDelimiter
                          + userDatabase.UserName
                          + EntityConstants.TokenDelimiter
                          + userDatabase.AuthenticationType.ToString()
                          + EntityConstants.TokenDelimiter
                          + (userDatabase.ActiveDirectoryId ?? "").Trim()
                          + EntityConstants.TokenDelimiter
                          + ""
                          + EntityConstants.TokenDelimiter
                          + sessionType.ToString()
                          + EntityConstants.TokenDelimiter
                          + EntityConstants.TokenDelimiter
                          + EntityConstants.TokenDelimiter;

                    // TODO: Remove for production.
                    if (AffinityConfiguration.DeploymentLocation == DeploymentLocation.BtsSaleem)
                    {
                        now = now.Add(TimeSpan.FromHours(1));
                    }

                    sessionDatabase = userDatabase.Sessions.SingleOrDefault
                                      (
                        s =>
                        (
                            (s.DateTimeCreated < now) &&
                            (s.DateTimeExpiration > now) &&
                            (s.SessionId == sessionId) &&
                            (s.Token == token) &&
                            (s.UserAgent == userAgent) &&
                            (s.IPAddressString == clientIpAddress) &&
                            (s.SessionType == sessionType)
                        )
                                      );

                    var lines = new List <string>();
                    lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                    lines.Add($"SIGNIN");
                    lines.Add($"Session Found: {sessionDatabase != null}");
                    lines.Add($"now: {now}");
                    lines.Add($"SessionId: {sessionId}");
                    lines.Add($"token: {token}");
                    lines.Add($"useragent: {userAgent}");
                    lines.Add($"ipAddressString: {clientIpAddress}");
                    lines.Add($"sessionType: {sessionType}");
                    lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                    AffinityConfiguration.Messages.Add(string.Join("<br />", lines));

                    if (sessionDatabase == null)
                    {
                        var guid        = Guid.NewGuid();
                        var rijndaelKey = new byte [GlobalConstants.AlgorithmSymmetricKeySize];
                        var rijndaelInitializationVector = new byte [GlobalConstants.AlgorithmSymmetricInitializationVectorSize];
                        var rsaKeyPair = Rsa.GenerateKeyPair(GlobalConstants.AlgorithmAsymmetricKeySize);

                        using (var randomNumberGenerator = RandomNumberGenerator.Create())
                        {
                            randomNumberGenerator.GetBytes(rijndaelKey);
                            randomNumberGenerator.GetBytes(rijndaelInitializationVector);
                        }

                        do
                        {
                            guid = Guid.NewGuid();
                        } while (context.Sessions.Any(s => s.Guid == guid));

                        sessionDatabase                              = new MasterSession();
                        sessionDatabase.Guid                         = guid;
                        sessionDatabase.CultureName                  = "en";
                        sessionDatabase.Token                        = token;
                        sessionDatabase.SessionId                    = sessionId;
                        sessionDatabase.SessionType                  = sessionType;
                        sessionDatabase.UserAgent                    = userAgent;
                        sessionDatabase.IPAddressString              = clientIpAddress;
                        sessionDatabase.DeviceType                   = DeviceType.Unknown;
                        sessionDatabase.DateTimeCreated              = now;
                        sessionDatabase.DateTimeExpiration           = sessionDatabase.DateTimeCreated.Add(TimeSpan.FromDays(1));
                        sessionDatabase.RijndaelKey                  = Convert.ToBase64String(rijndaelKey);
                        sessionDatabase.RijndaelInitializationVector = Convert.ToBase64String(rijndaelInitializationVector);
                        sessionDatabase.RsaKeyPublic                 = rsaKeyPair.KeyPublic.KeyToString();
                        sessionDatabase.RsaKeyPrivate                = rsaKeyPair.KeyPrivate.KeyToString();
                        sessionDatabase.User                         = userDatabase;
                        sessionDatabase.UserId                       = userDatabase.Id;
                        context.Sessions.Add(sessionDatabase);
                        context.SaveChanges();
                    }
                    else
                    {
                        sessionDatabase.DateTimeExpiration = DateTime.UtcNow.Add(TimeSpan.FromDays(1));
                        context.SaveChanges();
                    }

                    var sessions = userDatabase.Sessions.Where(s => s.DateTimeExpiration < DateTime.UtcNow.Subtract(TimeSpan.FromDays(30)));
                    foreach (var s in sessions)
                    {
                        context.Sessions.Remove(s);
                    }
                    context.SaveChanges();

                    sessionDatabase = context.Sessions.AsNoTracking().Single(s => s.Id == sessionDatabase.Id);
                    userDatabase    = context.Users.AsNoTracking().Include(p => p.Roles).AsNoTracking().Single(u => u.Id == userDatabase.Id);

                    userDatabase.PasswordHash   = "";
                    userDatabase.PasswordSalt   = "";
                    sessionDatabase.RijndaelKey = "";
                    sessionDatabase.RijndaelInitializationVector = "";
                    sessionDatabase.RsaKeyPrivate = "";
                    sessionDatabase.RsaKeyPublic  = (sessionType == SessionType.Api) ? sessionDatabase.RsaKeyPublic : "";

                    masterUserSession = new MasterUserSession(userDatabase, sessionDatabase);

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 29
0
        public static void ThrowOnInvalidToken
        (
            string token,
            SessionType sessionType,
            string username,
            string clientIpAddress,
            string userAgent,
            long ticks,
            string sessionId,
            out MasterUserSession masterUserSession
        )
        {
            MasterUser    userDatabase    = null;
            MasterSession sessionDatabase = null;

            masterUserSession = null;

            if (clientIpAddress != null)
            {
                if (clientIpAddress.Contains(":"))
                {
                    clientIpAddress = clientIpAddress.Split(new string[] { ":" }, StringSplitOptions.None)[0];
                }
            }

            using (var context = new ContextMaster())
            {
                var now = DateTime.UtcNow;
                var sessionsDatabase = context
                                       .Sessions
                                       .Include(p => p.User)
                                       .Where
                                       (
                    s =>
                    (
                        // TODO: Add checks.
                        (s.DateTimeCreated < now) &&
                        (s.DateTimeExpiration > now) &&
                        (s.SessionId == sessionId) &&
                        (s.Token == token) &&
                        (s.UserAgent == userAgent) &&
                        (s.IPAddressString == clientIpAddress) &&
                        (s.SessionType == sessionType)
                    )
                                       )
                                       .ToList();

                var lines = new List <string>();
                lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                lines.Add($"VALIDATE TOKEN");
                lines.Add($"Session Found: {sessionsDatabase != null}");
                lines.Add($"now: {now}");
                lines.Add($"SessionId: {sessionId}");
                lines.Add($"token: {token}");
                lines.Add($"useragent: {userAgent}");
                lines.Add($"ipAddressString: {clientIpAddress}");
                lines.Add($"sessionType: {sessionType}");
                lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                AffinityConfiguration.Messages.Add(string.Join("<br />", lines));

                if (sessionsDatabase.Count > 1)
                {
                    // Order by Id (descending).
                    sessionsDatabase.Sort((x, y) => x.Id.CompareTo(y.Id));

                    do
                    {
                        context.Sessions.Remove(sessionsDatabase.First());
                        context.SaveChanges();
                        sessionsDatabase.Remove(sessionsDatabase.First());
                    }while (sessionsDatabase.Count > 1);

                    context.SaveChanges();
                }

                if (sessionsDatabase.Count < 1)
                {
                    throw (new TokenInvalidException());
                }
                else if (sessionsDatabase.Count > 1)
                {
                    throw (new Exception("Multiple session matches were found. This is a dev bug!"));
                }

                sessionDatabase = sessionsDatabase.Single();
                sessionDatabase = context.Sessions.AsNoTracking().Include(s => s.User).Single(s => s.Id == sessionDatabase.Id);
                userDatabase    = context.Users.AsNoTracking().Include(u => u.Roles).Single(u => u.Id == sessionDatabase.User.Id);

                masterUserSession = new MasterUserSession(userDatabase, sessionDatabase);
            }
        }