예제 #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 = await _userManager.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
                    );
            }
        }
예제 #2
0
        public async Task <int> CreateWithAdminUserAsync(
            string tenancyName,
            string name,
            string adminPassword,
            string adminEmailAddress,
            string connectionString,
            bool isActive,
            int?editionId,
            bool shouldChangePasswordOnNextLogin,
            bool sendActivationEmail,
            DateTime?subscriptionEndDate,
            bool isInTrialPeriod,
            string emailActivationLink)
        {
            int  newTenantId;
            long newAdminId;

            await CheckEditionAsync(editionId, isInTrialPeriod);

            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                //Create tenant
                var tenant = new Tenant(tenancyName, name)
                {
                    IsActive  = isActive,
                    EditionId = editionId,
                    SubscriptionEndDateUtc = subscriptionEndDate?.ToUniversalTime(),
                    IsInTrialPeriod        = isInTrialPeriod,
                    ConnectionString       = connectionString.IsNullOrWhiteSpace() ? null : SimpleStringCipher.Instance.Encrypt(connectionString)
                };

                await CreateAsync(tenant);

                await _unitOfWorkManager.Current.SaveChangesAsync(); //To get new tenant's id.

                //Create tenant database
                _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);

                //We are working entities of new tenant, so changing tenant filter
                using (_unitOfWorkManager.Current.SetTenantId(tenant.Id))
                {
                    //Create static roles for new tenant
                    CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get static role ids

                    //grant all permissions to admin role
                    var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin);
                    await _roleManager.GrantAllPermissionsAsync(adminRole);

                    //User role should be default
                    var userRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.User);
                    userRole.IsDefault = true;
                    CheckErrors(await _roleManager.UpdateAsync(userRole));

                    //Create admin user for the tenant
                    var adminUser = User.CreateTenantAdminUser(tenant.Id, adminEmailAddress);
                    adminUser.ShouldChangePasswordOnNextLogin = shouldChangePasswordOnNextLogin;
                    adminUser.IsActive = true;

                    if (adminPassword.IsNullOrEmpty())
                    {
                        adminPassword = await _userManager.CreateRandomPassword();
                    }
                    else
                    {
                        await _userManager.InitializeOptionsAsync(AbpSession.TenantId);

                        foreach (var validator in _userManager.PasswordValidators)
                        {
                            CheckErrors(await validator.ValidateAsync(_userManager, adminUser, adminPassword));
                        }
                    }

                    adminUser.Password = _passwordHasher.HashPassword(adminUser, adminPassword);

                    CheckErrors(await _userManager.CreateAsync(adminUser));
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get admin user's id

                    //Assign admin user to admin role!
                    CheckErrors(await _userManager.AddToRoleAsync(adminUser, adminRole.Name));

                    //Notifications
                    await _appNotifier.WelcomeToTheApplicationAsync(adminUser);

                    //Send activation email
                    if (sendActivationEmail)
                    {
                        adminUser.SetNewEmailConfirmationCode();
                        await _userEmailer.SendEmailActivationLinkAsync(adminUser, emailActivationLink, adminPassword);
                    }

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    await _demoDataBuilder.BuildForAsync(tenant);

                    newTenantId = tenant.Id;
                    newAdminId  = adminUser.Id;
                }

                await uow.CompleteAsync();
            }

            //Used a second UOW since UOW above sets some permissions and _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync needs these permissions to be saved.
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                using (_unitOfWorkManager.Current.SetTenantId(newTenantId))
                {
                    await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(new UserIdentifier(newTenantId, newAdminId));

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    await uow.CompleteAsync();
                }
            }

            return(newTenantId);
        }
 /// <summary>
 /// Subscribes to all available notifications for given user.
 /// It does not subscribe entity related notifications.
 /// </summary>
 public static void SubscribeToAllAvailableNotifications(this INotificationSubscriptionManager notificationSubscriptionManager, long userId)
 {
     AsyncHelper.RunSync(() => notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(userId));
 }
예제 #4
0
        public virtual async Task <ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                CheckSelfRegistrationIsEnabled();

                if (!model.IsExternalLogin && UseCaptchaOnRegistration())
                {
                    var recaptchaHelper = this.GetRecaptchaVerificationHelper();
                    if (recaptchaHelper.Response.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("CaptchaCanNotBeEmpty"));
                    }

                    if (recaptchaHelper.VerifyRecaptchaResponse() != RecaptchaVerificationResult.Success)
                    {
                        throw new UserFriendlyException(L("IncorrectCaptchaAnswer"));
                    }
                }

                if (!_multiTenancyConfig.IsEnabled)
                {
                    model.TenancyName = Tenant.DefaultTenantName;
                }
                else if (model.TenancyName.IsNullOrEmpty())
                {
                    throw new UserFriendlyException(L("TenantNameCanNotBeEmpty"));
                }

                CurrentUnitOfWork.SetTenantId(null);

                var tenant = await GetActiveTenantAsync(model.TenancyName);

                CurrentUnitOfWork.SetTenantId(tenant.Id);

                if (!await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.UserManagement.AllowSelfRegistration, tenant.Id))
                {
                    throw new UserFriendlyException(L("SelfUserRegistrationIsDisabledMessage_Detail"));
                }

                await _userPolicy.CheckMaxUserCountAsync(tenant.Id);

                //Getting tenant-specific settings
                var isNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueForTenantAsync <bool>(AppSettings.UserManagement.IsNewRegisteredUserActiveByDefault, tenant.Id);

                var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueForTenantAsync <bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenant.Id);

                var user = new User
                {
                    TenantId     = tenant.Id,
                    Name         = model.Name,
                    Surname      = model.Surname,
                    EmailAddress = model.EmailAddress,
                    IsActive     = isNewRegisteredUserActiveByDefault
                };

                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,
                            TenantId      = tenant.Id
                        }
                    };

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

                    if (string.Equals(externalLoginInfo.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        user.IsEmailConfirmed = true;
                    }
                }
                else
                {
                    if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("FormIsNotValidMessage"));
                    }
                }

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

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

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

                if (!user.IsEmailConfirmed)
                {
                    user.SetNewEmailConfirmationCode();
                    await _userEmailer.SendEmailActivationLinkAsync(user);
                }

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

                await _appNotifier.WelcomeToTheApplicationAsync(user);

                await _appNotifier.NewUserRegisteredAsync(user);

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

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

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

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

                return(View("RegisterResult", new RegisterResultViewModel
                {
                    TenancyName = tenant.TenancyName,
                    NameAndSurname = user.Name + " " + user.Surname,
                    UserName = user.UserName,
                    EmailAddress = user.EmailAddress,
                    IsActive = user.IsActive,
                    IsEmailConfirmationRequired = isEmailConfirmationRequiredForLogin
                }));
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;
                ViewBag.UseCaptcha            = !model.IsExternalLogin && UseCaptchaOnRegistration();
                ViewBag.ErrorMessage          = ex.Message;
                ViewBag.ErrorDetails          = ex.Details;

                return(View("Register", model));
            }
        }
        public async Task <User> RegisterAsync(string name, string surname, string emailAddress, string userName, string plainPassword, string taxId, string serviceType, string npi, string specialty, string primaryContact, string address, string city, string state, string zip, bool isEmailConfirmed, string emailActivationLink)
        {
            bool isActive = false;

            CheckForTenant();
            CheckSelfRegistrationIsEnabled();

            var tenant = await GetActiveTenantAsync();

            //var isNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsNewRegisteredUserActiveByDefault);

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://10.5.1.61:5000/api/eligibility_af/provider");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("?tin=" + taxId);

            if (response.IsSuccessStatusCode)
            {
                string  json    = response.Content.ReadAsStringAsync().Result;
                JObject results = JObject.Parse(json);
                if (results.Count > 0)
                {
                    isActive = true;
                }
            }
            if (surname == null)
            {
                surname = "None";
            }

            await _userPolicy.CheckMaxUserCountAsync(tenant.Id);

            var user = new User
            {
                TenantId         = tenant.Id,
                Name             = name,
                Surname          = surname,
                EmailAddress     = emailAddress,
                IsActive         = isActive,
                UserName         = userName,
                TaxId            = taxId,
                ServiceType      = serviceType,
                Npi              = npi,
                Specialty        = specialty,
                PrimaryContact   = primaryContact,
                Address          = address,
                City             = city,
                State            = state,
                Zip              = zip,
                IsEmailConfirmed = isEmailConfirmed,
                Roles            = new List <UserRole>()
            };

            user.SetNormalizedNames();

            user.Password = _passwordHasher.HashPassword(user, plainPassword);

            foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
            {
                user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
            }

            CheckErrors(await _userManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync();

            if (!user.IsEmailConfirmed)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(user, emailActivationLink);
            }

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

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            await _appNotifier.NewUserRegisteredAsync(user);

            return(user);
        }
예제 #6
0
        public async Task CreateTenant(CreateTenantInput input)
        {
            int  newTenantId;
            long newAdminId;

            using (var uow = UnitOfWorkManager.Begin())
            {
                //Create tenant
                var tenant = new Tenant(input.TenancyName, input.Name)
                {
                    IsActive = input.IsActive, EditionId = input.EditionId
                };
                CheckErrors(await TenantManager.CreateAsync(tenant));
                await CurrentUnitOfWork.SaveChangesAsync(); //To get new tenant's id.

                //We are working entities of new tenant, so changing tenant filter
                using (CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenant.Id))
                {
                    //Create static roles for new tenant
                    CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
                    await CurrentUnitOfWork.SaveChangesAsync(); //To get static role ids

                    //grant all permissions to admin role
                    var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin);
                    await _roleManager.GrantAllPermissionsAsync(adminRole);

                    //User role should be default
                    var userRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.User);
                    userRole.IsDefault = true;
                    CheckErrors(await _roleManager.UpdateAsync(userRole));

                    //Create admin user for the tenant
                    if (input.AdminPassword.IsNullOrEmpty())
                    {
                        input.AdminPassword = User.CreateRandomPassword();
                    }

                    var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress, input.AdminPassword);
                    adminUser.ShouldChangePasswordOnNextLogin = input.ShouldChangePasswordOnNextLogin;
                    adminUser.IsActive = input.IsActive;

                    CheckErrors(await UserManager.CreateAsync(adminUser));
                    await CurrentUnitOfWork.SaveChangesAsync(); //To get admin user's id

                    //Assign admin user to admin role!
                    CheckErrors(await UserManager.AddToRoleAsync(adminUser.Id, adminRole.Name));

                    //Notifications
                    await _appNotifier.WelcomeToTheApplicationAsync(adminUser);

                    //Send activation email
                    if (input.SendActivationEmail)
                    {
                        adminUser.SetNewEmailConfirmationCode();
                        await _userEmailer.SendEmailActivationLinkAsync(adminUser, input.AdminPassword);
                    }

                    await CurrentUnitOfWork.SaveChangesAsync();

                    await _demoDataBuilder.BuildForAsync(tenant);

                    newTenantId = tenant.Id;
                    newAdminId  = adminUser.Id;
                }

                await uow.CompleteAsync();
            }

            //Used a second UOW since UOW above sets some permissions and _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync needs these permissions to be saved.
            using (var uow = UnitOfWorkManager.Begin())
            {
                using (CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, newTenantId))
                {
                    await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(newTenantId, newAdminId);

                    await CurrentUnitOfWork.SaveChangesAsync();
                }

                await uow.CompleteAsync();
            }
        }
예제 #7
0
        public async Task <int> CreateWithAdminUserAsync(
            string tenantType,
            string tenancyName,
            string name,
            string hostAdminEmailAddress,
            string hostAdminPassword,
            string adminPassword,
            string adminEmailAddress,
            string connectionString,
            bool isActive,
            int?editionId,
            bool shouldChangePasswordOnNextLogin,
            bool sendActivationEmail,
            DateTime?subscriptionEndDate,
            bool isInTrialPeriod,
            string emailActivationLink)
        {
            int  newTenantId;
            long newAdminId;

            await CheckEditionAsync(editionId, isInTrialPeriod);

            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                //Create tenant
                var tenant = new Tenant(tenancyName, name)
                {
                    TenantType             = tenantType,
                    IsActive               = isActive,
                    EditionId              = editionId,
                    SubscriptionEndDateUtc = subscriptionEndDate?.ToUniversalTime(),
                    IsInTrialPeriod        = isInTrialPeriod,
                    ConnectionString       = connectionString.IsNullOrWhiteSpace() ? null : SimpleStringCipher.Instance.Encrypt(connectionString)
                };

                await CreateAsync(tenant);

                await _unitOfWorkManager.Current.SaveChangesAsync(); //To get new tenant's id.

                //Create tenant database
                _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);

                //We are working with entities of the new tenant, so changing tenant filter
                using (_unitOfWorkManager.Current.SetTenantId(tenant.Id))
                {
                    List <string> adminPermissions = new List <string>();
                    List <string> userPermissions  = new List <string>();

                    string staticAdminRoleName = string.Empty;
                    string staticUserRoleName  = string.Empty;

                    switch (tenantType)
                    {
                    case "A":
                        staticAdminRoleName = StaticRoleNames.Tenants.AssetOwnerAdmin;
                        staticUserRoleName  = StaticRoleNames.Tenants.AssetOwnerUser;
                        adminPermissions    = TenantPermissionConsts.AssetOwnerAdminPermissions.Split(',').ToList();
                        userPermissions     = TenantPermissionConsts.AssetOwnerUserPermissions.Split(',').ToList();
                        break;

                    case "C":
                        staticAdminRoleName = StaticRoleNames.Tenants.CustomerAdmin;
                        staticUserRoleName  = StaticRoleNames.Tenants.CustomerUser;
                        adminPermissions    = TenantPermissionConsts.CustomerAdminPermissions.Split(',').ToList();
                        userPermissions     = TenantPermissionConsts.CustomerUserPermissions.Split(',').ToList();
                        break;

                    case "V":
                        staticAdminRoleName = StaticRoleNames.Tenants.VendorAdmin;
                        staticUserRoleName  = StaticRoleNames.Tenants.VendorUser;
                        adminPermissions    = TenantPermissionConsts.VendorAdminPermissions.Split(',').ToList();
                        userPermissions     = TenantPermissionConsts.VendorUserPermissions.Split(',').ToList();
                        break;

                    default:
                        throw new Exception($"Cannot determine TenantType for {tenant.TenancyName}!");
                    }

                    //Create static roles for new tenant

                    var hostAdminRole = new Role()
                    {
                        TenantId = tenant.Id, IsDefault = false, IsStatic = true, Name = StaticRoleNames.Tenants.Admin, DisplayName = StaticRoleNames.Tenants.Admin, NormalizedName = StaticRoleNames.Tenants.Admin.ToUpper()
                    };
                    CheckErrors(await _roleManager.CreateAsync(hostAdminRole));

                    var adminRole = new Role()
                    {
                        TenantId = tenant.Id, IsDefault = false, IsStatic = true, Name = staticAdminRoleName, DisplayName = staticAdminRoleName, NormalizedName = staticAdminRoleName.ToUpper()
                    };
                    CheckErrors(await _roleManager.CreateAsync(adminRole));

                    var userRole = new Role()
                    {
                        TenantId = tenant.Id, IsDefault = true, IsStatic = true, Name = staticUserRoleName, DisplayName = staticUserRoleName, NormalizedName = staticUserRoleName.ToUpper()
                    };
                    CheckErrors(await _roleManager.CreateAsync(userRole));

                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get static role ids

                    // Grant permissions to the Admin role
                    foreach (var permission in adminPermissions)
                    {
                        if (permission != "")
                        {
                            await _rolePermissionStore.AddPermissionAsync(adminRole, new PermissionGrantInfo(permission, true));
                        }
                    }

                    // Grant permissions to the User role
                    foreach (var permission in userPermissions)
                    {
                        if (permission != "")
                        {
                            await _rolePermissionStore.AddPermissionAsync(userRole, new PermissionGrantInfo(permission, true));
                        }
                    }

                    //Create the host admin user for the tenant

                    var hostAdminUser = User.CreateTenantHostAdminUser(tenant.Id, hostAdminEmailAddress);
                    hostAdminUser.ShouldChangePasswordOnNextLogin = shouldChangePasswordOnNextLogin;
                    hostAdminUser.IsActive = true;

                    if (hostAdminPassword.IsNullOrEmpty())
                    {
                        hostAdminPassword = await _userManager.CreateRandomPassword();
                    }
                    else
                    {
                        await _userManager.InitializeOptionsAsync(AbpSession.TenantId);

                        foreach (var validator in _userManager.PasswordValidators)
                        {
                            CheckErrors(await validator.ValidateAsync(_userManager, hostAdminUser, hostAdminPassword));
                        }
                    }

                    hostAdminUser.Password = _passwordHasher.HashPassword(hostAdminUser, hostAdminPassword);

                    CheckErrors(await _userManager.CreateAsync(hostAdminUser));
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get hostAdmin user's id

                    //Assign hostAdmin user to hostAdmin role!
                    CheckErrors(await _userManager.AddToRoleAsync(hostAdminUser, hostAdminRole.Name));


                    //Create admin user for the tenant

                    var firstName = adminEmailAddress.Split('@').ToList().FirstOrDefault();

                    Regex rgx         = new Regex("[^a-zA-Z0-9 -]");
                    var   newUserName = string.Format("{0}Admin", rgx.Replace(tenancyName, "").ToLower()).Replace(" ", "");

                    var adminUser = User.CreateTenantAdminUser(tenant.Id, adminEmailAddress, newUserName, firstName, "Admin");
                    adminUser.ShouldChangePasswordOnNextLogin = shouldChangePasswordOnNextLogin;
                    adminUser.IsActive = true;

                    if (adminPassword.IsNullOrEmpty())
                    {
                        adminPassword = await _userManager.CreateRandomPassword();
                    }
                    else
                    {
                        await _userManager.InitializeOptionsAsync(AbpSession.TenantId);

                        foreach (var validator in _userManager.PasswordValidators)
                        {
                            CheckErrors(await validator.ValidateAsync(_userManager, adminUser, adminPassword));
                        }
                    }

                    adminUser.Password = _passwordHasher.HashPassword(adminUser, adminPassword);

                    CheckErrors(await _userManager.CreateAsync(adminUser));
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get admin user's id

                    //Assign admin user to admin role!
                    CheckErrors(await _userManager.AddToRoleAsync(adminUser, adminRole.Name));

                    //Notifications
                    await _appNotifier.WelcomeToTheApplicationAsync(adminUser);

                    //Send activation email
                    if (sendActivationEmail)
                    {
                        adminUser.SetNewEmailConfirmationCode();
                        await _userEmailer.SendEmailActivationLinkAsync(adminUser, emailActivationLink, adminPassword);
                    }

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    await _demoDataBuilder.BuildForAsync(tenant);

                    newTenantId = tenant.Id;
                    newAdminId  = adminUser.Id;
                }

                // Create the AssetOwner, Vendor or Customer

                switch (tenantType)
                {
                case "A":
                    AssetOwner assetOwner = new AssetOwner()
                    {
                        Reference = tenant.TenancyName, Identifier = tenant.TenancyName, Name = tenant.Name, TenantId = tenant.Id
                    };
                    _assetOwnerRepository.Insert(assetOwner);
                    break;

                case "C":

                    var defaultCustomerTypeId = _customerTypeRepository.GetAll().FirstOrDefault().Id;

                    Customer customer = new Customer()
                    {
                        CustomerTypeId = defaultCustomerTypeId, Reference = tenant.TenancyName, Identifier = tenant.TenancyName, Name = tenant.Name, TenantId = tenant.Id
                    };
                    _customerRepository.Insert(customer);
                    break;

                case "V":
                    Vendor vendor = new Vendor()
                    {
                        Reference = tenant.TenancyName, Identifier = tenant.TenancyName, Name = tenant.Name, TenantId = tenant.Id
                    };
                    _vendorRepository.Insert(vendor);
                    break;

                default:
                    throw new Exception($"Cannot determine TenantType for {tenant.TenancyName}!");
                }

                await uow.CompleteAsync();
            }

            // Used a second UOW since the UOW above sets some permissions and _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync needs these permissions to be saved.
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                using (_unitOfWorkManager.Current.SetTenantId(newTenantId))
                {
                    await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(new UserIdentifier(newTenantId, newAdminId));

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    await uow.CompleteAsync();
                }
            }

            return(newTenantId);
        }
예제 #8
0
        protected virtual async Task CreateUserAsync(CreateOrUpdateUserInput input)
        {
            //if (AbpSession.TenantId.HasValue)
            //{
            //    await _userPolicy.CheckMaxUserCountAsync(AbpSession.GetTenantId());
            //}

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

            user.TenantId = AbpSession.TenantId;

            //if (!input.User.Password.IsNullOrEmpty())
            {
                CheckErrors(await UserManager.PasswordValidator.ValidateAsync(input.User.Password));
            }
            //else
            //{
            //    input.User.Password = User.CreateRandomPassword();
            //}

            user.Password = new PasswordHasher().HashPassword(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));
            }
            if (!string.IsNullOrWhiteSpace(user.PhoneNumber) && (await UserManager.FindUserByPhoneNumberAsync(user.PhoneNumber)) != null)
            {
                throw new UserFriendlyException("当前手机号已被注册,创建用户失败");
            }
            CheckErrors(await UserManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync(); //To get new user's Id.

            await SetOrganization(user, input.Organizations);

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

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            try
            {
                if (input.SendActivationEmail && !string.IsNullOrWhiteSpace(input.User.EmailAddress))
                {
                    var body = $"您好,系统已为您创建账号,用户名:{input.User.UserName}, 验证码:{input.User.Password},感谢您使用本系统";
                    if (!input.User.IsActive)
                    {
                        body = $"您好,系统已为您创建账号,用户名:{input.User.UserName}, 验证码:{input.User.Password}," +
                               "首次登陆需要激活帐号,感谢您使用本系统。";
                    }
                    var subject = "账号创建通知";
                    await _emailSender.SendAsync(input.User.EmailAddress, subject, body);
                }
                if (input.SendActivationMessage && !string.IsNullOrWhiteSpace(input.User.PhoneNumber))
                {
                    var body = $"您好,系统已为您创建账号,用户名:{input.User.UserName}, 密码:{input.User.Password},感谢您使用本系统";
                    if (!input.User.IsActive)
                    {
                        body = $"您好,系统已为您创建账号,用户名:{input.User.UserName}, 密码:{input.User.Password},首次登陆需要激活帐号,感谢您使用本系统。";
                    }
                    await _smsSender.Sender(input.User.PhoneNumber, body);
                }
            }
            catch (Exception ex)
            {
                //ignore
            }
        }
예제 #9
0
        public override async Task <UserDto> CreateAsync(CreateUserDto input)
        {
            CheckCreatePermission();

            var user = ObjectMapper.Map <User>(input);

            if (input.RoleTypeList != null && input.RoleTypeList.Count > 0)
            {
                user.InitRoleType = input.RoleTypeList[0];  //初始角色类型
            }

            user.TenantId         = AbpSession.TenantId;
            user.IsEmailConfirmed = true;

            await _userManager.InitializeOptionsAsync(AbpSession.TenantId);

            CheckErrors(await _userManager.CreateAsync(user, input.Password));

            if (input.RoleNames != null)
            {
                CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames));
            }

            CurrentUnitOfWork.SaveChanges();


            await SetOrganization(user, input.Organizations);

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

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            try
            {
                if (input.SendActivationEmail && !string.IsNullOrWhiteSpace(input.EmailAddress))
                {
                    var body = $"您好,系统已为您创建账号,用户名:{input.UserName}, 验证码:{input.Password},感谢您使用本系统";
                    if (!input.IsActive)
                    {
                        body = $"您好,系统已为您创建账号,用户名:{input.UserName}, 验证码:{input.Password}," +
                               "首次登陆需要激活帐号,感谢您使用本系统。";
                    }
                    var subject = "账号创建通知";
                    await _emailSender.SendAsync(input.EmailAddress, subject, body);
                }
                if (input.SendActivationMessage && !string.IsNullOrWhiteSpace(input.PhoneNumber))
                {
                    var body = $"您好,系统已为您创建账号,用户名:{input.UserName}, 密码:{input.Password},感谢您使用本系统";
                    if (!input.IsActive)
                    {
                        body = $"您好,系统已为您创建账号,用户名:{input.UserName}, 密码:{input.Password},首次登陆需要激活帐号,感谢您使用本系统。";
                    }
                    await _smsSender.Sender(input.PhoneNumber, body);
                }
            }
            catch (Exception)
            {
                //ignore
            }
            return(MapToEntityDto(user));
        }
        public async Task CreateUser(AutumnUserDto input)
        {
            try
            {
                var user = ObjectMapper.Map <User>(input); //Passwords is not mapped (see mapping configuration)
                user.TenantId = null;

                await UserManager.InitializeOptionsAsync(AbpSession.TenantId);

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

                user.Password = _passwordHasher.HashPassword(user, input.Password);
                user.Surname  = "xyz";
                //Assign roles
                var role = await _roleManager.GetRoleByNameAsync(StaticRoleNames.Host.User);

                user.Roles              = new Collection <UserRole>();
                user.CreatorUserId      = null;
                user.DeleterUserId      = null;
                user.LastModifierUserId = null;
                user.Roles.Add(new UserRole(null, 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
                //    );
                //}

                var userRetirementPlan = ObjectMapper.Map <UserRetirementPlanDto>(input);
                userRetirementPlan.UserId     = user.Id;
                userRetirementPlan.ReturnRate = 0;
                var countryData = _countryRepository.FirstOrDefault((int)user.CountryId);
                switch (userRetirementPlan.RetirementGoalOptions)
                {
                //Variable legacy
                case RetirementGoalsEnumDto.DesiredRetirementSum:
                    if (userRetirementPlan.DesiredLegacyAmount == null)
                    {
                        userRetirementPlan.DesiredLegacyAmount = 0;
                    }

                    userRetirementPlan.DesiredRetirementIncome = FinancialCalculations.PMT((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, -(double)userRetirementPlan.DesiredRetirementSum, (double)userRetirementPlan.DesiredLegacyAmount) / 12;
                    userRetirementPlan.InitialNet             = userRetirementPlan.InitialSaved - userRetirementPlan.InitialOwed;
                    userRetirementPlan.RequiredSavings        = FinancialCalculations.PMT((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.InitialNet, -(double)userRetirementPlan.DesiredRetirementSum) / 12;
                    userRetirementPlan.TotalMonthlySavings    = userRetirementPlan.TotalMonthlyIncome - userRetirementPlan.TotalMonthlyExpences;
                    userRetirementPlan.LikelyRetirementSum    = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.TotalMonthlySavings * -12, (double)-userRetirementPlan.InitialNet) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.LikelyRetirementLegacy = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, countryData.LifeExpectancy - (double)userRetirementPlan.DesiredRetirementAge, (double)userRetirementPlan.DesiredRetirementIncome * 12, -(double)userRetirementPlan.LikelyRetirementSum);

                    break;

                //Variable legacy
                case RetirementGoalsEnumDto.DesiredRetirementIncome:
                    if (userRetirementPlan.DesiredLegacyAmount == null)
                    {
                        userRetirementPlan.DesiredLegacyAmount = 0;
                    }

                    userRetirementPlan.DesiredRetirementSum   = FinancialCalculations.PV((double)userRetirementPlan.ReturnRate, countryData.LifeExpectancy - (double)userRetirementPlan.DesiredRetirementAge, (double)userRetirementPlan.DesiredRetirementIncome * -12, (double)userRetirementPlan.DesiredLegacyAmount) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.InitialNet             = userRetirementPlan.InitialSaved - userRetirementPlan.InitialOwed;
                    userRetirementPlan.RequiredSavings        = FinancialCalculations.PMT((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.InitialNet, -(double)userRetirementPlan.DesiredRetirementSum) / 12;
                    userRetirementPlan.TotalMonthlySavings    = userRetirementPlan.TotalMonthlyIncome - userRetirementPlan.TotalMonthlyExpences;
                    userRetirementPlan.LikelyRetirementSum    = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.TotalMonthlySavings * -12, (double)-userRetirementPlan.InitialNet) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.LikelyRetirementLegacy = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, countryData.LifeExpectancy - (double)userRetirementPlan.DesiredRetirementAge, (double)userRetirementPlan.DesiredRetirementIncome * 12, -(double)userRetirementPlan.LikelyRetirementSum);

                    break;

                //Variable age
                case RetirementGoalsEnumDto.DesiredLegacyAmount:

                    userRetirementPlan.DesiredRetirementAge = countryData.RetirementAge;
                    userRetirementPlan.DesiredRetirementSum = FinancialCalculations.PV((double)userRetirementPlan.ReturnRate, countryData.LifeExpectancy - (double)userRetirementPlan.DesiredRetirementAge, (double)userRetirementPlan.DesiredRetirementIncome * -12, (double)userRetirementPlan.DesiredLegacyAmount) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.InitialNet           = userRetirementPlan.InitialSaved - userRetirementPlan.InitialOwed;
                    userRetirementPlan.TotalMonthlySavings  = userRetirementPlan.TotalMonthlyIncome - userRetirementPlan.TotalMonthlyExpences;
                    userRetirementPlan.RequiredSavings      = FinancialCalculations.PMT((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.InitialNet, -(double)userRetirementPlan.DesiredRetirementSum) / 12;
                    userRetirementPlan.LikelyRetirementSum  = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.InitialNet * -12, (double)-userRetirementPlan.InitialNet) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.LikelyRetirementAge  = Math.Round((((double)userRetirementPlan.DesiredRetirementSum - (double)userRetirementPlan.LikelyRetirementSum) / (((double)userRetirementPlan.TotalMonthlySavings + (double)userRetirementPlan.DesiredRetirementIncome) * 12)) + (double)userRetirementPlan.DesiredRetirementAge, MidpointRounding.AwayFromZero);

                    break;

                //Variable legacy
                case RetirementGoalsEnumDto.DesiredRetirementAge:
                    if (userRetirementPlan.DesiredLegacyAmount == null)
                    {
                        userRetirementPlan.DesiredLegacyAmount = 0;
                    }

                    userRetirementPlan.DesiredRetirementSum   = FinancialCalculations.PV((double)userRetirementPlan.ReturnRate, countryData.LifeExpectancy - (double)userRetirementPlan.DesiredRetirementAge, (double)userRetirementPlan.DesiredRetirementIncome * -12, (double)userRetirementPlan.DesiredLegacyAmount) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.InitialNet             = userRetirementPlan.InitialSaved - userRetirementPlan.InitialOwed;
                    userRetirementPlan.RequiredSavings        = FinancialCalculations.PMT((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.InitialNet, -(double)userRetirementPlan.DesiredRetirementSum) / 12;
                    userRetirementPlan.TotalMonthlySavings    = userRetirementPlan.TotalMonthlyIncome - userRetirementPlan.TotalMonthlyExpences;
                    userRetirementPlan.LikelyRetirementSum    = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age, (double)userRetirementPlan.TotalMonthlySavings * -12, (double)-userRetirementPlan.InitialNet) * (Math.Pow(1 + (double)userRetirementPlan.ReturnRate, (double)userRetirementPlan.DesiredRetirementAge - (double)user.Age));
                    userRetirementPlan.LikelyRetirementLegacy = FinancialCalculations.FV((double)userRetirementPlan.ReturnRate, countryData.LifeExpectancy - (double)userRetirementPlan.DesiredRetirementAge, (double)userRetirementPlan.DesiredRetirementIncome * 12, -(double)userRetirementPlan.LikelyRetirementSum);

                    break;

                case RetirementGoalsEnumDto.PlaceToLiveAfterRetirement:

                    break;

                default:

                    userRetirementPlan.DesiredRetirementAge = countryData.RetirementAge;
                    userRetirementPlan.DesiredLegacyAmount  = 0;

                    break;
                }

                await _userRetirementPlanRepository.InsertAsync(ObjectMapper.Map <UserRetirementPlan>(userRetirementPlan));
            }
            catch (UserFriendlyException e)
            {
                throw new UserFriendlyException(e.Message);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #11
0
        public async Task <User> RegisterAsync(
            string firstName,
            string lastName,
            string userName,
            string yourName,
            string contentType,
            string contentVolume,
            string industry,
            bool isContentShedule,
            string cms,
            string website,
            string company,
            string userType,
            string phoneNumber,
            string emailAddress,
            string plainPassword,
            bool isEmailConfirmed)
        {
            //CheckForTenant();
            //CheckSelfRegistrationIsEnabled();

            //var tenant = 1;await GetActiveTenantAsync();
            //var isNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsNewRegisteredUserActiveByDefault);
            try
            {
                var companyName = new CompanyInput
                {
                    Name         = company,
                    CreationTime = DateTime.Now
                };
                var companyId = await _companyManager.CreateCompany(companyName);

                //await _userPolicy.CheckMaxUserCountAsync(tenant.Id);


                var user = new User
                {
                    EmailAddress     = emailAddress,
                    IsEmailConfirmed = false,
                    Name             = firstName,
                    Surname          = lastName,
                    UserName         = userName ?? firstName + emailAddress,
                    UserType         = (int)Enum.Parse(typeof(UserType), userType),
                    PhoneNumber      = phoneNumber,
                    CompanyUserId    = companyId,
                    YourName         = yourName,
                    Website          = website,
                    ContentType      = contentType,
                    ContentVolume    = contentVolume,
                    Industry         = industry,
                    IsContentShedule = isContentShedule,
                    CMS        = cms,
                    IsActive   = false,
                    Roles      = new List <UserRole>(),
                    TosVersion = 0,
                    TenantId   = AbpSession.TenantId
                };

                //user.SetNormalizedNames();

                user.Password = _passwordHasher.HashPassword(user, plainPassword);

                foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
                {
                    user.Roles.Add(new UserRole(null, user.Id, defaultRole.Id));
                }

                await _userManager.CreateAsync(user);

                await CurrentUnitOfWork.SaveChangesAsync();

                //if (!user.IsEmailConfirmed)
                //{
                //    user.SetNewEmailConfirmationCode();
                //await _userEmailer.SendEmailActivationLinkAsync(user, emailActivationLink);
                //}

                //Notifications
                _friendshipRepository.Insert(new Friendship(new Abp.UserIdentifier(AbpSession.TenantId, user.Id), new Abp.UserIdentifier(null, 1), "Default", "admin", null, FriendshipState.Accepted));
                var curentTenant = await GetActiveTenantAsync();

                var tenantAdmin = (await _userManager.GetUsersInRoleAsync("Admin")).FirstOrDefault();
                if (tenantAdmin != null)
                {
                    _friendshipRepository.Insert(new Friendship(new Abp.UserIdentifier(AbpSession.TenantId, user.Id), new Abp.UserIdentifier(curentTenant.Id, tenantAdmin.Id), curentTenant.TenancyName, tenantAdmin.Name, null, FriendshipState.Accepted));
                }
                await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());

                await _appNotifier.WelcomeToTheApplicationAsync(user);

                await _appNotifier.NewUserRegisteredAsync(user);

                return(user);
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
예제 #12
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);
            }
        }
예제 #13
0
        public async Task <int> CreateWithAdminUserAsync(string tenancyName, string name, string adminPassword, string adminEmailAddress, string connectionString, bool isActive, int?editionId, bool shouldChangePasswordOnNextLogin, bool sendActivationEmail)
        {
            int  newTenantId;
            long newAdminId;

            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                //Create tenant
                var tenant = new Tenant(tenancyName, name)
                {
                    IsActive         = isActive,
                    EditionId        = editionId,
                    ConnectionString = connectionString.IsNullOrWhiteSpace() ? null : SimpleStringCipher.Instance.Encrypt(connectionString)
                };

                await CreateAsync(tenant);

                await _unitOfWorkManager.Current.SaveChangesAsync(); //To get new tenant's id.

                //Create tenant database
                _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);

                //We are working entities of new tenant, so changing tenant filter
                using (_unitOfWorkManager.Current.SetTenantId(tenant.Id))
                {
                    //Create static roles for new tenant
                    CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get static role ids

                    //grant all permissions to admin role
                    var adminRole = _roleManager.Roles.Single(r => r.Name == StaticNames.Role.Admin);
                    await _roleManager.GrantAllPermissionsAsync(adminRole);

                    //User role should be default
                    var userRole = _roleManager.Roles.Single(r => r.Name == StaticNames.Role.Default);
                    userRole.IsDefault = true;
                    CheckErrors(await _roleManager.UpdateAsync(userRole));

                    //Create admin user for the tenant
                    if (adminPassword.IsNullOrEmpty())
                    {
                        adminPassword = User.CreateRandomPassword();
                    }

                    var adminUser = User.CreateTenantAdminUser(tenant.Id, adminEmailAddress, adminPassword);
                    //  adminUser.ShouldChangePasswordOnNextLogin = shouldChangePasswordOnNextLogin;
                    adminUser.IsActive = true;

                    CheckErrors(await _userManager.CreateAsync(adminUser));
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get admin user's id

                    //Assign admin user to admin role!
                    CheckErrors(await _userManager.AddToRoleAsync(adminUser.Id, adminRole.Name));

                    //Notifications
                    await _appNotifier.WelcomeToTheApplicationAsync(adminUser);

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    newTenantId = tenant.Id;
                    newAdminId  = adminUser.Id;
                }

                await uow.CompleteAsync();
            }

            //Used a second UOW since UOW above sets some permissions and _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync needs these permissions to be saved.
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                using (_unitOfWorkManager.Current.SetTenantId(newTenantId))
                {
                    await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(new UserIdentifier(newTenantId, newAdminId));

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    await uow.CompleteAsync();
                }
            }

            return(newTenantId);
        }