This repository has been archived on 2023-02-13. You can view files and clone it, but cannot push or open issues or pull requests.
gswi-server/gswi.Service/AuthServiceImpl.cs

504 lines
22 KiB
C#
Raw Normal View History

2022-02-20 19:04:11 +01:00
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using gswi.Configuration;
using gswi.Interface.Repositories;
using gswi.Interface.Services;
using gswi.Model;
using gswi.Model.DTOs;
using gswi.Model.Filters;
using gswi.Share.Common;
using gswi.SMTP.Interface;
using gswi.SMTP.Model;
2022-02-21 18:27:33 +01:00
using Microsoft.IdentityModel.Tokens;
using NLog;
2022-02-20 19:04:11 +01:00
2022-02-21 18:27:33 +01:00
namespace gswi.Service {
public class AuthServiceImpl : IAuthService {
2022-02-20 19:04:11 +01:00
private readonly IAuthUserRepository _authUserRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly AuthentificationSettings _authSettings;
private readonly ISMTPClient _smtpClient;
private readonly FrontendSettings _frontendSettings;
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static Random random = new Random();
public AuthServiceImpl(
IAuthUserRepository authUserRepository,
IUnitOfWork unitOfWork,
AuthentificationSettings authSettings,
ISMTPClient smtpClient,
FrontendSettings frontendSettings
2022-02-21 18:27:33 +01:00
) {
2022-02-20 19:04:11 +01:00
_unitOfWork = unitOfWork;
_authUserRepository = authUserRepository;
_authSettings = authSettings;
_smtpClient = smtpClient;
_frontendSettings = frontendSettings;
}
2022-02-21 18:27:33 +01:00
private static string _randomString(int length) {
2022-02-20 19:04:11 +01:00
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
2022-02-21 18:27:33 +01:00
private string _generateToken(IEnumerable<Claim> claims) {
2022-02-20 19:04:11 +01:00
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authSettings.SecretKey));
var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokenOptions = new JwtSecurityToken(
issuer: _authSettings.Issuer,
audience: _authSettings.Audience,
claims: claims,
expires: DateTime.Now.AddMinutes(_authSettings.TokenExpireTime),
signingCredentials: signingCredentials
);
return new JwtSecurityTokenHandler().WriteToken(tokenOptions);
}
2022-02-21 18:27:33 +01:00
private string _generateRefreshToken() {
2022-02-20 19:04:11 +01:00
var randomNumber = new byte[32];
2022-02-21 18:27:33 +01:00
using (var rng = RandomNumberGenerator.Create()) {
2022-02-20 19:04:11 +01:00
rng.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
}
}
2022-02-21 18:27:33 +01:00
private async Task<string> _createAndSaveRefreshToken(AuthUser user) {
2022-02-20 19:04:11 +01:00
var refreshToken = this._generateRefreshToken();
user.RefreshToken = refreshToken;
user.RefreshTokenExpiryTime = DateTime.Now.AddDays(_authSettings.RefreshTokenExpireTime);
await _unitOfWork.SaveChangesAsync();
return refreshToken;
}
2022-02-21 18:27:33 +01:00
private ClaimsPrincipal _getPrincipalFromExpiredToken(string token) {
var tokenValidationParameters = new TokenValidationParameters {
2022-02-20 19:04:11 +01:00
ValidateAudience = false, //you might want to validate the audience and issuer depending on your use case
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._authSettings.SecretKey)),
ValidateLifetime = false //here we are saying that we don't care about the token's expiration date
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken;
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;
if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
throw new SecurityTokenException("Invalid token");
return principal;
}
2022-02-21 18:27:33 +01:00
private async Task _createAndSaveConfirmationId(AuthUser user) {
2022-02-20 19:04:11 +01:00
bool end = false;
2022-02-21 18:27:33 +01:00
while (!end) {
2022-02-20 19:04:11 +01:00
string id = _randomString(16);
var userFromDb = await _authUserRepository.FindAuthUserByEMailConfirmationIdAsync(id);
2022-02-21 18:27:33 +01:00
if (userFromDb is null) {
2022-02-20 19:04:11 +01:00
end = true;
user.ConfirmationId = id;
}
}
}
2022-02-21 18:27:33 +01:00
private async Task _createAndSaveForgotPasswordId(AuthUser user) {
2022-02-20 19:04:11 +01:00
bool end = false;
2022-02-21 18:27:33 +01:00
while (!end) {
2022-02-20 19:04:11 +01:00
string id = _randomString(16);
var userFromDb = await _authUserRepository.FindAuthUserByEMailForgotPasswordIdAsync(id);
2022-02-21 18:27:33 +01:00
if (userFromDb is null) {
2022-02-20 19:04:11 +01:00
end = true;
user.ForgotPasswordId = id;
}
}
}
2022-02-21 18:27:33 +01:00
private async Task _sendConfirmationIdToUser(AuthUser user) {
2022-02-20 19:04:11 +01:00
string url = _frontendSettings.URL.EndsWith("/") ? _frontendSettings.URL : $"{_frontendSettings}/";
2022-02-21 18:27:33 +01:00
await _smtpClient.SendEmailAsync(new EMail() {
2022-02-20 19:04:11 +01:00
Receiver = user.EMail,
Subject = $"E-Mail für {user.FirstName} {user.LastName} bestätigen",
Message = $"{url}auth/register/{user.ConfirmationId}"
});
}
2022-02-21 18:27:33 +01:00
private async Task _sendForgotPasswordIdToUser(AuthUser user) {
2022-02-20 19:04:11 +01:00
string url = _frontendSettings.URL.EndsWith("/") ? _frontendSettings.URL : $"{_frontendSettings}/";
2022-02-21 18:27:33 +01:00
await _smtpClient.SendEmailAsync(new EMail() {
2022-02-20 19:04:11 +01:00
Receiver = user.EMail,
Subject = $"Passwort für {user.FirstName} {user.LastName} zurücksetzen",
Message = $"{url}auth/forgot-password/{user.ForgotPasswordId}"
});
}
2022-02-21 18:27:33 +01:00
public async Task<List<AuthUserDTO>> GetAllAuthUsersAsync() {
2022-02-20 19:04:11 +01:00
var authUserDTOs = new List<AuthUserDTO>();
var authUsers = await _authUserRepository.GetAllAuthUsersAsync();
2022-02-21 18:27:33 +01:00
authUsers.ForEach(authUser => {
2022-02-20 19:04:11 +01:00
authUserDTOs.Add(authUser.ToAuthUserDTO());
});
return authUserDTOs;
}
public async Task<GetFilteredAuthUsersResultDTO> GetFilteredAuthUsersAsync(AuthUserSelectCriterion selectCriterion) {
(var users, var totalCount) = await _authUserRepository.GetFilteredAuthUsersAsync(selectCriterion);
var result = new List<AuthUserDTO>();
users.ForEach(user => {
result.Add(user.ToAuthUserDTO());
});
2022-02-21 18:27:33 +01:00
2022-02-20 19:04:11 +01:00
return new GetFilteredAuthUsersResultDTO() {
Users = result,
TotalCount = totalCount
};
}
2022-02-21 18:27:33 +01:00
public async Task<AuthUserDTO> GetAuthUserByEMailAsync(string email) {
try {
2022-02-20 19:04:11 +01:00
var authUser = await _authUserRepository.GetAuthUserByEMailAsync(email);
return authUser.ToAuthUserDTO();
2022-02-21 18:27:33 +01:00
} catch (Exception e) {
2022-02-20 19:04:11 +01:00
_logger.Error(e);
throw new ServiceException(ServiceErrorCode.InvalidData, $"AuthUser with email {email} not found");
}
}
2022-02-21 18:27:33 +01:00
public async Task<AuthUserDTO> FindAuthUserByEMailAsync(string email) {
2022-02-20 19:04:11 +01:00
var authUser = await _authUserRepository.FindAuthUserByEMailAsync(email);
return authUser != null ? authUser.ToAuthUserDTO() : null;
}
2022-02-21 18:27:33 +01:00
public async Task<long> AddAuthUserAsync(AuthUserDTO authUserDTO) {
2022-02-20 19:04:11 +01:00
var authUserDb = await _authUserRepository.FindAuthUserByEMailAsync(authUserDTO.EMail);
2022-02-21 18:27:33 +01:00
if (authUserDb != null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User already exists");
}
authUserDTO.Password = ComputeHash(authUserDTO.Password, new SHA256CryptoServiceProvider());
var authUser = authUserDTO.ToAuthUser();
2022-02-21 18:27:33 +01:00
if (!IsValidEmail(authUser.EMail)) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Invalid E-Mail");
}
2022-02-21 18:27:33 +01:00
try {
2022-02-20 19:04:11 +01:00
_authUserRepository.AddAuthUser(authUser);
await _createAndSaveConfirmationId(authUser);
await _sendConfirmationIdToUser(authUser);
await _unitOfWork.SaveChangesAsync();
_logger.Info($"Added authUser with email: {authUser.EMail}");
return authUser.Id;
2022-02-21 18:27:33 +01:00
} catch (Exception e) {
2022-02-20 19:04:11 +01:00
_logger.Error(e);
throw new ServiceException(ServiceErrorCode.UnableToAdd, $"Cannot add authUser {authUserDTO.EMail}");
}
}
2022-02-21 18:27:33 +01:00
public async Task<bool> ConfirmEMail(string id) {
2022-02-20 19:04:11 +01:00
var user = await _authUserRepository.FindAuthUserByEMailConfirmationIdAsync(id);
2022-02-21 18:27:33 +01:00
if (user.ConfirmationId == id) {
2022-02-20 19:04:11 +01:00
user.ConfirmationId = null;
await _unitOfWork.SaveChangesAsync();
return true;
}
return false;
}
2022-02-21 18:27:33 +01:00
public async Task<TokenDTO> Login(AuthUserDTO userDTO) {
if (userDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"User is empty");
}
var userFromDb = await _authUserRepository.FindAuthUserByEMailAsync(userDTO.EMail);
2022-02-21 18:27:33 +01:00
if (userFromDb == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found");
}
2022-02-21 18:27:33 +01:00
if (userFromDb.ConfirmationId != null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed");
}
userDTO.Password = ComputeHash(userDTO.Password, new SHA256CryptoServiceProvider());
2022-02-21 18:27:33 +01:00
if (userFromDb.Password != userDTO.Password) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "Wrong password");
}
var tokenString = this._generateToken(new List<Claim>() {
new Claim(ClaimTypes.Name, userDTO.EMail),
new Claim(ClaimTypes.Role, userFromDb.AuthRole.ToString())
});
var refreshString = await this._createAndSaveRefreshToken(userFromDb);
2022-02-21 18:27:33 +01:00
if (userFromDb.ForgotPasswordId != null) {
2022-02-20 19:04:11 +01:00
userFromDb.ForgotPasswordId = null;
await _unitOfWork.SaveChangesAsync();
}
2022-02-21 18:27:33 +01:00
return new TokenDTO {
2022-02-20 19:04:11 +01:00
Token = tokenString,
RefreshToken = refreshString
};
}
2022-02-21 18:27:33 +01:00
public async Task ForgotPassword(string email) {
2022-02-20 19:04:11 +01:00
var user = await _authUserRepository.FindAuthUserByEMailAsync(email);
2022-02-21 18:27:33 +01:00
if (user is null) {
2022-02-20 19:04:11 +01:00
return;
}
await _createAndSaveForgotPasswordId(user);
await _sendForgotPasswordIdToUser(user);
await _unitOfWork.SaveChangesAsync();
}
2022-02-21 18:27:33 +01:00
public async Task<EMailStringDTO> ConfirmForgotPassword(string id) {
2022-02-20 19:04:11 +01:00
var user = await _authUserRepository.FindAuthUserByEMailForgotPasswordIdAsync(id);
2022-02-21 18:27:33 +01:00
return new EMailStringDTO() {
2022-02-20 19:04:11 +01:00
EMail = user.EMail
};
}
2022-02-21 18:27:33 +01:00
public async Task ResetPassword(ResetPasswordDTO rpDTO) {
2022-02-20 19:04:11 +01:00
var user = await _authUserRepository.FindAuthUserByEMailForgotPasswordIdAsync(rpDTO.Id);
2022-02-21 18:27:33 +01:00
if (user == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found");
}
2022-02-21 18:27:33 +01:00
if (user.ConfirmationId != null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed");
}
2022-02-21 18:27:33 +01:00
if (rpDTO.Password == null || rpDTO.Password == "") {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, "Password is empty");
}
rpDTO.Password = ComputeHash(rpDTO.Password, new SHA256CryptoServiceProvider());
user.Password = rpDTO.Password;
await _unitOfWork.SaveChangesAsync();
}
2022-02-21 18:27:33 +01:00
public async Task UpdateUser(UpdateUserDTO updateUserDTO) {
if (updateUserDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"User is empty");
}
2022-02-21 18:27:33 +01:00
if (updateUserDTO.AuthUserDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Existing user is empty");
}
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"New user is empty");
}
2022-02-21 18:27:33 +01:00
if (!IsValidEmail(updateUserDTO.AuthUserDTO.EMail) || !IsValidEmail(updateUserDTO.NewAuthUserDTO.EMail)) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Invalid E-Mail");
}
var user = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.AuthUserDTO.EMail);
2022-02-21 18:27:33 +01:00
if (user == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found");
}
2022-02-21 18:27:33 +01:00
if (user.ConfirmationId != null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed");
}
// update first name
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.FirstName != null && updateUserDTO.AuthUserDTO.FirstName != updateUserDTO.NewAuthUserDTO.FirstName) {
2022-02-20 19:04:11 +01:00
user.FirstName = updateUserDTO.NewAuthUserDTO.FirstName;
}
// update last name
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.LastName != null && updateUserDTO.NewAuthUserDTO.LastName != "" && updateUserDTO.AuthUserDTO.LastName != updateUserDTO.NewAuthUserDTO.LastName) {
2022-02-20 19:04:11 +01:00
user.LastName = updateUserDTO.NewAuthUserDTO.LastName;
}
// update E-Mail
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.EMail != null && updateUserDTO.NewAuthUserDTO.EMail != "" && updateUserDTO.AuthUserDTO.EMail != updateUserDTO.NewAuthUserDTO.EMail) {
2022-02-20 19:04:11 +01:00
var userByNewEMail = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.NewAuthUserDTO.EMail);
2022-02-21 18:27:33 +01:00
if (userByNewEMail != null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User already exists");
}
user.EMail = updateUserDTO.NewAuthUserDTO.EMail;
}
bool isExistingPasswordSet = false;
bool isnewPasswordSet = false;
// hash passwords in DTOs
2022-02-21 18:27:33 +01:00
if (updateUserDTO.AuthUserDTO.Password != null && updateUserDTO.AuthUserDTO.Password != "") {
2022-02-20 19:04:11 +01:00
isExistingPasswordSet = true;
updateUserDTO.AuthUserDTO.Password = ComputeHash(updateUserDTO.AuthUserDTO.Password, new SHA256CryptoServiceProvider());
}
2022-02-21 18:27:33 +01:00
if (updateUserDTO.AuthUserDTO.Password != user.Password) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "Wrong password");
}
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.Password != null && updateUserDTO.NewAuthUserDTO.Password != "") {
2022-02-20 19:04:11 +01:00
isnewPasswordSet = true;
updateUserDTO.NewAuthUserDTO.Password = ComputeHash(updateUserDTO.NewAuthUserDTO.Password, new SHA256CryptoServiceProvider());
}
// update password
2022-02-21 18:27:33 +01:00
if (isExistingPasswordSet && isnewPasswordSet && updateUserDTO.AuthUserDTO.Password != updateUserDTO.NewAuthUserDTO.Password) {
2022-02-20 19:04:11 +01:00
user.Password = updateUserDTO.NewAuthUserDTO.Password;
}
await _unitOfWork.SaveChangesAsync();
}
2022-02-21 18:27:33 +01:00
public async Task UpdateUserAsAdmin(AdminUpdateUserDTO updateUserDTO) {
if (updateUserDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"User is empty");
}
2022-02-21 18:27:33 +01:00
if (updateUserDTO.AuthUserDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Existing user is empty");
}
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"New user is empty");
}
2022-02-21 18:27:33 +01:00
if (!IsValidEmail(updateUserDTO.AuthUserDTO.EMail) || !IsValidEmail(updateUserDTO.NewAuthUserDTO.EMail)) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Invalid E-Mail");
}
var user = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.AuthUserDTO.EMail);
2022-02-21 18:27:33 +01:00
if (user == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found");
}
2022-02-21 18:27:33 +01:00
if (user.ConfirmationId != null && updateUserDTO.NewAuthUserDTO.IsConfirmed) {
2022-02-20 19:04:11 +01:00
user.ConfirmationId = null;
2022-02-21 18:27:33 +01:00
} else if (user.ConfirmationId == null && !updateUserDTO.NewAuthUserDTO.IsConfirmed) {
2022-02-20 19:04:11 +01:00
await _createAndSaveConfirmationId(user);
}
// else
// {
// throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed");
// }
// update first name
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.FirstName != null && updateUserDTO.AuthUserDTO.FirstName != updateUserDTO.NewAuthUserDTO.FirstName) {
2022-02-20 19:04:11 +01:00
user.FirstName = updateUserDTO.NewAuthUserDTO.FirstName;
}
// update last name
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.LastName != null && updateUserDTO.NewAuthUserDTO.LastName != "" && updateUserDTO.AuthUserDTO.LastName != updateUserDTO.NewAuthUserDTO.LastName) {
2022-02-20 19:04:11 +01:00
user.LastName = updateUserDTO.NewAuthUserDTO.LastName;
}
// update E-Mail
2022-02-21 18:27:33 +01:00
if (updateUserDTO.NewAuthUserDTO.EMail != null && updateUserDTO.NewAuthUserDTO.EMail != "" && updateUserDTO.AuthUserDTO.EMail != updateUserDTO.NewAuthUserDTO.EMail) {
2022-02-20 19:04:11 +01:00
var userByNewEMail = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.NewAuthUserDTO.EMail);
2022-02-21 18:27:33 +01:00
if (userByNewEMail != null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidUser, "User already exists");
}
user.EMail = updateUserDTO.NewAuthUserDTO.EMail;
}
// update password
2022-02-21 18:27:33 +01:00
if (updateUserDTO.ChangePassword && updateUserDTO.AuthUserDTO.Password != updateUserDTO.NewAuthUserDTO.Password) {
2022-02-20 19:04:11 +01:00
user.Password = ComputeHash(updateUserDTO.NewAuthUserDTO.Password, new SHA256CryptoServiceProvider());
}
// update role
2022-02-21 18:27:33 +01:00
if (user.AuthRole == updateUserDTO.AuthUserDTO.AuthRole && user.AuthRole != updateUserDTO.NewAuthUserDTO.AuthRole) {
2022-02-20 19:04:11 +01:00
user.AuthRole = updateUserDTO.NewAuthUserDTO.AuthRole;
}
await _unitOfWork.SaveChangesAsync();
}
2022-02-21 18:27:33 +01:00
public async Task<TokenDTO> Refresh(TokenDTO tokenDTO) {
if (tokenDTO is null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is empty");
}
var principal = this._getPrincipalFromExpiredToken(tokenDTO.Token);
var email = principal.Identity.Name;
var user = await this._authUserRepository.FindAuthUserByEMailAsync(email);
2022-02-21 18:27:33 +01:00
if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is expired");
}
var newToken = this._generateToken(principal.Claims);
var newRefreshToken = await this._createAndSaveRefreshToken(user);
2022-02-21 18:27:33 +01:00
return new TokenDTO() {
2022-02-20 19:04:11 +01:00
Token = newToken,
RefreshToken = newRefreshToken
};
}
2022-02-21 18:27:33 +01:00
public async Task Revoke(TokenDTO tokenDTO) {
if (tokenDTO == null || tokenDTO.Token == null || tokenDTO.RefreshToken == null) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is empty");
};
var principal = this._getPrincipalFromExpiredToken(tokenDTO.Token);
var email = principal.Identity.Name;
var user = await this._authUserRepository.FindAuthUserByEMailAsync(email);
2022-02-21 18:27:33 +01:00
if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) {
2022-02-20 19:04:11 +01:00
throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is expired");
}
user.RefreshToken = null;
await _unitOfWork.SaveChangesAsync();
}
2022-02-21 18:27:33 +01:00
public async Task DeleteAuthUserByEMailAsync(string email) {
try {
2022-02-20 19:04:11 +01:00
await _authUserRepository.DeleteAuthUserByEMailAsync(email);
await _unitOfWork.SaveChangesAsync();
_logger.Info($"Deleted authUser with email: {email}");
2022-02-21 18:27:33 +01:00
} catch (Exception e) {
2022-02-20 19:04:11 +01:00
_logger.Error(e);
throw new ServiceException(ServiceErrorCode.UnableToDelete, $"Cannot delete authUser with email {email}");
}
}
2022-02-21 18:27:33 +01:00
public async Task DeleteAuthUserAsync(AuthUserDTO authUserDTO) {
try {
2022-02-20 19:04:11 +01:00
_authUserRepository.DeleteAuthUser(authUserDTO.ToAuthUser());
await _unitOfWork.SaveChangesAsync();
_logger.Info($"Deleted authUser {authUserDTO.EMail}");
2022-02-21 18:27:33 +01:00
} catch (Exception e) {
2022-02-20 19:04:11 +01:00
_logger.Error(e);
throw new ServiceException(ServiceErrorCode.UnableToDelete, $"Cannot delete authUser {authUserDTO.EMail}");
}
}
2022-02-21 18:27:33 +01:00
private string ComputeHash(string input, HashAlgorithm algorithm) {
2022-02-20 19:04:11 +01:00
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
return BitConverter.ToString(hashedBytes);
}
2022-02-21 18:27:33 +01:00
private bool IsValidEmail(string email) {
try {
2022-02-20 19:04:11 +01:00
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
2022-02-21 18:27:33 +01:00
} catch {
2022-02-20 19:04:11 +01:00
return false;
}
}
}
}