Пример #1
0
        public async Task <ApplicationUser> RegisterNewUserAsync(string userName, string email, string password, bool requireConfirmEmail)
        {
            var user = new ApplicationUser
            {
                UserName = userName,
                Email    = email
            };

            var result = password == null ?
                         await _userManager.CreateAsync(user) :
                         await _userManager.CreateAsync(user, password);

            if (!result.Succeeded)
            {
                throw new DomainException(string.Join(",", result.Errors.Select(i => i.Description)));
            }

            await _userManager.AddClaimsAsync(user, new Claim[] {
                new Claim(Policies.IsUser, string.Empty),
                new Claim(JwtClaimTypes.Name, user.UserName),
                new Claim(JwtClaimTypes.Email, user.Email),
                new Claim(JwtClaimTypes.EmailVerified, "false", ClaimValueTypes.Boolean)
            });

            if (await _roleManager.RoleExistsAsync(DefaultRoleNames.User))
            {
                await _userManager.AddToRoleAsync(user, DefaultRoleNames.User);
            }

            _logger.LogInformation("New user registered: {0}", user);

            var emailMessage = new EmailMessageDto();

            if (requireConfirmEmail)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = $"{_configuration["BlazorBoilerplate:ApplicationUrl"]}/Account/ConfirmEmail/{user.Id}?token={token}";

                emailMessage.BuildNewUserConfirmationEmail(user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form
            }
            else
            {
                emailMessage.BuildNewUserEmail(user.FullName, user.UserName, user.Email, password);
            }

            emailMessage.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));

            try
            {
                await _emailManager.SendEmailAsync(emailMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError("New user email failed: Body: {0}, Error: {1}", emailMessage.Body, ex.GetBaseException().Message);
            }

            return(user);
        }
Пример #2
0
        public async Task <ApplicationUser> RegisterNewUserAsync(string userName, string email, string password, bool requireConfirmEmail)
        {
            var user = new ApplicationUser
            {
                UserName = userName,
                Email    = email
            };

            var createUserResult = password == null ?
                                   await _userManager.CreateAsync(user) :
                                   await _userManager.CreateAsync(user, password);

            if (!createUserResult.Succeeded)
            {
                throw new DomainException(createUserResult.Errors.FirstOrDefault()?.Description);
            }

            await _userManager.AddClaimsAsync(user, new Claim[] {
                new Claim(Policies.IsUser, ""),
                new Claim(JwtClaimTypes.Name, user.UserName),
                new Claim(JwtClaimTypes.Email, user.Email),
                new Claim(JwtClaimTypes.EmailVerified, "false", ClaimValueTypes.Boolean)
            });

            //Role - Here we tie the new user to the "User" role
            await _userManager.AddToRoleAsync(user, "User");

            _logger.LogInformation("New user registered: {0}", user);

            var emailMessage = new EmailMessageDto();

            if (requireConfirmEmail)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["BlazorBoilerplate:ApplicationUrl"], user.Id, token);

                emailMessage.BuildNewUserConfirmationEmail(user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form
            }
            else
            {
                emailMessage.BuildNewUserEmail(user.FullName, user.UserName, user.Email, password);
            }

            emailMessage.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
            try
            {
                await _emailService.SendEmailAsync(emailMessage);
            }
            catch (Exception ex)
            {
                _logger.LogInformation("New user email failed: Body: {0}, Error: {1}", emailMessage.Body, ex.Message);
            }

            return(user);
        }
Пример #3
0
        public async Task <ApiResponse> Create(RegisterDto parameters)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(new ApiResponse(400, "User Model is Invalid"));
                }

                var user = new ApplicationUser
                {
                    UserName = parameters.UserName,
                    Email    = parameters.Email
                };

                user.UserName = parameters.UserName;
                var result = await _userManager.CreateAsync(user, parameters.Password);

                if (!result.Succeeded)
                {
                    return(new ApiResponse(400, "Register User Failed: " + result.Errors.FirstOrDefault()?.Description));
                }
                else
                {
                    var claimsResult = _userManager.AddClaimsAsync(user, new Claim[] {
                        new Claim(Policies.IsUser, ""),
                        new Claim(JwtClaimTypes.Name, parameters.UserName),
                        new Claim(JwtClaimTypes.Email, parameters.Email),
                        new Claim(JwtClaimTypes.EmailVerified, "false", ClaimValueTypes.Boolean)
                    }).Result;
                }

                //Role - Here we tie the new user to the "User" role
                await _userManager.AddToRoleAsync(user, "User");

                if (Convert.ToBoolean(_configuration["BlazorBoilerplate:RequireConfirmedEmail"] ?? "false"))
                {
                    #region New  User Confirmation Email

                    try
                    {
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                        var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["BlazorBoilerplate:ApplicationUrl"], user.Id, token);

                        var email = new EmailMessageDto();
                        email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
                        email = EmailTemplates.BuildNewUserConfirmationEmail(email, user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form

                        _logger.LogInformation("New user created: {0}", user);
                        await _emailService.SendEmailAsync(email);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogInformation("New user email failed: {0}", ex.Message);
                    }

                    #endregion New  User Confirmation Email

                    return(new ApiResponse(200, "Create User Success"));
                }

                #region New  User Email

                try
                {
                    var email = new EmailMessageDto();
                    email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
                    email.BuildNewUserEmail(user.FullName, user.UserName, user.Email, parameters.Password);

                    _logger.LogInformation("New user created: {0}", user);
                    await _emailService.SendEmailAsync(email);
                }
                catch (Exception ex)
                {
                    _logger.LogInformation("New user email failed: {0}", ex.Message);
                }

                #endregion New  User Email

                UserInfoDto userInfo = new UserInfoDto
                {
                    IsAuthenticated = false,
                    UserName        = user.UserName,
                    Email           = user.Email,
                    FirstName       = user.FirstName,
                    LastName        = user.LastName,
                    //ExposedClaims = user.Claims.ToDictionary(c => c.Type, c => c.Value),
                    Roles = new List <string> {
                        "User"
                    }
                };

                return(new ApiResponse(200, "Created New User", userInfo));
            }
            catch (Exception ex)
            {
                _logger.LogError("Create User Failed: {0}", ex.Message);
                return(new ApiResponse(400, "Create User Failed"));
            }
        }
Пример #4
0
        public async Task <ApiResponse> Create(RegisterViewModel parameters)
        {
            var user = new ApplicationUser
            {
                UserName = parameters.UserName,
                Email    = parameters.Email
            };

            user.UserName = parameters.UserName;
            var result = await _userManager.CreateAsync(user, parameters.Password);

            if (!result.Succeeded)
            {
                var msg = string.Join(",", result.Errors.Select(i => i.Description));
                _logger.LogWarning($"Error while creating {user.UserName}: {msg}");
                return(new ApiResponse(Status400BadRequest, msg));
            }
            else
            {
                var claimsResult = _userManager.AddClaimsAsync(user, new Claim[] {
                    new Claim(Policies.IsUser, string.Empty),
                    new Claim(JwtClaimTypes.Name, parameters.UserName),
                    new Claim(JwtClaimTypes.Email, parameters.Email),
                    new Claim(JwtClaimTypes.EmailVerified, "false", ClaimValueTypes.Boolean)
                }).Result;
            }

            var defaultRoleExists = await _roleManager.RoleExistsAsync(DefaultRoleNames.User);

            if (defaultRoleExists)
            {
                await _userManager.AddToRoleAsync(user, DefaultRoleNames.User);
            }

            if (Convert.ToBoolean(_configuration["BlazorBoilerplate:RequireConfirmedEmail"] ?? "false"))
            {
                try
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["BlazorBoilerplate:ApplicationUrl"], user.Id, token);

                    var email = new EmailMessageDto();
                    email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
                    email = EmailTemplates.BuildNewUserConfirmationEmail(email, user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form

                    _logger.LogInformation("New user created: {0}", user);
                    await _emailManager.SendEmailAsync(email);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"New user email failed: {ex.GetBaseException().Message}");
                }

                return(new ApiResponse(Status200OK, "Create User Success"));
            }

            try
            {
                var email = new EmailMessageDto();
                email.ToAddresses.Add(new EmailAddressDto(user.Email, user.Email));
                email.BuildNewUserEmail(user.FullName, user.UserName, user.Email, parameters.Password);

                _logger.LogInformation("New user created: {0}", user);
                await _emailManager.SendEmailAsync(email);
            }
            catch (Exception ex)
            {
                _logger.LogError($"New user email failed: {ex.GetBaseException().Message}");
            }

            var userViewModel = new UserViewModel
            {
                UserId          = user.Id,
                IsAuthenticated = false,
                UserName        = user.UserName,
                Email           = user.Email,
                FirstName       = user.FirstName,
                LastName        = user.LastName
            };

            if (defaultRoleExists)
            {
                userViewModel.Roles = new List <string> {
                    DefaultRoleNames.User
                }
            }
            ;

            return(new ApiResponse(Status200OK, L["User {0} created", userViewModel.UserName], userViewModel));
        }