mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 21:50:08 +01:00
64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using QuotifyBE.Data;
|
|
using QuotifyBE.Entities;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace QuotifyBE.Controllers;
|
|
|
|
public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettings)
|
|
{
|
|
private readonly ApplicationDbContext _db = db;
|
|
private readonly IConfiguration _appsettings = appsettings;
|
|
|
|
async public Task<User?> GetUserFromEmail(string email)
|
|
{
|
|
return await _db.Users.FirstOrDefaultAsync(e => e.Email == email);
|
|
}
|
|
|
|
|
|
public string HashWithSHA512(string s)
|
|
{
|
|
using (var sha512 = SHA512.Create())
|
|
{
|
|
byte[] bytes = Encoding.ASCII.GetBytes(s);
|
|
byte[] hash = sha512.ComputeHash(bytes);
|
|
string hashstring = BitConverter.ToString(hash).Replace("-", "").ToLower();
|
|
|
|
return hashstring;
|
|
}
|
|
}
|
|
|
|
public string GenerateJwtToken(string username, string passwordHash)
|
|
{
|
|
var claims = new[]
|
|
{
|
|
new Claim(JwtRegisteredClaimNames.Sub, username),
|
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
|
};
|
|
|
|
var key = new SymmetricSecurityKey(
|
|
// https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens#comment45057142_23089839
|
|
// passwordHash is important for invalidating tokens after a user changed their password
|
|
Encoding.UTF8.GetBytes(
|
|
// JwtSecret won't be null here - otherwise Program.cs wouldn't start
|
|
_appsettings["JwtSecret"]! + passwordHash
|
|
)
|
|
);
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: _appsettings["DomainName"]!,
|
|
audience: _appsettings["DomainName"]!,
|
|
claims: claims,
|
|
expires: DateTime.Now.AddMinutes(5),
|
|
signingCredentials: creds
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|