using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Nodes;
namespace GeeksForGeeks_API_Project.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy",
"Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[Authorize]
[HttpGet(Name = "GetWeatherForecast"), Authorize]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
[HttpPost]
public IActionResult SignIn([FromBody] SignInModel signInModel)
{
if (signInModel.Email != "[email protected]")
return NotFound(new JsonObject() { { "Error", "User Not Found" } });
bool result = signInModel.Email == "[email protected]"
&& signInModel.Password == "test@1234";
if (result)
{
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, signInModel.Email),
new Claim(ClaimTypes.Email, signInModel.Email),
new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti ,
Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("+)
3@5!7#9$0%2^4&+)3@5!7#9$0%2^4&6*8(06*8(0+)3@5!7#9$0%2^4&6*8(07#9$0%2^4&"));
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(authClaims),
Expires = DateTime.UtcNow.AddHours(24 - DateTime.UtcNow.Hour),
SigningCredentials = new SigningCredentials(key,
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(new JsonObject { { "Success", "User Logged In" },
{ "User", tokenHandler.WriteToken(token).ToString() },
{ "Valid", token.ValidTo } });
}
return BadRequest(new JsonObject() { { "Error", "Wrong Password" } });
}
}
}