public UserSessionModel AuthenticateUser(UserAuthenticationEditModel model)
        {
            var userSessionModel = new UserSessionModel();
            var userEmail        = model.Email.Trim().ToLower();

            var userLogin = (from u in _userLoginRepository.List
                             join p in _personRepository.List on u.UserName equals p.Email
                             where u.UserName == userEmail
                             select new
            {
                u.UserName,
                p.FirstName,
                p.LastName
            }).FirstOrDefault();

            if (userLogin != null)
            {
                string    salt           = GetSaltForUser(model.Email.ToLower());
                string    hashedPassword = _encryptionService.GetUserHashedPassword(salt, model.Password);
                UserLogin verifiedPerson = _userLoginRepository.Get(x => x.UserName == model.Email.ToLower() && x.Password == hashedPassword);

                if (verifiedPerson != null)
                {
                    var tokenHandler = new JwtSecurityTokenHandler();

                    var key = Encoding.ASCII.GetBytes(_appSettings.Secret);

                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject            = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userLogin.UserName.ToString()) }),
                        Expires            = DateTime.UtcNow.AddDays(1),
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                    };

                    var token = tokenHandler.CreateToken(tokenDescriptor);
                    userSessionModel.Token = tokenHandler.WriteToken(token);


                    userSessionModel = CreateSessionModel(userSessionModel, userLogin.UserName, userLogin.FirstName, userLogin.LastName);

                    userSessionModel.Message = "Welcome " + userSessionModel.FullName;
                }
                else
                {
                    userSessionModel.IsAuthenticated = false;
                    userSessionModel.Message         = "Invalid username and password combination. Please try again !";
                }
            }

            else
            {
                userSessionModel.IsAuthenticated = false;
                userSessionModel.Message         = "User doesn't exists for the given username";
            }

            return(userSessionModel);
        }
Exemplo n.º 2
0
 public UserSessionModel AuthenticateUser([FromBody] UserAuthenticationEditModel model)
 {
     return(_authenticationService.AuthenticateUser(model));
 }