This commit is contained in:
2024-03-08 07:51:57 +01:00
commit e84a2f4f8d
191 changed files with 43915 additions and 0 deletions
@@ -0,0 +1,41 @@
using Kemkas.Web.Db.Models;
using Microsoft.AspNetCore.Identity;
namespace Kemkas.Web.Services.Identity;
public interface ICurrentUserService
{
public Task<ApplicationUser?> GetCurrentUser();
public Task<ApplicationUser> GetCurrentUserOrThrow();
}
public class CurrentUserService(
IHttpContextAccessor httpContextAccessor,
UserManager<ApplicationUser> userManager
) : ICurrentUserService
{
private ApplicationUser? _user;
public async Task<ApplicationUser?> GetCurrentUser()
{
if (_user is not null)
{
return _user;
}
var userName = httpContextAccessor.HttpContext?.User.Identity?.Name;
if (userName is null)
{
return null;
}
_user = await userManager.FindByNameAsync(userName);
return _user;
}
public async Task<ApplicationUser> GetCurrentUserOrThrow()
{
return await GetCurrentUser() ?? throw new InvalidOperationException("no current user!");
}
}
@@ -0,0 +1,29 @@
using System.Net.Http.Headers;
using Kemkas.Web.Config;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;
namespace Kemkas.Web.Services.Identity;
public class MailgunEmailSender(IOptions<MailgunOptions> sendGridOptions, HttpClient httpClient) : IEmailSender
{
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var domain = sendGridOptions.Value.DomainName;
var uri = new Uri($"https://api.eu.mailgun.net/v3/{domain}/messages");
var request = new HttpRequestMessage(HttpMethod.Post, uri);
var authHeaderValue = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"api:{sendGridOptions.Value.ApiKey}"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
request.Content = new FormUrlEncodedContent(
[
new KeyValuePair<string,string>("from", $"no-reply@{domain}"),
new KeyValuePair<string,string>("to", email),
new KeyValuePair<string,string>("subject", subject),
new KeyValuePair<string,string>("html", htmlMessage),
]);
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
}
}