コード例 #1
0
        public static async Task <string> RunAsUserAsync(string userName, string password, string[] roles)
        {
            using var scope = _scopeFactory.CreateScope();

            var userManager = scope.ServiceProvider.GetService <UserManager <Infrastructure.Identity.ApplicationUser> >();

            var user = new Infrastructure.Identity.ApplicationUser {
                UserName = userName, Email = userName
            };

            var result = await userManager.CreateAsync(user, password);

            if (roles.Any())
            {
                var roleManager = scope.ServiceProvider.GetService <RoleManager <IdentityRole> >();

                foreach (var role in roles)
                {
                    await roleManager.CreateAsync(new IdentityRole(role));
                }

                await userManager.AddToRolesAsync(user, roles);
            }

            if (result.Succeeded)
            {
                _currentUserId = user.Id;

                return(_currentUserId);
            }

            var errors = string.Join(Environment.NewLine, result.ToApplicationResult().Errors);

            throw new Exception($"Unable to create {userName}.{Environment.NewLine}{errors}");
        }
コード例 #2
0
        private async Task <Result> DeleteUserAsync(ApplicationUser user)
        {
            var result = await _userManager.UpdateAsync(user);

            return(result.ToApplicationResult());
        }
コード例 #3
0
        private async Task <AuthenticationResult> GenerateAuthenticationResultForUserAsync(ApplicationUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_jwtSettings.Secret);

            var userProfile = await GetUserProfileByUserId(user.Id);

            var employee = await _context.Employees.FirstOrDefaultAsync(x => x.UserProfileId == userProfile.Id);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim("firstName", userProfile.FirstName),
                new Claim("lastName", userProfile.LastName),
                new Claim("id", userProfile.Id.ToString())
            };

            if (employee != null)
            {
                claims.Add(new Claim("clinicId", employee.ClinicId.ToString()));
            }

            var userClaims = await _userManager.GetClaimsAsync(user);

            claims.AddRange(userClaims);

            var userRoles = await _userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                var role = await _roleManager.FindByNameAsync(userRole);

                if (role == null)
                {
                    continue;
                }
                var roleClaims = await _roleManager.GetClaimsAsync(role);

                foreach (var roleClaim in roleClaims)
                {
                    if (claims.Contains(roleClaim))
                    {
                        continue;
                    }

                    claims.Add(roleClaim);
                }
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.Add(_jwtSettings.TokenLifetime),
                SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            await _context.SaveChangesAsync();

            return(new AuthenticationResult
            {
                Success = true,
                Token = tokenHandler.WriteToken(token)
            });
        }
コード例 #4
0
        public async Task <AuthenticationResult> RegisterAsync(AddUserCommand userToAdd)
        {
            var existingUser = await _userManager.FindByEmailAsync(userToAdd.Email);

            if (existingUser != null)
            {
                return new AuthenticationResult
                       {
                           Errors = new[] { "User with this email address already exists" }
                       }
            }
            ;

            await using var transaction = await _context.Database.BeginTransactionAsync();

            try
            {
                var user = new ApplicationUser
                {
                    UserName    = userToAdd.Email,
                    Email       = userToAdd.Email,
                    PhoneNumber = userToAdd.PhoneNumber
                };

                var createdUser = await _userManager.CreateAsync(user, userToAdd.Password);

                if (!createdUser.Succeeded)
                {
                    return new AuthenticationResult
                           {
                               Errors = createdUser.Errors.Select(x => x.Description)
                           }
                }
                ;

                await _userManager.AddToRoleAsync(user, RoleConstants.User);

                var userProfile = new UserProfile
                {
                    FirstName    = userToAdd.FirstName,
                    MiddleName   = userToAdd.MiddleName,
                    LastName     = userToAdd.LastName,
                    Address      = userToAdd.Address,
                    StreetName   = userToAdd.StreetName,
                    StreetNo     = userToAdd.StreetNo,
                    CNP          = userToAdd.Cnp,
                    CountryId    = userToAdd.CountryId,
                    CountyId     = userToAdd.CountyId,
                    CityId       = userToAdd.CityId,
                    GenderId     = userToAdd.GenderId,
                    EmailAddress = userToAdd.Email,
                    PhoneNumber  = userToAdd.PhoneNumber,
                    UserId       = user.Id
                };

                await _context.AddAsync(userProfile);

                await _context.SaveChangesAsync();

                // Commit transaction if all commands succeed, transaction will auto-rollback
                // when disposed if either commands fails
                await transaction.CommitAsync();

                return(await GenerateAuthenticationResultForUserAsync(user));
            }
            catch (Exception e)
            {
                await transaction.RollbackAsync();

                throw new Exception(e.ToString());
            }
        }