C#
[HttpPost]
public IActionResult Login(LogInAndSignUp user)
{
var logUser = context.LogInAndSignUps.Where(x => x.Email == user.Email && x.Password == user.Password).FirstOrDefault();
if (logUser != null)
{
// Generate JWT token
var token = GenerateJwtToken(logUser);
// Set the token in a cookie
var cookieOptions = new CookieOptions
{
HttpOnly = true, // Prevents JavaScript from accessing the cookie
Expires = DateTime.Now.AddMinutes(30) // Set expiration time for the token
};
Response.Cookies.Append("UserToken", token, cookieOptions);
// Redirect to the dashboard
return RedirectToAction("Dashboard");
}
else
{
ViewBag.Message = "Login Failed";
}
return View();
}
[Authorize]
public IActionResult Dashboard()
{
Console.WriteLine("Dashboard action called.");
var userEmail = HttpContext.Session.GetString("UserSession");
//var userEmail = User.FindFirstValue(JwtRegisteredClaimNames.Sub); // Extract email from token
if (userEmail != null)
{
var user = context.LogInAndSignUps.Where(x => x.Email == userEmail).FirstOrDefault();
if (user != null)
{
return View(user);
}
}
return RedirectToAction("Login");
}