예제 #1
0
        private async Task SetAuthenticationToken()
        {
            UserType userType = UserTypeFactory.Default();
            UserType admin    = UserTypeFactory.Default().WithName("Admin");

            City city = CityFactory.Default();

            await ExecuteDatabaseAction(async (doFestContext) =>
            {
                await doFestContext.UserTypes.AddAsync(userType);
                await doFestContext.UserTypes.AddAsync(admin);
                await doFestContext.Cities.AddAsync(city);
                await doFestContext.SaveChangesAsync();
                CityId = city.Id;
            });

            var userRegisterModel = new RegisterModel
            {
                Username       = "******",
                Age            = 20,
                BucketListName = "test bucketlist",
                City           = city.Id,
                Email          = "*****@*****.**",
                Name           = "testtest",
                Password       = "******",
                Year           = 3
            };

            var userRegisterResponse = await HttpClient.PostAsJsonAsync($"api/v1/auth/register", userRegisterModel);

            userRegisterResponse.IsSuccessStatusCode.Should().BeTrue();
            if (_isAdmin == true)
            {
                var userRespository    = new UserRepository(dbContext);
                var userTypeRepository = new UserTypeRepository(userTypeDbContext);
                var userTypeAdmin      = await userTypeRepository.GetByName("Admin");

                var user = await userRespository.GetByEmail(userRegisterModel.Email);

                user.UserTypeId = userTypeAdmin.Id;
                userRespository.Update(user);
                await userRespository.SaveChanges();
            }
            var authenticateModel = new LoginModelRequest
            {
                Email    = userRegisterModel.Email,
                Password = userRegisterModel.Password
            };
            var userAuthenticateResponse = await HttpClient.PostAsJsonAsync($"api/v1/auth/login", authenticateModel);

            userAuthenticateResponse.IsSuccessStatusCode.Should().BeTrue();
            AuthenticatedUserId = new Guid();
            var authenticationResponseContent = await userAuthenticateResponse.Content.ReadAsAsync <LoginModelResponse>();

            var stream  = authenticationResponseContent.Token;
            var handler = new JwtSecurityTokenHandler();
            var tokenS  = handler.ReadToken(stream) as JwtSecurityToken;

            AuthenticatedUserId = new Guid(tokenS.Claims.First(x => x.Type == "userId").Value);

            AuthenticationToken = authenticationResponseContent.Token;
        }