Пример #1
0
        public IActionResult Login(UserForLoginResource userForLoginDto)
        {
            var loginUser = _repo.FindUserByEmail(userForLoginDto.email);

            if (loginUser == null)
            {
                return(Ok(new { error = "100" }));
            }
            if (loginUser.isDeleted)
            {
                return(Ok(new { error = "105" }));
            }
            if (!_repo.IsActiveUser(userForLoginDto.email))
            {
                return(Ok(new { error = "102" }));
            }

            var userFromRepo = _repo.Login(userForLoginDto.email, userForLoginDto.password);

            if (userFromRepo == null)
            {
                return(Ok(new { error = "101" }));
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.firstName),
                new Claim(ClaimTypes.Role, userFromRepo.isAdmin.ToString())
            };

            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(180),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var data = new
            {
                userFromRepo.id,
                userFromRepo.firstName,
                userFromRepo.lastName,
                token = tokenHandler.WriteToken(token)
            };

            return(Ok(new { data }));
        }
        public async Task <IActionResult> Login(UserForLoginResource userForLogin)
        {
            var user = await _usermanager.FindByNameAsync(userForLogin.UserName.ToUpper());

            if (user == null)
            {
                return(BadRequest("Faild to find Username"));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLogin.Password, false);

            if (result.Succeeded)
            {
                var userToReturn = _mapper.Map <UserForListResource>(user);

                return(Ok(new
                {
                    token = GenerateJwtToken(user).Result,
                    user = userToReturn
                }));
            }

            return(Unauthorized());
        }