示例#1
0
        public static void SeedIdentity(UserManager <AppUser> userManager, RoleManager <AppRole> roleManager)
        {
            var roleNames = new[] { "Admin", "Customer" };

            foreach (var roleName in roleNames)
            {
                var role = roleManager.FindByNameAsync(roleName).Result;
                if (role == null)
                {
                    role      = new AppRole();
                    role.Name = roleName;
                    var result = roleManager.CreateAsync(role).Result;
                    if (!result.Succeeded)
                    {
                        throw new ApplicationException("Role creation failed!");
                    }
                }
            }

            // ================ ADMIN TEST USER ================

            var userName  = "******";
            var passWord  = "******";
            var firstName = "Test";
            var lastName  = "Admin";
            var phone     = "88005553535";

            var user = userManager.FindByNameAsync(userName).Result;

            if (user == null)
            {
                user = new AppUser
                {
                    Email     = userName,
                    UserName  = userName,
                    FirstName = firstName,
                    LastName  = lastName,
                    Phone     = phone,
                    Id        = new Guid("00000000-0000-0000-0000-000000000001")
                };

                var result = userManager.CreateAsync(user, passWord).Result;
                if (!result.Succeeded)
                {
                    throw new ApplicationException("User creation failed!");
                }

                var identityResult = userManager.AddToRoleAsync(user, "Admin").Result;
            }

            // ================ CUSTOMER TEST USER ================


            userName  = "******";
            passWord  = "******";
            firstName = "Test";
            lastName  = "Customer";
            phone     = "88005553535";

            user = userManager.FindByNameAsync(userName).Result;
            if (user == null)
            {
                user = new AppUser
                {
                    Email     = userName,
                    UserName  = userName,
                    FirstName = firstName,
                    LastName  = lastName,
                    Phone     = phone,
                    Id        = new Guid("00000000-0000-0000-0000-000000000002")
                };

                var result = userManager.CreateAsync(user, passWord).Result;
                if (!result.Succeeded)
                {
                    throw new ApplicationException("User creation failed!");
                }

                var identityResult = userManager.AddToRoleAsync(user, "Customer").Result;
            }
        }
示例#2
0
        public async Task <IActionResult> Register([FromBody] RegisterDTO dto)
        {
            var appUser = await _userManager.FindByEmailAsync(dto.Email);

            if (appUser != null)
            {
                _logger.LogInformation($"WebApi register. User {dto.Email} already registered!");
                return(NotFound(new MessageDTO("User already registered!")));
            }

            appUser = new AppUser()
            {
                Email     = dto.Email,
                UserName  = dto.Email,
                FirstName = dto.FirstName,
                LastName  = dto.LastName,
                Phone     = dto.Phone
            };
            var result = await _userManager.CreateAsync(appUser, dto.Password);

            await _userManager.AddToRolesAsync(appUser, dto.Roles);

            if (result.Succeeded)
            {
                _logger.LogInformation($"User {appUser.Email} created a new account with password.");
                var user = await _userManager.FindByEmailAsync(appUser.Email);

                if (user != null)
                {
                    var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);

                    var jwt = IdentityExtensions.GenerateJWT(
                        claimsPrincipal.Claims
                        .Append(new Claim(ClaimTypes.GivenName, appUser.FirstName))
                        .Append(new Claim(ClaimTypes.Surname, appUser.LastName)),
                        _configuration["JWT:SigningKey"],
                        _configuration["JWT:Issuer"],
                        _configuration.GetValue <int>("JWT:ExpirationInDays")
                        );
                    _logger.LogInformation($"WebApi register. User {user.Email} logged in.");
                    return(Ok(new JwtResponseDTO()
                    {
                        Token = jwt,
                        Status = $"User {user.Email} created and logged in.",
                        FirstName = appUser.FirstName,
                        LastName = appUser.LastName,
                        Roles = _userManager.GetRolesAsync(appUser)?.Result ?? new Collection <string>()
                    }));
                }

                _logger.LogInformation($"User {appUser.Email} not found after creation!");
                return(BadRequest(new MessageDTO("User not found after creation!")));
            }

            var errors = result.Errors.Select(error => error.Description).ToList();

            return(BadRequest(new MessageDTO()
            {
                Messages = errors
            }));
        }