示例#1
0
        public async Task <IResponseDTO> CreateUser(CreateUpdateUserDto options, int userId)
        {
            try
            {
                // Generate user password
                var password = GeneratePassword();
                var appUser  = _mapper.Map <ApplicationUser>(options);
                appUser.CreatedBy      = userId;
                appUser.CreatedOn      = DateTime.Now;
                appUser.UserName       = appUser.Email;
                appUser.ChangePassword = true;
                appUser.Status         = UserStatusEnum.Active.ToString();
                appUser.UserRoles      = new List <ApplicationUserRole>
                {
                    new ApplicationUserRole
                    {
                        RoleId = options.RoleId
                    }
                };

                // Create the user
                IdentityResult result = await _userManager.CreateAsync(appUser, password);

                if (!result.Succeeded)
                {
                    _response.IsPassed = false;
                    _response.Errors   = result.Errors.Select(x => x.Description).ToList();
                    return(_response);
                }

                // send email to the user to change his password
                var verifyEmailToken = await _userManager.GeneratePasswordResetTokenAsync(appUser);

                verifyEmailToken = WebUtility.UrlEncode(verifyEmailToken);
                await _emailService.AfterRegistiration(appUser.Email, verifyEmailToken);

                _response.IsPassed = true;
                _response.Message  = "Email was sent to the user email so he can set his password.";
            }
            catch (Exception ex)
            {
                _response.Data     = null;
                _response.IsPassed = false;
                _response.Errors.Add($"Error: {ex.Message}");
            }

            return(_response);
        }