/// <summary> /// This method is responsable for handling the validation and verification of the users login attempt /// </summary> /// <param name="request">the users login information</param> /// <returns>The response which indicates if they are sucessful and the bearer token /// they will use for authentication on success</returns> public LoginResponse LoginUser(LoginRequest request) { s_logger.Info("Attempting to log in..."); LoginResponse response = new LoginResponse(); try { //Validate input response = (LoginResponse)request.CheckValidation(response); if (response.Status == HttpStatusCode.BadRequest) { return(response); } var dataLayer = new UsersDataLayer(); //Verify user exists UserDTO user = dataLayer.GetUserByUsername(request.Username); if (user == null) { response.Token = string.Empty; response.Status = HttpStatusCode.BadRequest; response.StatusMessages.Add(new StatusMessage(HttpStatusCode.BadRequest, "Unable to login username or password is incorrect")); s_logger.Warn($"Unable to login as a username [ {request.Username} ], username or password is incorrect."); return(response); } // Ensure that their password is correct string hashedPassword = HashText(request.Password); if (user.Password != hashedPassword) { response.Token = string.Empty; response.Status = HttpStatusCode.BadRequest; response.StatusMessages.Add(new StatusMessage(HttpStatusCode.BadRequest, "Unable to login username or password is incorrect")); s_logger.Warn($"Unable to login as a username [ {request.Username} ], username or password is incorrect."); return(response); } // Generate users bearer token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.AppSecret); var tokenDescriptior = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.Sid, user.UserId.ToString()) }), Expires = DateTime.Now.AddHours(4), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature) }; var rawToken = tokenHandler.CreateToken(tokenDescriptior); var token = tokenHandler.WriteToken(rawToken); response.Token = token; if (user.FirstTime) { response.Status = HttpStatusCode.Accepted; response.UserId = user.UserId; return(response); } response.Status = HttpStatusCode.OK; } catch (Exception ex) { s_logger.Error(ex, "Unable to perform log in attempt."); response = new LoginResponse { Token = string.Empty, Status = HttpStatusCode.InternalServerError }; response.StatusMessages.Add(new StatusMessage(HttpStatusCode.InternalServerError, "Unable to perform log in attempt.")); } return(response); }