Beispiel #1
0
        protected virtual async Task CreateUserAsync(CreateOrUpdateUserInput input)
        {
            if (AbpSession.TenantId.HasValue)
            {
                await _userPolicy.CheckMaxUserCountAsync(AbpSession.GetTenantId());
            }

            var user = ObjectMapper.Map <User>(input.User); //Passwords is not mapped (see mapping configuration)

            user.TenantId = AbpSession.TenantId;

            //Set password
            if (input.SetRandomPassword)
            {
                var randomPassword = User.CreateRandomPassword();
                user.Password       = _passwordHasher.HashPassword(user, randomPassword);
                input.User.Password = randomPassword;
            }
            else if (!input.User.Password.IsNullOrEmpty())
            {
                await UserManager.InitializeOptionsAsync(AbpSession.TenantId);

                foreach (var validator in _passwordValidators)
                {
                    CheckErrors(await validator.ValidateAsync(UserManager, user, input.User.Password));
                }
                user.Password = _passwordHasher.HashPassword(user, input.User.Password);
            }

            user.ShouldChangePasswordOnNextLogin = input.User.ShouldChangePasswordOnNextLogin;

            //Assign roles
            user.Roles = new Collection <UserRole>();
            foreach (var roleName in input.AssignedRoleNames)
            {
                var role = await _roleManager.GetRoleByNameAsync(roleName);

                user.Roles.Add(new UserRole(AbpSession.TenantId, user.Id, role.Id));
            }

            CheckErrors(await UserManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync(); //To get new user's Id.

            //Notifications
            await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            //Organization Units
            await UserManager.SetOrganizationUnitsAsync(user, input.OrganizationUnits.ToArray());

            //Send activation email
            if (input.SendActivationEmail)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(
                    user,
                    AppUrlService.CreateEmailActivationUrlFormat(AbpSession.TenantId),
                    input.User.Password
                    );
            }
        }
Beispiel #2
0
        private async Task UpdateExternalLoginSettingsAsync(ExternalLoginProviderSettingsEditDto input)
        {
            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Facebook,
                input.Facebook == null || !input.Facebook.IsValid()? "" : input.Facebook.ToJsonString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Facebook_IsDeactivated,
                input.Facebook_IsDeactivated.ToString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Google,
                input.Google == null || !input.Google.IsValid()? "" : input.Google.ToJsonString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Google_IsDeactivated,
                input.Google_IsDeactivated.ToString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Twitter,
                input.Twitter == null || !input.Twitter.IsValid()? "" : input.Twitter.ToJsonString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Twitter_IsDeactivated,
                input.Twitter_IsDeactivated.ToString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Microsoft,
                input.Microsoft == null || !input.Microsoft.IsValid()? "" : input.Microsoft.ToJsonString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.Microsoft_IsDeactivated,
                input.Microsoft_IsDeactivated.ToString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.OpenIdConnect,
                input.OpenIdConnect == null || !input.OpenIdConnect.IsValid()? "" : input.OpenIdConnect.ToJsonString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.OpenIdConnect_IsDeactivated,
                input.OpenIdConnect_IsDeactivated.ToString()
                );

            var openIdConnectMappedClaimsValue = "";

            if (input.OpenIdConnect == null || !input.OpenIdConnect.IsValid() || input.OpenIdConnectClaimsMapping.IsNullOrEmpty())
            {
                openIdConnectMappedClaimsValue = await SettingManager.GetSettingValueForApplicationAsync(AppSettings.ExternalLoginProvider.OpenIdConnectMappedClaims);//set default value
            }
            else
            {
                openIdConnectMappedClaimsValue = input.OpenIdConnectClaimsMapping.ToJsonString();
            }

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.OpenIdConnectMappedClaims,
                openIdConnectMappedClaimsValue
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.WsFederation,
                input.WsFederation == null || !input.WsFederation.IsValid()? "" : input.WsFederation.ToJsonString()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.Tenant.WsFederation_IsDeactivated,
                input.WsFederation_IsDeactivated.ToString()
                );

            var wsFederationMappedClaimsValue = "";

            if (input.WsFederation == null || !input.WsFederation.IsValid() || input.WsFederationClaimsMapping.IsNullOrEmpty())
            {
                wsFederationMappedClaimsValue = await SettingManager.GetSettingValueForApplicationAsync(AppSettings.ExternalLoginProvider.WsFederationMappedClaims);//set default value
            }
            else
            {
                wsFederationMappedClaimsValue = input.WsFederationClaimsMapping.ToJsonString();
            }

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                AppSettings.ExternalLoginProvider.WsFederationMappedClaims,
                wsFederationMappedClaimsValue
                );

            ExternalLoginOptionsCacheManager.ClearCache();
        }
Beispiel #3
0
 public async Task Create(CreateAnimalInput input)
 {
     Logger.Info(string.Format("Creating a new animal with name: {0}", input.Name));
     var @animal = Animal.Create(AbpSession.GetTenantId(), input.Name, input.Owner, input.Age);
     await _animalManager.CreateAsync(@animal);
 }
Beispiel #4
0
        /// <summary>
        /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected async Task <Tenant> GetCurrentTenantAsync()
        {
            var tenantId = AbpSession.GetTenantId();

            return(await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId)));
        }
Beispiel #5
0
        private async Task <GeneralSettingsEditDto> GetGeneralSettingsAsync()
        {
            var settings = new GeneralSettingsEditDto();

            if (Clock.SupportsMultipleTimezone)
            {
                var timezone = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId());

                settings.Timezone = timezone;
                settings.TimezoneForComparison = timezone;
            }

            var defaultTimeZoneId = await _timeZoneService.GetDefaultTimezoneAsync(SettingScopes.Tenant, AbpSession.TenantId);

            if (settings.Timezone == defaultTimeZoneId)
            {
                settings.Timezone = string.Empty;
            }

            return(settings);
        }
        protected virtual Task <Tenant> GetCurrentTenantAsync()
        {
            var tenantManager = Resolve <TenantManager>();

            return(tenantManager.GetByIdAsync(AbpSession.GetTenantId()));
        }
        private async Task <List <Dashboard> > GetDefaultDashboardValue(string application)
        {
            string dashboardConfigAsJsonString;

            if (AbpSession.MultiTenancySide == MultiTenancySides.Host)
            {
                dashboardConfigAsJsonString = await SettingManager.GetSettingValueForApplicationAsync(GetSettingName(application));
            }
            else
            {
                dashboardConfigAsJsonString = await SettingManager.GetSettingValueForTenantAsync(GetSettingName(application), AbpSession.GetTenantId());
            }

            return(string.IsNullOrWhiteSpace(dashboardConfigAsJsonString)
                ? null
                : JsonConvert.DeserializeObject <List <Dashboard> >(dashboardConfigAsJsonString));
        }
Beispiel #8
0
        public async Task <IActionResult> Upgrade(int upgradeEditionId)
        {
            if (!AbpSession.TenantId.HasValue)
            {
                throw new ArgumentNullException();
            }

            SubscriptionPaymentType subscriptionPaymentType;

            using (CurrentUnitOfWork.SetTenantId(null))
            {
                var tenant = await _tenantManager.GetByIdAsync(AbpSession.GetTenantId());

                subscriptionPaymentType = tenant.SubscriptionPaymentType;

                if (tenant.EditionId.HasValue)
                {
                    var currentEdition = await _editionManager.GetByIdAsync(tenant.EditionId.Value);

                    if (((SubscribableEdition)currentEdition).IsFree)
                    {
                        return(RedirectToAction("Buy", "Payment", new
                        {
                            tenantId = AbpSession.GetTenantId(),
                            editionId = upgradeEditionId
                        }));
                    }
                }
            }

            var paymentInfo = await _paymentAppService.GetPaymentInfo(new PaymentInfoInput { UpgradeEditionId = upgradeEditionId });

            var edition = await _tenantRegistrationAppService.GetEdition(upgradeEditionId);

            var lastPayment = await _subscriptionPaymentRepository.GetLastCompletedPaymentOrDefaultAsync(
                tenantId : AbpSession.GetTenantId(),
                gateway : null,
                isRecurring : null);

            var model = new UpgradeEditionViewModel
            {
                Edition                 = edition,
                AdditionalPrice         = paymentInfo.AdditionalPrice,
                SubscriptionPaymentType = subscriptionPaymentType,
                PaymentPeriodType       = lastPayment.GetPaymentPeriodType()
            };

            if (subscriptionPaymentType.IsRecurring())
            {
                model.PaymentGateways = new List <PaymentGatewayModel>
                {
                    new PaymentGatewayModel
                    {
                        GatewayType = lastPayment.Gateway,
                        SupportsRecurringPayments = true
                    }
                };
            }
            else
            {
                model.PaymentGateways = _paymentAppService.GetActiveGateways(new GetActiveGatewaysInput());
            }

            return(View("Upgrade", model));
        }
Beispiel #9
0
        public async Task <ActionResult> Index()
        {
            var output = await _tenantSettingsAppService.GetAllSettings();

            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

            var timezoneItems = await _timingAppService.GetTimezoneComboboxItems(new GetTimezoneComboboxItemsInput
            {
                DefaultTimezoneScope = SettingScopes.Tenant,
                SelectedTimezoneId   = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId())
            });

            var user = await _userManager.GetUserAsync(AbpSession.ToUserIdentifier());

            ViewBag.CurrentUserEmail = user.EmailAddress;

            var tenant = await _tenantManager.FindByIdAsync(AbpSession.GetTenantId());

            ViewBag.TenantId          = tenant.Id;
            ViewBag.TenantLogoId      = tenant.LogoId;
            ViewBag.TenantCustomCssId = tenant.CustomCssId;

            var model = new SettingsViewModel
            {
                Settings      = output,
                TimezoneItems = timezoneItems
            };

            AddEnabledSocialLogins(model);

            return(View(model));
        }
 private async Task UpdateUserLockOutSettingsAsync(UserLockOutSettingsEditDto settings)
 {
     await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, settings.IsEnabled.ToString().ToLowerInvariant());
     await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, settings.DefaultAccountLockoutSeconds.ToString());
     await SettingManager.ChangeSettingForTenantAsync(AbpSession.GetTenantId(), AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, settings.MaxFailedAccessAttemptsBeforeLockout.ToString());
 }
Beispiel #11
0
        public async Task <ActionResult> Index()
        {
            var output = await _tenantSettingsAppService.GetAllSettings();

            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

            var timezoneItems = await _timingAppService.GetEditionComboboxItems(new GetTimezoneComboboxItemsInput
            {
                DefaultTimezoneScope = SettingScopes.Tenant,
                SelectedTimezoneId   = await SettingManager.GetSettingValueForTenantAsync(TimingSettingNames.TimeZone, AbpSession.GetTenantId())
            });

            var model = new SettingsViewModel
            {
                Settings      = output,
                TimezoneItems = timezoneItems
            };

            return(View(model));
        }
Beispiel #12
0
 public async Task CreateAsync(CreateBlogInput input)
 {
     var @blog = Blog.Create(AbpSession.GetTenantId(), input.Title, input.Content, input.AuthorId, input.CategoryId, input.Image);
     await _blogManager.CreateAsync(@blog);
 }
        private async Task UpdateEmailSettingsAsync(EmailSettingsEditDto input)
        {
            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.DefaultFromAddress,
                input.DefaultFromAddress
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.DefaultFromAddress,
                input.DefaultFromAddress
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.DefaultFromDisplayName,
                input.DefaultFromDisplayName
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.Host,
                input.SmtpHost
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.Port,
                input.SmtpPort.ToString(CultureInfo.InvariantCulture)
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.UserName,
                input.SmtpUserName
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.Password,
                SimpleStringCipher.Instance.Encrypt(input.SmtpPassword)
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.Domain,
                input.SmtpDomain
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.EnableSsl,
                input.SmtpEnableSsl.ToString().ToLowerInvariant()
                );

            await SettingManager.ChangeSettingForTenantAsync(
                AbpSession.GetTenantId(),
                EmailSettingNames.Smtp.UseDefaultCredentials,
                input.SmtpUseDefaultCredentials.ToString().ToLowerInvariant()
                );
        }
Beispiel #14
0
        public async Task <EditionsSelectOutput> GetEditionsForSelect()
        {
            var features = FeatureManager
                           .GetAll()
                           .Where(feature => (feature[FeatureMetadata.CustomFeatureKey] as FeatureMetadata)?.IsVisibleOnPricingTable ?? false);

            var flatFeatures = ObjectMapper
                               .Map <List <FlatFeatureSelectDto> >(features)
                               .OrderBy(f => f.DisplayName)
                               .ToList();

            var editions = (await _editionManager.GetAllAsync())
                           .Cast <SubscribableEdition>()
                           .OrderBy(e => e.MonthlyPrice)
                           .ToList();

            var featureDictionary = features.ToDictionary(feature => feature.Name, f => f);

            var editionWithFeatures = new List <EditionWithFeaturesDto>();

            foreach (var edition in editions)
            {
                editionWithFeatures.Add(await CreateEditionWithFeaturesDto(edition, featureDictionary));
            }

            if (AbpSession.UserId.HasValue)
            {
                var currentEditionId = (await _tenantManager.GetByIdAsync(AbpSession.GetTenantId()))
                                       .EditionId;

                if (currentEditionId.HasValue)
                {
                    editionWithFeatures = editionWithFeatures.Where(e => e.Edition.Id != currentEditionId).ToList();

                    var currentEdition = (SubscribableEdition)(await _editionManager.GetByIdAsync(currentEditionId.Value));
                    if (!currentEdition.IsFree)
                    {
                        var lastPayment = await _subscriptionPaymentRepository.GetLastCompletedPaymentOrDefaultAsync(
                            AbpSession.GetTenantId(),
                            null,
                            null);

                        if (lastPayment != null)
                        {
                            editionWithFeatures = editionWithFeatures
                                                  .Where(e =>
                                                         e.Edition.GetPaymentAmount(lastPayment.PaymentPeriodType) >
                                                         currentEdition.GetPaymentAmount(lastPayment.PaymentPeriodType)
                                                         )
                                                  .ToList();
                        }
                    }
                }
            }

            return(new EditionsSelectOutput
            {
                AllFeatures = flatFeatures,
                EditionsWithFeatures = editionWithFeatures,
            });
        }
Beispiel #15
0
 protected virtual Tenant GetCurrentTenant()
 {
     return(TenantManager.GetById(AbpSession.GetTenantId()));
 }
Beispiel #16
0
        public async Task <GetCurrentLoginInformationsOutput> GetCurrentLoginInformations()
        {
            var output = new GetCurrentLoginInformationsOutput
            {
                Application = new ApplicationInfoDto
                {
                    Version      = AppVersionHelper.Version,
                    ReleaseDate  = AppVersionHelper.ReleaseDate,
                    Features     = new Dictionary <string, bool>(),
                    Currency     = FintrakERPIMSDemoConsts.Currency,
                    CurrencySign = FintrakERPIMSDemoConsts.CurrencySign,
                    AllowTenantsToChangeEmailSettings = FintrakERPIMSDemoConsts.AllowTenantsToChangeEmailSettings,
                    UserDelegationIsEnabled           = _userDelegationConfiguration.IsEnabled
                }
            };

            var uiCustomizer = await _uiThemeCustomizerFactory.GetCurrentUiCustomizer();

            output.Theme = await uiCustomizer.GetUiSettings();

            if (AbpSession.TenantId.HasValue)
            {
                output.Tenant = ObjectMapper
                                .Map <TenantLoginInfoDto>(await TenantManager
                                                          .Tenants
                                                          .Include(t => t.Edition)
                                                          .FirstAsync(t => t.Id == AbpSession.GetTenantId()));
            }

            if (AbpSession.ImpersonatorTenantId.HasValue)
            {
                output.ImpersonatorTenant = ObjectMapper
                                            .Map <TenantLoginInfoDto>(await TenantManager
                                                                      .Tenants
                                                                      .Include(t => t.Edition)
                                                                      .FirstAsync(t => t.Id == AbpSession.ImpersonatorTenantId));
            }

            if (AbpSession.UserId.HasValue)
            {
                output.User = ObjectMapper.Map <UserLoginInfoDto>(await GetCurrentUserAsync());
            }

            if (AbpSession.ImpersonatorUserId.HasValue)
            {
                output.ImpersonatorUser = ObjectMapper.Map <UserLoginInfoDto>(await GetImpersonatorUserAsync());
            }

            if (output.Tenant == null)
            {
                return(output);
            }

            if (output.Tenant.Edition != null)
            {
                var lastPayment = await _subscriptionPaymentRepository.GetLastCompletedPaymentOrDefaultAsync(output.Tenant.Id, null, null);

                if (lastPayment != null)
                {
                    output.Tenant.Edition.IsHighestEdition = IsEditionHighest(output.Tenant.Edition.Id, lastPayment.GetPaymentPeriodType());
                }
            }

            output.Tenant.SubscriptionDateString = GetTenantSubscriptionDateString(output);
            output.Tenant.CreationTimeString     = output.Tenant.CreationTime.ToString("d");

            return(output);
        }
        public async Task <CreatePaymentResponse> CreatePayment(CreatePaymentDto input)
        {
            var targetEdition = (SubscribableEdition)await _editionManager.GetByIdAsync(input.EditionId);

            var tenant = AbpSession.TenantId == null ? null : await TenantManager.GetByIdAsync(AbpSession.GetTenantId());

            var amount = await CalculateAmountForPaymentAsync(targetEdition, input.PaymentPeriodType, input.EditionPaymentType, tenant);

            using (var paymentGatewayManager = _paymentGatewayManagerFactory.Create(input.SubscriptionPaymentGatewayType))
            {
                var createPaymentResult = await paymentGatewayManager.Object.CreatePaymentAsync(CalculatePaymentDescription(input, targetEdition), amount);

                await _subscriptionPaymentRepository.InsertAsync(
                    new SubscriptionPayment
                {
                    PaymentPeriodType = input.PaymentPeriodType,
                    EditionId         = input.EditionId,
                    TenantId          = tenant == null ? 0 : tenant.Id,
                    Gateway           = input.SubscriptionPaymentGatewayType,
                    Amount            = amount,
                    DayCount          = input.PaymentPeriodType.HasValue ? (int)input.PaymentPeriodType.Value : 0,
                    PaymentId         = createPaymentResult.GetId(),
                    Status            = SubscriptionPaymentStatus.Processing
                }
                    );

                return(createPaymentResult);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected Tenant GetCurrentTenant()
        {
            var tenantId = AbpSession.GetTenantId();

            return(UsingDbContext(null, context => context.Tenants.Single(t => t.Id == tenantId)));
        }
        public virtual async Task <ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                CheckModelState();

                //Create user
                var user = new User
                {
                    Name         = model.Name,
                    Surname      = model.Surname,
                    EmailAddress = model.EmailAddress,
                    IsActive     = true
                };

                //Get external login info if possible
                ExternalLoginInfo externalLoginInfo = null;
                if (model.IsExternalLogin)
                {
                    externalLoginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

                    if (externalLoginInfo == null)
                    {
                        throw new ApplicationException("Can not external login!");
                    }

                    user.Logins = new List <UserLogin>
                    {
                        new UserLogin
                        {
                            LoginProvider = externalLoginInfo.Login.LoginProvider,
                            ProviderKey   = externalLoginInfo.Login.ProviderKey
                        }
                    };

                    if (model.UserName.IsNullOrEmpty())
                    {
                        model.UserName = model.EmailAddress;
                    }

                    model.Password = Authorization.Users.User.CreateRandomPassword();

                    if (string.Equals(externalLoginInfo.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        user.IsEmailConfirmed = true;
                    }
                }
                else
                {
                    //Username and Password are required if not external login
                    if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("FormIsNotValidMessage"));
                    }
                }

                user.UserName = model.UserName;
                user.Password = new PasswordHasher().HashPassword(model.Password);

                //Switch to the tenant
                _unitOfWorkManager.Current.EnableFilter(AbpDataFilters.MayHaveTenant); //TODO: Needed?
                _unitOfWorkManager.Current.SetTenantId(AbpSession.GetTenantId());

                //Add default roles
                user.Roles = new List <UserRole>();
                foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
                {
                    user.Roles.Add(new UserRole {
                        RoleId = defaultRole.Id
                    });
                }

                //Save user
                CheckErrors(await _userManager.CreateAsync(user));
                await _unitOfWorkManager.Current.SaveChangesAsync();

                //Directly login if possible
                if (user.IsActive)
                {
                    AbpLoginResult <Tenant, User> loginResult;
                    if (externalLoginInfo != null)
                    {
                        loginResult = await _logInManager.LoginAsync(externalLoginInfo.Login, GetTenancyNameOrNull());
                    }
                    else
                    {
                        loginResult = await GetLoginResultAsync(user.UserName, model.Password, GetTenancyNameOrNull());
                    }

                    if (loginResult.Result == AbpLoginResultType.Success)
                    {
                        await SignInAsync(loginResult.User, loginResult.Identity);

                        return(Redirect(Url.Action("Index", "Home")));
                    }

                    Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
                }

                //If can not login, show a register result page
                return(View("RegisterResult", new RegisterResultViewModel
                {
                    TenancyName = GetTenancyNameOrNull(),
                    NameAndSurname = user.Name + " " + user.Surname,
                    UserName = user.UserName,
                    EmailAddress = user.EmailAddress,
                    IsActive = user.IsActive
                }));
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;
                ViewBag.ErrorMessage          = ex.Message;

                return(View("Register", model));
            }
        }
        private bool IsSchemeEnabledOnTenant(ExternalLoginProviderInfo scheme)
        {
            if (!AbpSession.TenantId.HasValue)
            {
                return(true);
            }

            switch (scheme.Name)
            {
            case "OpenIdConnect":
                return(!_settingManager.GetSettingValueForTenant <bool>(AppSettings.ExternalLoginProvider.Tenant.OpenIdConnect_IsDeactivated, AbpSession.GetTenantId()));

            case "Microsoft":
                return(!_settingManager.GetSettingValueForTenant <bool>(AppSettings.ExternalLoginProvider.Tenant.Microsoft_IsDeactivated, AbpSession.GetTenantId()));

            case "Google":
                return(!_settingManager.GetSettingValueForTenant <bool>(AppSettings.ExternalLoginProvider.Tenant.Google_IsDeactivated, AbpSession.GetTenantId()));

            case "Twitter":
                return(!_settingManager.GetSettingValueForTenant <bool>(AppSettings.ExternalLoginProvider.Tenant.Twitter_IsDeactivated, AbpSession.GetTenantId()));

            case "Facebook":
                return(!_settingManager.GetSettingValueForTenant <bool>(AppSettings.ExternalLoginProvider.Tenant.Facebook_IsDeactivated, AbpSession.GetTenantId()));

            case "WsFederation":
                return(!_settingManager.GetSettingValueForTenant <bool>(AppSettings.ExternalLoginProvider.Tenant.WsFederation_IsDeactivated, AbpSession.GetTenantId()));

            default: return(true);
            }
        }
Beispiel #21
0
 protected virtual Task <Tenant> GetCurrentTenantAsync()
 {
     return(TenantManager.GetByIdAsync(AbpSession.GetTenantId()));
 }
        public virtual async Task UpdateAsync(UpdateLocalizedStringInput input)
        {
            await _applicationLanguageTextManager.UpdateStringAsync(AbpSession.GetTenantId(), input.Source, new CultureInfo("en"), input.Name, input.EnValue);

            await _applicationLanguageTextManager.UpdateStringAsync(AbpSession.GetTenantId(), input.Source, new CultureInfo("zh-Hans"), input.Name, input.ZhValue);
        }
Beispiel #23
0
        private async Task <TenantEmailSettingsEditDto> GetEmailSettingsAsync()
        {
            var useHostDefaultEmailSettings = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.Email.UseHostDefaultEmailSettings, AbpSession.GetTenantId());

            if (useHostDefaultEmailSettings)
            {
                return(new TenantEmailSettingsEditDto
                {
                    UseHostDefaultEmailSettings = true
                });
            }

            var smtpPassword = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Password, AbpSession.GetTenantId());

            return(new TenantEmailSettingsEditDto
            {
                UseHostDefaultEmailSettings = false,
                DefaultFromAddress = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.DefaultFromAddress, AbpSession.GetTenantId()),
                DefaultFromDisplayName = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.DefaultFromDisplayName, AbpSession.GetTenantId()),
                SmtpHost = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Host, AbpSession.GetTenantId()),
                SmtpPort = await SettingManager.GetSettingValueForTenantAsync <int>(EmailSettingNames.Smtp.Port, AbpSession.GetTenantId()),
                SmtpUserName = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.UserName, AbpSession.GetTenantId()),
                SmtpPassword = SimpleStringCipher.Instance.Decrypt(smtpPassword),
                SmtpDomain = await SettingManager.GetSettingValueForTenantAsync(EmailSettingNames.Smtp.Domain, AbpSession.GetTenantId()),
                SmtpEnableSsl = await SettingManager.GetSettingValueForTenantAsync <bool>(EmailSettingNames.Smtp.EnableSsl, AbpSession.GetTenantId()),
                SmtpUseDefaultCredentials = await SettingManager.GetSettingValueForTenantAsync <bool>(EmailSettingNames.Smtp.UseDefaultCredentials, AbpSession.GetTenantId())
            });
        }
Beispiel #24
0
        /// <summary>
        /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
        /// Throws exception if there is no current tenant.
        /// </summary>
        protected async Task <Tenant> GetCurrentTenantAsync()
        {
            var tenantId = AbpSession.GetTenantId();

            return(await UsingDbSession(session => session.Query <Tenant>().SingleAsync(t => t.Id == tenantId)));
        }
Beispiel #25
0
        private async Task <ExternalLoginProviderSettingsEditDto> GetExternalLoginProviderSettings()
        {
            var facebookSettings = await SettingManager.GetSettingValueForTenantAsync(AppSettings.ExternalLoginProvider.Tenant.Facebook, AbpSession.GetTenantId());

            var googleSettings = await SettingManager.GetSettingValueForTenantAsync(AppSettings.ExternalLoginProvider.Tenant.Google, AbpSession.GetTenantId());

            var twitterSettings = await SettingManager.GetSettingValueForTenantAsync(AppSettings.ExternalLoginProvider.Tenant.Twitter, AbpSession.GetTenantId());

            var microsoftSettings = await SettingManager.GetSettingValueForTenantAsync(AppSettings.ExternalLoginProvider.Tenant.Microsoft, AbpSession.GetTenantId());

            var openIdConnectSettings = await SettingManager.GetSettingValueForTenantAsync(AppSettings.ExternalLoginProvider.Tenant.OpenIdConnect, AbpSession.GetTenantId());

            var openIdConnectMappedClaims = await SettingManager.GetSettingValueAsync(AppSettings.ExternalLoginProvider.OpenIdConnectMappedClaims);

            var wsFederationSettings = await SettingManager.GetSettingValueForTenantAsync(AppSettings.ExternalLoginProvider.Tenant.WsFederation, AbpSession.GetTenantId());

            var wsFederationMappedClaims = await SettingManager.GetSettingValueAsync(AppSettings.ExternalLoginProvider.WsFederationMappedClaims);

            return(new ExternalLoginProviderSettingsEditDto
            {
                Facebook_IsDeactivated = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.ExternalLoginProvider.Tenant.Facebook_IsDeactivated, AbpSession.GetTenantId()),
                Facebook = facebookSettings.IsNullOrWhiteSpace()
                    ? new FacebookExternalLoginProviderSettings()
                    : facebookSettings.FromJsonString <FacebookExternalLoginProviderSettings>(),

                Google_IsDeactivated = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.ExternalLoginProvider.Tenant.Google_IsDeactivated, AbpSession.GetTenantId()),
                Google = googleSettings.IsNullOrWhiteSpace()
                    ? new GoogleExternalLoginProviderSettings()
                    : googleSettings.FromJsonString <GoogleExternalLoginProviderSettings>(),

                Twitter_IsDeactivated = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.ExternalLoginProvider.Tenant.Twitter_IsDeactivated, AbpSession.GetTenantId()),
                Twitter = twitterSettings.IsNullOrWhiteSpace()
                    ? new TwitterExternalLoginProviderSettings()
                    : twitterSettings.FromJsonString <TwitterExternalLoginProviderSettings>(),

                Microsoft_IsDeactivated = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.ExternalLoginProvider.Tenant.Microsoft_IsDeactivated, AbpSession.GetTenantId()),
                Microsoft = microsoftSettings.IsNullOrWhiteSpace()
                    ? new MicrosoftExternalLoginProviderSettings()
                    : microsoftSettings.FromJsonString <MicrosoftExternalLoginProviderSettings>(),

                OpenIdConnect_IsDeactivated = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.ExternalLoginProvider.Tenant.OpenIdConnect_IsDeactivated, AbpSession.GetTenantId()),
                OpenIdConnect = openIdConnectSettings.IsNullOrWhiteSpace()
                    ? new OpenIdConnectExternalLoginProviderSettings()
                    : openIdConnectSettings.FromJsonString <OpenIdConnectExternalLoginProviderSettings>(),
                OpenIdConnectClaimsMapping = openIdConnectMappedClaims.IsNullOrWhiteSpace()
                    ? new List <JsonClaimMapDto>()
                    : openIdConnectMappedClaims.FromJsonString <List <JsonClaimMapDto> >(),

                WsFederation_IsDeactivated = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.ExternalLoginProvider.Tenant.WsFederation_IsDeactivated, AbpSession.GetTenantId()),
                WsFederation = wsFederationSettings.IsNullOrWhiteSpace()
                    ? new WsFederationExternalLoginProviderSettings()
                    : wsFederationSettings.FromJsonString <WsFederationExternalLoginProviderSettings>(),
                WsFederationClaimsMapping = wsFederationMappedClaims.IsNullOrWhiteSpace()
                    ? new List <JsonClaimMapDto>()
                    : wsFederationMappedClaims.FromJsonString <List <JsonClaimMapDto> >()
            });
        }
Beispiel #26
0
 public async Task CreateAsync(CreateEventInput input)
 {
     var @event = Event.Create(AbpSession.GetTenantId(), input.Title, input.Date, input.Description, input.MaxRegistrationCount);
     await _eventManager.CreateAsync(@event);
 }
Beispiel #27
0
 private async Task <LdapSettingsEditDto> GetLdapSettingsAsync()
 {
     return(new LdapSettingsEditDto
     {
         IsModuleEnabled = true,
         IsEnabled = await SettingManager.GetSettingValueForTenantAsync <bool>(LdapSettingNames.IsEnabled, AbpSession.GetTenantId()),
         Domain = await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Domain, AbpSession.GetTenantId()),
         UserName = await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.UserName, AbpSession.GetTenantId()),
         Password = await SettingManager.GetSettingValueForTenantAsync(LdapSettingNames.Password, AbpSession.GetTenantId()),
     });
 }
Beispiel #28
0
        protected virtual async Task CreateUserAsync(CreateOrUpdateUserInput input)
        {
            if (AbpSession.TenantId.HasValue)
            {
                await _userPolicy.CheckMaxUserCountAsync(AbpSession.GetTenantId());
            }
            var fingerCode = Convert.ToInt32(input.User.FingerCode);
            var machineId  = input.User.MachineId;
            var uploadUser = input.User.UploadUser;
            var userImage  = input.User.UserImage;
            var user       = ObjectMapper.Map <User>(input.User); //Passwords is not mapped (see mapping configuration)

            user.TenantId = AbpSession.TenantId;

            //Set password
            if (input.SetRandomPassword)
            {
                var randomPassword = await _userManager.CreateRandomPassword();

                user.MobilePassword = EnryptString(randomPassword);
                user.Password       = _passwordHasher.HashPassword(user, randomPassword);
                input.User.Password = randomPassword;
            }
            else if (!input.User.Password.IsNullOrEmpty())
            {
                await UserManager.InitializeOptionsAsync(AbpSession.TenantId);

                foreach (var validator in _passwordValidators)
                {
                    CheckErrors(await validator.ValidateAsync(UserManager, user, input.User.Password));
                }
                user.MobilePassword = EnryptString(input.User.Password);
                user.Password       = _passwordHasher.HashPassword(user, input.User.Password);
            }

            user.ShouldChangePasswordOnNextLogin = input.User.ShouldChangePasswordOnNextLogin;

            //Assign roles
            user.Roles = new Collection <UserRole>();
            foreach (var roleName in input.AssignedRoleNames)
            {
                var role = await _roleManager.GetRoleByNameAsync(roleName);

                user.Roles.Add(new UserRole(AbpSession.TenantId, user.Id, role.Id));
            }

            //Assign Locations
            user.Locations = new Collection <UserLocation>();
            foreach (var assignedLocation in input.AssignedLocations)
            {
                var locationToAdd = await _locationRepository.FirstOrDefaultAsync(x => x.Id == assignedLocation.LocationId);

                user.Locations.Add(new UserLocation(user.Id, locationToAdd.Id, assignedLocation.FromDate, assignedLocation.ToDate));
            }

            CheckErrors(await UserManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync(); //To get new user's Id.

            //Notifications
            await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            //Organization Units
            await UserManager.SetOrganizationUnitsAsync(user, input.OrganizationUnits.ToArray());

            //Send activation email
            if (input.SendActivationEmail)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(
                    user,
                    AppUrlService.CreateEmailActivationUrlFormat(AbpSession.TenantId),
                    input.User.Password
                    );
            }

            //add user shifts
            //foreach (var userShiftModel in input.User.UserShifts)
            //{
            //    //add user shift
            //    await _userShiftRepository.InsertAsync(ObjectMapper.Map<UserShift>(userShiftModel.UserShift));
            //}
            foreach (var userShiftModel in input.User.OverrideShifts)
            {
                //add user shift
                await _overrideShiftRepository.InsertAsync(ObjectMapper.Map <OverrideShift>(userShiftModel.OverrideShift));
            }

            //add user to machine
            var userToUpload = new UploadMachineUserInput();

            userToUpload.Person          = new Person();
            userToUpload.MachineData     = new MachineData();
            userToUpload.Person.UserCode = fingerCode;
            var machine = await _machineRepository.FirstOrDefaultAsync(x => x.Id == machineId);

            userToUpload.MachineData.IP   = machine.IpAddress;
            userToUpload.MachineData.SN   = machine.SubNet;
            userToUpload.MachineData.Port = machine.Port;

            var inputJson = new StringContent(
                System.Text.Json.JsonSerializer.Serialize(userToUpload, new System.Text.Json.JsonSerializerOptions()), System.Text.Encoding.UTF8, "application/json");
            var client   = _clientFactory.CreateClient();
            var response = await client.PostAsync(_appConfiguration["Machine:uploadUserAPI"], inputJson);

            if (response.IsSuccessStatusCode)
            {
                using (var responseStream = await response.Content.ReadAsStreamAsync())
                {
                    await System.Text.Json.JsonSerializer.DeserializeAsync <string>(responseStream);
                }

                var downloadImageInput = new DownloadImageInput();
                var clearImage         = userImage.Split(",").ToList <string>();
                downloadImageInput.Datas       = Convert.FromBase64String(clearImage[1]);
                downloadImageInput.MachineData = userToUpload.MachineData;
                downloadImageInput.UserCode    = userToUpload.Person.UserCode;
                await UploadImage(downloadImageInput);
            }
        }