コード例 #1
0
        public async Task <IActionResult> Login(UserLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Email, userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Email, userFromRepo.Email)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var userGrids = await _cakeRepo.GetUserGrids(userFromRepo.Id);

            var userGridsDto = new List <GridLogin>();

            foreach (var grid in userGrids)
            {
                var dto = new GridLogin(grid.Id, grid.Name);
                userGridsDto.Add(dto);
            }

            return(Ok(new {
                token = tokenHandler.WriteToken(token),
                user = userFromRepo,
                userGrids = userGridsDto
            }));
        }