Files
QuotifyBE/Controllers/AuthController.cs

61 lines
1.8 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using QuotifyBE.DTOs;
using System.Threading.Tasks;
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;
}
// POST /api/v1/auth/login
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] UserLoginDTO formUser, GeneralUseHelpers guhf)
{
// Ensure the form is complete
if (formUser.Email == null || formUser.Password == null)
{
return BadRequest(new {status = "error", error_msg = "Form contains missing data"});
}
// Find the user with retrieved e-mail
User? user = await guhf.GetUserFromEmail(formUser.Email);
if (user == null)
{
return NotFound(new {status = "error", error_msg = "User not found"});
}
// Hash the password and compare with the user-provided one
string hashedFormPassword = guhf.HashWithSHA512(formUser.Password);
if (hashedFormPassword == user.PasswordHash)
{
// All set - generate the token and return it
var token = guhf.GenerateJwtToken(formUser.Email, formUser.Password);
return Ok(new { status = "ok", token });
} else return Unauthorized(new {status = "error", error_msg = "Unknown pair of email and password"});
}
// GET /api/v1/auth/some_values
[HttpGet("some_values")]
[Authorize]
public IActionResult GetValues()
{
return Ok(new string[] { "value1", "value2" });
}
}