예제 #1
0
        public async Task <IActionResult> Login([FromBody] UserForLoginDto userForRegisterDto)
        {
            if (_repo.ValidarConfirmacion(userForRegisterDto.Email) == false)
            {
                var numeroNuevo = _repo.NumeroConfirmacion();
                _repo.ActualizarNumeroConfirmacion(userForRegisterDto.Email, numeroNuevo);
                return(Ok("SINCONFIRMAR"));
            }



            var userFromRepo = await _repo.Login(userForRegisterDto.Email.ToLower(), userForRegisterDto.Password);

            if (userFromRepo == null) //User login failed
            {
                return(Ok(false));
            }

            //generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                    new Claim(ClaimTypes.Name, userFromRepo.Email)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
            };

            var tokenCreated = tokenHandler.CreateToken(tokenDescriptor);
            var token        = tokenHandler.WriteToken(tokenCreated);

            TokenValidate tokenValidate = new TokenValidate();

            tokenValidate.Cliente         = userFromRepo.NumeroCliente;
            tokenValidate.WebToken        = token;
            tokenValidate.FechaGeneracion = DateTime.Now;

            await _repo.InsertToken(tokenValidate);

            return(Ok(new { token, userFromRepo.NumeroCliente }));
        }