Esempio n. 1
0
        public async Task <ActionResult> Login(UserVM userVM)
        {
            var getUser = _userRepository.GetByEmail(userVM.Email);

            if (getUser == null)
            {
                return(BadRequest("Email Wrong!"));
            }
            else
            {
                //Lockout account
                if (getUser.LockStatus == true)
                {
                    return(BadRequest("Your Account is Locked, Please Try Again Later or Reset Your Password"));
                }
                else
                {
                    var check = BCryptHelper.CheckPassword(userVM.Password, getUser.Password);
                    if (check == false)
                    {
                        //Lockout function
                        await LockedOut(getUser);

                        return(BadRequest("Password Wrong!"));
                    }
                    else
                    {
                        //Reset lockedout account count after succesfull login
                        getUser.FailCount = 0;
                        await _userRepository.Put(getUser);

                        //Get Role From User Login
                        var dataRole = await _roleRepository.GetRole(getUser.Id);

                        foreach (Role item in dataRole)
                        {
                            userVM.RoleName = item.Name;
                        }
                        //Get Data From User Detail
                        var detailUser = await _userDetailsRepository.Get(getUser.Id);

                        //Build JWToken
                        var claims = new List <Claim>
                        {
                            new Claim("Id", getUser.Id.ToString()),
                            new Claim("Email", userVM.Email),
                            new Claim("Role", userVM.RoleName),
                            new Claim("App", getUser.App_Type.ToString()),
                            new Claim("Name", detailUser.FirstName + " " + detailUser.LastName)
                        };

                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

                        var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

                        return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
                    }
                }
            }
        }