public async Task UpdateUserProfile(UpdateUserProfileInput input)
        {
            var user = await UserManager.GetUserByIdAsync(StudioXSession.GetUserId());

            var mapped = input.MapTo(user);
            await UserManager.UpdateAsync(mapped);
        }
Exemple #2
0
 public async Task ChangeUiTheme(ChangeUiThemeInput input)
 {
     await SettingManager.ChangeSettingForUserAsync(
         StudioXSession.ToUserIdentifier(),
         AppSettingNames.UiTheme,
         input.Theme
         );
 }
Exemple #3
0
        protected virtual Task <User> GetCurrentUserAsync()
        {
            var user = UserManager.FindByIdAsync(StudioXSession.GetUserId().ToString());

            if (user == null)
            {
                throw new Exception("There is no current user!");
            }

            return(user);
        }
Exemple #4
0
        public async Task ShouldNotLoginIfEmailConfirmationIsEnabledAndUserHasNotConfirmed()
        {
            Resolve <IMultiTenancyConfig>().IsEnabled = true;

            //Set session
            StudioXSession.TenantId = 1;
            StudioXSession.UserId   = 1;

            //Email confirmation is disabled as default
            (await logInManager.LoginAsync("user1", "123qwe", Tenant.DefaultTenantName)).Result.ShouldBe(StudioXLoginResultType.Success);

            //Change configuration
            await Resolve <ISettingManager>().ChangeSettingForTenantAsync(StudioXSession.GetTenantId(), StudioXZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, "true");

            //Email confirmation is enabled now
            (await logInManager.LoginAsync("user1", "123qwe", Tenant.DefaultTenantName)).Result.ShouldBe(StudioXLoginResultType.UserEmailIsNotConfirmed);
        }
        public async Task ChangePassword(ChangePasswordInput input)
        {
            var user = await UserManager.GetUserByIdAsync(StudioXSession.GetUserId());

            var hashedPassword     = passwordHasher.HashPassword(user, input.Password);
            var verificationResult = passwordHasher.VerifyHashedPassword(user, hashedPassword, input.Password);

            if (verificationResult != PasswordVerificationResult.Success)
            {
                throw new UserFriendlyException("Current password must match old password!");
            }

            var identityResult = await UserManager.ChangePasswordAsync(user, input.NewPassword);

            if (!identityResult.Succeeded)
            {
                throw new UserFriendlyException(identityResult.Errors.JoinAsString(", "));
            }
        }
        public virtual ActionResult ChangeCulture(string cultureName, string returnUrl = "")
        {
            if (!GlobalizationHelper.IsValidCultureCode(cultureName))
            {
                throw new StudioXException("Unknown language: " + cultureName + ". It must be a valid culture!");
            }

            var cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cultureName, cultureName));

            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                cookieValue,
                new CookieOptions {
                Expires = Clock.Now.AddYears(2)
            }
                );

            if (StudioXSession.UserId.HasValue)
            {
                SettingManager.ChangeSettingForUser(
                    StudioXSession.ToUserIdentifier(),
                    LocalizationSettingNames.DefaultLanguage,
                    cultureName
                    );
            }

            if (Request.IsAjaxRequest())
            {
                return(Json(new AjaxResponse()));
            }

            if (!string.IsNullOrWhiteSpace(returnUrl) && StudioXUrlHelper.IsLocalUrl(Request, returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(Redirect("/")); //TODO: Go to app root
        }
Exemple #7
0
        public virtual ActionResult ChangeCulture(string cultureName, string returnUrl = "")
        {
            if (!GlobalizationHelper.IsValidCultureCode(cultureName))
            {
                throw new StudioXException("Unknown language: " + cultureName + ". It must be a valid culture!");
            }

            Response.Cookies.Add(
                new HttpCookie(webLocalizationConfiguration.CookieName, cultureName)
            {
                Expires = Clock.Now.AddYears(2),
                Path    = Request.ApplicationPath
            }
                );

            if (StudioXSession.UserId.HasValue)
            {
                SettingManager.ChangeSettingForUser(
                    StudioXSession.ToUserIdentifier(),
                    LocalizationSettingNames.DefaultLanguage,
                    cultureName
                    );
            }

            if (Request.IsAjaxRequest())
            {
                return(Json(new AjaxResponse(), JsonRequestBehavior.AllowGet));
            }

            if (!string.IsNullOrWhiteSpace(returnUrl) && Request.Url != null && StudioXUrlHelper.IsLocalUrl(Request.Url, returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(Redirect(Request.ApplicationPath));
        }
Exemple #8
0
 protected virtual Task <Tenant> GetCurrentTenantAsync()
 {
     return(TenantManager.GetByIdAsync(StudioXSession.GetTenantId()));
 }
 public void TestSession()
 {
     StudioXSession.ShouldNotBe(null);
     StudioXSession.TenantId.ShouldBe(1);
     StudioXSession.UserId.ShouldBe(42);
 }
Exemple #10
0
        public void DapperReposioryTests()
        {
            using (IUnitOfWorkCompleteHandle uow = unitOfWorkManager.Begin())
            {
                // Insert operation should work and tenant, creation audit properties must be set
                productDapperRepository.Insert(new Product("TShirt"));
                Product insertedProduct = productDapperRepository.GetAll(x => x.Name == "TShirt").FirstOrDefault();

                insertedProduct.ShouldNotBeNull();
                insertedProduct.TenantId.ShouldBe(StudioXSession.TenantId);
                insertedProduct.CreationTime.ShouldNotBeNull();
                insertedProduct.CreatorUserId.ShouldBe(StudioXSession.UserId);

                // Update operation should work and Modification Audits should be set
                productDapperRepository.Insert(new Product("TShirt"));
                Product productToUpdate = productDapperRepository.GetAll(x => x.Name == "TShirt").FirstOrDefault();
                productToUpdate.Name = "Pants";
                productDapperRepository.Update(productToUpdate);

                productToUpdate.ShouldNotBeNull();
                productToUpdate.TenantId.ShouldBe(StudioXSession.TenantId);
                productToUpdate.CreationTime.ShouldNotBeNull();
                productToUpdate.LastModifierUserId.ShouldBe(StudioXSession.UserId);

                // Get method should return single
                productDapperRepository.Insert(new Product("TShirt"));
                Action getAction = () => productDapperRepository.Single(x => x.Name == "TShirt");

                getAction.ShouldThrow <InvalidOperationException>("Sequence contains more than one element");

                // Select * from syntax should work
                IEnumerable <Product> products = productDapperRepository.Query("select * from Products");

                products.Count().ShouldBeGreaterThan(0);

                // Ef and Dapper should work under same transaction
                Product productFromEf     = productRepository.FirstOrDefault(x => x.Name == "TShirt");
                Product productFromDapper = productDapperRepository.Single(productFromEf.Id);

                productFromDapper.Name.ShouldBe(productFromEf.Name);
                productFromDapper.TenantId.ShouldBe(productFromEf.TenantId);

                // Soft Delete should work for Dapper
                productDapperRepository.Insert(new Product("SoftDeletableProduct"));

                Product toSoftDeleteProduct = productDapperRepository.Single(x => x.Name == "SoftDeletableProduct");

                productDapperRepository.Delete(toSoftDeleteProduct);

                toSoftDeleteProduct.IsDeleted.ShouldBe(true);
                toSoftDeleteProduct.DeleterUserId.ShouldBe(StudioXSession.UserId);
                toSoftDeleteProduct.TenantId.ShouldBe(StudioXSession.TenantId);

                Product softDeletedProduct = productRepository.FirstOrDefault(x => x.Name == "SoftDeletableProduct");
                softDeletedProduct.ShouldBeNull();

                Product softDeletedProductFromDapper = productDapperRepository.FirstOrDefault(x => x.Name == "SoftDeletableProduct");
                softDeletedProductFromDapper.ShouldBeNull();

                using (unitOfWorkManager.Current.DisableFilter(StudioXDataFilters.SoftDelete))
                {
                    Product softDeletedProductWhenFilterDisabled = productRepository.FirstOrDefault(x => x.Name == "SoftDeletableProduct");
                    softDeletedProductWhenFilterDisabled.ShouldNotBeNull();

                    Product softDeletedProductFromDapperWhenFilterDisabled = productDapperRepository.Single(x => x.Name == "SoftDeletableProduct");
                    softDeletedProductFromDapperWhenFilterDisabled.ShouldNotBeNull();
                }

                using (StudioXSession.Use(2, 266))
                {
                    int productWithTenant2Id = productDapperRepository.InsertAndGetId(new Product("ProductWithTenant2"));

                    Product productWithTenant2 = productRepository.Get(productWithTenant2Id);

                    productWithTenant2.TenantId.ShouldBe(1); //Not sure about that?,Because we changed TenantId to 2 in this scope !!! StudioX.TenantId = 2 now NOT 1 !!!
                }

                using (unitOfWorkManager.Current.SetTenantId(3))
                {
                    int productWithTenant3Id = productDapperRepository.InsertAndGetId(new Product("ProductWithTenant3"));

                    Product productWithTenant3 = productRepository.Get(productWithTenant3Id);

                    productWithTenant3.TenantId.ShouldBe(3);
                }

                Product productWithTenantId3FromDapper = productDapperRepository.FirstOrDefault(x => x.Name == "ProductWithTenant3");
                productWithTenantId3FromDapper.ShouldBeNull();

                using (unitOfWorkManager.Current.SetTenantId(3))
                {
                    Product productWithTenantId3FromDapperInsideTenantScope = productDapperRepository.FirstOrDefault(x => x.Name == "ProductWithTenant3");
                    productWithTenantId3FromDapperInsideTenantScope.ShouldNotBeNull();
                }

                using (unitOfWorkManager.Current.SetTenantId(StudioXSession.TenantId))
                {
                    int productWithTenantId40 = productDapperRepository.InsertAndGetId(new Product("ProductWithTenantId40"));

                    Product productWithTenant40 = productRepository.Get(productWithTenantId40);

                    productWithTenant40.TenantId.ShouldBe(StudioXSession.TenantId);
                    productWithTenant40.CreatorUserId.ShouldBe(StudioXSession.UserId);
                }


                //Second DbContext tests
                int productDetailId = productDetailRepository.InsertAndGetId(new ProductDetail("Woman"));
                productDetailDapperRepository.Get(productDetailId).ShouldNotBeNull();


                uow.Complete();
            }
        }
Exemple #11
0
        /// <summary>
        /// Gets current tenant if <see cref="IStudioXSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected async Task <Tenant> GetCurrentTenantAsync()
        {
            var tenantId = StudioXSession.GetTenantId();

            return(await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId)));
        }
Exemple #12
0
        /// <summary>
        /// Gets current user if <see cref="IStudioXSession.UserId"/> is not null.
        /// Throws exception if it's null.
        /// </summary>
        protected async Task <User> GetCurrentUserAsync()
        {
            var userId = StudioXSession.GetUserId();

            return(await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId)));
        }
Exemple #13
0
        /// <inheritdoc />
        public async Task <IReadOnlyList <ISettingValue> > GetAllSettingValuesAsync(SettingScopes scopes)
        {
            var settingDefinitions = new Dictionary <string, SettingDefinition>();
            var settingValues      = new Dictionary <string, ISettingValue>();

            //Fill all setting with default values.
            foreach (var setting in settingDefinitionManager.GetAllSettingDefinitions())
            {
                settingDefinitions[setting.Name] = setting;
                settingValues[setting.Name]      = new SettingValueObject(setting.Name, setting.DefaultValue);
            }

            //Overwrite application settings
            if (scopes.HasFlag(SettingScopes.Application))
            {
                foreach (var settingValue in await GetAllSettingValuesForApplicationAsync())
                {
                    var setting = settingDefinitions.GetOrDefault(settingValue.Name);

                    //TODO: Conditions get complicated, try to simplify it
                    if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Application))
                    {
                        continue;
                    }

                    if (!setting.IsInherited &&
                        (setting.Scopes.HasFlag(SettingScopes.Tenant) && StudioXSession.TenantId.HasValue ||
                         setting.Scopes.HasFlag(SettingScopes.User) && StudioXSession.UserId.HasValue))
                    {
                        continue;
                    }

                    settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                }
            }

            //Overwrite tenant settings
            if (scopes.HasFlag(SettingScopes.Tenant) && StudioXSession.TenantId.HasValue)
            {
                foreach (var settingValue in await GetAllSettingValuesForTenantAsync(StudioXSession.TenantId.Value))
                {
                    var setting = settingDefinitions.GetOrDefault(settingValue.Name);

                    //TODO: Conditions get complicated, try to simplify it
                    if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Tenant))
                    {
                        continue;
                    }

                    if (!setting.IsInherited && setting.Scopes.HasFlag(SettingScopes.User) &&
                        StudioXSession.UserId.HasValue)
                    {
                        continue;
                    }

                    settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                }
            }

            //Overwrite user settings
            if (scopes.HasFlag(SettingScopes.User) && StudioXSession.UserId.HasValue)
            {
                foreach (var settingValue in await GetAllSettingValuesForUserAsync(StudioXSession.ToUserIdentifier()))
                {
                    var setting = settingDefinitions.GetOrDefault(settingValue.Name);
                    if (setting != null && setting.Scopes.HasFlag(SettingScopes.User))
                    {
                        settingValues[settingValue.Name] =
                            new SettingValueObject(settingValue.Name, settingValue.Value);
                    }
                }
            }

            return(settingValues.Values.ToImmutableList());
        }
        /// <summary>
        /// Gets current tenant if <see cref="IStudioXSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected Tenant GetCurrentTenant()
        {
            var tenantId = StudioXSession.GetTenantId();

            return(UsingDbContext(null, context => context.Tenants.Single(t => t.Id == tenantId)));
        }
        /// <summary>
        /// Gets current user if <see cref="IStudioXSession.UserId"/> is not null.
        /// Throws exception if it's null.
        /// </summary>
        protected User GetCurrentUser()
        {
            var userId = StudioXSession.GetUserId();

            return(UsingDbContext(context => context.Users.Single(u => u.Id == userId)));
        }