mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 23:00:07 +01:00
88 lines
2.8 KiB
C#
88 lines
2.8 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using QuotifyBE.Controllers;
|
|
using QuotifyBE.DTOs;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
namespace QuotifyBE.Controllers
|
|
{
|
|
|
|
[ApiController]
|
|
[Route("[controller]")]
|
|
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;
|
|
private readonly IConfiguration _appsettings;
|
|
|
|
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration appsettings)
|
|
{
|
|
_logger = logger;
|
|
_appsettings = appsettings;
|
|
}
|
|
|
|
[HttpGet(Name = "GetWeatherForecast")]
|
|
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("login")]
|
|
public IActionResult Login([FromBody] UserLoginDTO user)
|
|
{
|
|
if (user.Email == "admin" && user.Password == "password")
|
|
{
|
|
var token = GenerateJwtToken(user.Email);
|
|
return Ok(new { token });
|
|
}
|
|
return Unauthorized();
|
|
}
|
|
|
|
[HttpGet("some_values")]
|
|
[Authorize]
|
|
public IActionResult GetValues()
|
|
{
|
|
return Ok(new string[] { "value1", "value2" });
|
|
}
|
|
|
|
private string GenerateJwtToken(string username)
|
|
{
|
|
var claims = new[]
|
|
{
|
|
new Claim(JwtRegisteredClaimNames.Sub, username),
|
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
|
};
|
|
|
|
var key = new SymmetricSecurityKey(
|
|
Encoding.UTF8.GetBytes(_appsettings["JwtSecret"]!)
|
|
// won't be null here - otherwise Program.cs wouldn't start
|
|
);
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: _appsettings["DomainName"]!,
|
|
audience: _appsettings["DomainName"]!,
|
|
claims: claims,
|
|
expires: DateTime.Now.AddDays(7),
|
|
signingCredentials: creds
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|
|
}
|