diff --git a/Controllers/AuthController.cs b/Controllers/AuthController.cs new file mode 100644 index 0000000..5ef685e --- /dev/null +++ b/Controllers/AuthController.cs @@ -0,0 +1,41 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using QuotifyBE.Data; +using QuotifyBE.DTOs; + +namespace QuotifyBE.Controllers; + + +[ApiController] +[Route("api/v1/auth")] +public class AuthController : ControllerBase +{ + + private readonly IConfiguration _appsettings; + private readonly ApplicationDbContext _db; + + public AuthController(IConfiguration appsettings, ApplicationDbContext db) + { + _db = db; + _appsettings = appsettings; + } + + [HttpPost("login")] + public IActionResult Login([FromBody] UserLoginDTO user, GeneralUseHelpers guhf) + { + if (user.Email == "admin" && user.Password == "password") + { + var token = guhf.GenerateJwtToken(user.Email, _appsettings); + return Ok(new { token }); + } + return Unauthorized(); + } + + [HttpGet("some_values")] + [Authorize] + public IActionResult GetValues() + { + return Ok(new string[] { "value1", "value2" }); + } + +} diff --git a/Controllers/GeneralUseHelperFunctions.cs b/Controllers/GeneralUseHelperFunctions.cs new file mode 100644 index 0000000..8ebd531 --- /dev/null +++ b/Controllers/GeneralUseHelperFunctions.cs @@ -0,0 +1,34 @@ +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + +namespace QuotifyBE.Controllers; + +public class GeneralUseHelpers +{ + public string GenerateJwtToken(string username, IConfiguration appsettings) + { + 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); + } +} diff --git a/Controllers/WeatherForecastController.cs b/Controllers/WeatherForecastController.cs deleted file mode 100644 index 0f6e918..0000000 --- a/Controllers/WeatherForecastController.cs +++ /dev/null @@ -1,87 +0,0 @@ -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 _logger; - private readonly IConfiguration _appsettings; - - public WeatherForecastController(ILogger logger, IConfiguration appsettings) - { - _logger = logger; - _appsettings = appsettings; - } - - [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable 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); - } - } -} diff --git a/Program.cs b/Program.cs index 007e5bd..4374b50 100644 --- a/Program.cs +++ b/Program.cs @@ -1,13 +1,13 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; +using QuotifyBE.Controllers; using QuotifyBE.Data; -using QuotifyBE.Entities; using System.Text; var builder = WebApplication.CreateBuilder(args); -// Configure Database Conecction +// Configure Database Connection var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext(options => options.UseNpgsql(connectionString)); @@ -40,6 +40,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // Add services to the container. builder.Services.AddAuthorization(); builder.Services.AddSingleton(builder.Configuration); +builder.Services.AddScoped(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle