using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using FoodsharingSiegen.Contracts;
using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Server.Data;
using FoodsharingSiegen.Server.Data.Service;
using FoodsharingSiegen.Server.Service;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
namespace FoodsharingSiegen.Server.Auth
{
///
/// The auth service class (a. beging, 04.04.2022)
///
///
public class AuthService : ServiceBase
{
#region Public Properties
///
/// Gets or sets the value of the user (ab)
///
public User? User { get; set; }
#endregion
#region Private Fields
///
/// The authentication state provider
///
private readonly AuthenticationStateProvider _authenticationStateProvider;
///
/// The local storage service
///
private readonly LocalStorageService _localStorageService;
#endregion
#region Setup/Teardown
///
/// Initializes a new instance of the class
///
/// The context
/// The local storage service
/// The authentication state provider
public AuthService(FsContext context, LocalStorageService localStorageService, AuthenticationStateProvider authenticationStateProvider) : base(context)
{
_localStorageService = localStorageService;
_authenticationStateProvider = authenticationStateProvider;
}
#endregion
#region Public Method Login
///
/// Logins the mail address (a. beging, 04.04.2022)
///
/// The mail address
/// The password
/// A task containing the operation result
public async Task Login(string mailAddress, string password)
{
#region Ensure Admin
var existingTroogS = await Context.Users.AnyAsync(x => x.Mail == "fs@beging.de");
if (!existingTroogS)
{
var troogs = new User
{
Name = "Andre",
Mail = "fs@beging.de",
Type = UserType.Admin,
Created = DateTime.UtcNow,
EncryptedPassword = "qSIxTZo7J8M="
};
await Context.Users.AddAsync(troogs);
await Context.SaveChangesAsync();
}
#endregion Ensure Admin
var encryptedPassword = AuthHelper.Encrypt(password);
User = await Context.Users.FirstOrDefaultAsync(x => x.Mail.ToLower() == mailAddress.ToLower() && x.EncryptedPassword == encryptedPassword);
if (User != null)
{
// Daten korrekt
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, User.Id.ToString()),
}),
Expires = DateTime.UtcNow.AddDays(30),
Issuer = "FS-Siegen",
Audience = "FS-Siegen",
SigningCredentials = new SigningCredentials(AuthHelper.GetSigningKey(), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var serializedToken = tokenHandler.WriteToken(token);
await _localStorageService.SetItem(StorageKeys.TokenKey, serializedToken);
return new OperationResult();
}
return new OperationResult(new Exception("Invalid"));
}
#endregion
#region Public Method Logout
///
/// Logouts this instance (a. beging, 04.04.2022)
///
/// A task containing the operation result
public async Task Logout()
{
try
{
await _localStorageService.RemoveItem(StorageKeys.TokenKey);
User = null;
((TokenAuthStateProvider) _authenticationStateProvider).MarkUserAsLoggedOut();
return new OperationResult();
}
catch (Exception e)
{
return new OperationResult(e);
}
}
#endregion
}
}