Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using System.Text;
using Data.Access.Repositories;
using Data.Model.BusinessStructs;
using Data.Model.Results;
using Data.Model.Utils;
using Infrastructure.DependencyInjection;
using Infrastructure.Settings;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace Infrastructure.Services;
namespace BLL.Services.Auth;

public class JwtTokenService(IOptions<JwtSettings> jwtSettings) : IJwtTokenService, IScopedDependency
public class AuthService(IOptions<JwtSettings> jwtSettings, IUserService userService) : IAuthService, IScopedDependency
{
private readonly JwtSettings _jwtSettings = jwtSettings.Value;

public string GenerateToken(string userId, string email, List<string>? roles = null)
private string GenerateToken(string username, string email)
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, userId),
new(ClaimTypes.NameIdentifier, username),
new(ClaimTypes.Email, email),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString())
};

// Add roles as claims
if (roles is { Count: > 0 })
{
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
}

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

Expand All @@ -42,6 +41,20 @@ public string GenerateToken(string userId, string email, List<string>? roles = n
return new JwtSecurityTokenHandler().WriteToken(token);
}

public async Task<TokenCreationResult> GenerateTokenAsync(string username, string password)
{
var user = await userService.GetByCredentialsAsync(username, password) ?? throw new UnauthorizedAccessException();
var token = GenerateToken(user.Username, user.Email);
return new TokenCreationResult(user.Id, token);
}

public async Task<TokenCreationResult> RenewTokenAsync(string refreshToken)
{
var user = await userService.GetUserByTokenAsync(refreshToken) ?? throw new UnauthorizedAccessException();
var token = GenerateToken(user.Username, user.Email);
return new TokenCreationResult(user.Id, token);
}

public ClaimsPrincipal? ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
Expand Down
12 changes: 12 additions & 0 deletions fullstack2026BE/BLL/Services/Auth/IAuthService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Security.Claims;
using Data.Model.Results;

namespace BLL.Services.Auth;

public interface IAuthService
{
Task<TokenCreationResult> GenerateTokenAsync(string username, string password);
Task<TokenCreationResult> RenewTokenAsync(string refreshToken);
ClaimsPrincipal? ValidateToken(string token);
}

3 changes: 2 additions & 1 deletion fullstack2026BE/BLL/Services/IUserService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Data.Model.BusinessStructs;
using Data.Model.DTO;

namespace BLL.Services;
Expand All @@ -14,5 +15,5 @@ public interface IUserService

Task<UserDto> RegisterAsync(string username, string email, string password);
Task<UserDto?> GetUserByTokenAsync(string refreshToken);
Task<string> GenerateAndStoreRefreshTokenAsync(UserDto userDto);
Task<string> GenerateAndStoreRefreshTokenAsync(UserId userId);
}
10 changes: 5 additions & 5 deletions fullstack2026BE/BLL/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Data.Model.Utils;
using Infrastructure.DependencyInjection;
using System.Net;
using Data.Model.BusinessStructs;

namespace BLL.Services;

Expand Down Expand Up @@ -52,7 +53,7 @@ public async Task<UserDto> RegisterAsync(string username, string email, string p

public async Task<UserDto?> GetUserByTokenAsync(string refreshToken)
{
var entity = await userRepository.GetUserByTokensAsync(refreshToken);
var entity = await userRepository.GetUserByTokenAsync(refreshToken);
return entity == null ? null : new UserDto
{
Id = entity.Id,
Expand All @@ -63,17 +64,16 @@ public async Task<UserDto> RegisterAsync(string username, string email, string p
};
}

public async Task<string> GenerateAndStoreRefreshTokenAsync(UserDto userDto)
public async Task<string> GenerateAndStoreRefreshTokenAsync(UserId userId)
{
if (userId == null) throw new HttpException(HttpStatusCode.BadRequest, "User ID is required to generate refresh token");
var refreshToken = GenerateSecureRefreshToken();
var userId = userDto.Id.GetValueOrDefault();
if (userId == 0) throw new HttpException(HttpStatusCode.BadRequest, "User ID is required to generate refresh token");
var newRefreshTokenEntity = new RefreshTokenEntity
{
CreatedAt = DateTimeOffset.UtcNow,
RefreshToken = refreshToken,
ExpiresAt = DateTimeOffset.UtcNow.AddDays(1),
UserId = userId
UserId = userId.Value,
};
await userRepository.DeleteAllWithUserIdAsync(userId);
await userRepository.StoreRefreshTokenAsync(newRefreshTokenEntity);
Expand Down
18 changes: 15 additions & 3 deletions fullstack2026BE/Data.Access/Helpers/InsertHelper.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
using System.Reflection;
using Data.Model.Entities;
using Infrastructure.Models;

namespace Data.Access.Helpers;

public abstract class InsertHelper
{
public static Dictionary<string, object?> ToInsertDictionary<T>(T entity) where T : BaseEntity
public static Dictionary<string, object?> ToInsertDictionary<T>(T entity)
{
var dict = new Dictionary<string, object?>();
foreach (var prop in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
var type = typeof(T);
var stronglyTypedIdType = typeof(StronglyTypedId<>);

foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (prop.Name == nameof(BaseEntity.Id)) continue;
if (prop.Name == "Id")
{
var propType = prop.PropertyType;
// Check if Id is a strongly-typed ID (i.e., inherits from StronglyTypedId<>)
if (propType.IsGenericType && propType.GetGenericTypeDefinition() == stronglyTypedIdType)
{
continue;
}
}
dict[prop.Name] = prop.GetValue(entity);
}
return dict;
Expand Down
5 changes: 3 additions & 2 deletions fullstack2026BE/Data.Access/Repositories/IUserRepository.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Data.Model.BusinessStructs;
using Data.Model.Entities;

namespace Data.Access.Repositories;
Expand All @@ -7,8 +8,8 @@ public interface IUserRepository
Task<IEnumerable<UserEntity>> GetAllAsync();
Task<UserEntity?> GetByEmailAsync(string email);
Task AddAsync(UserEntity user);
Task<UserEntity?> GetUserByTokensAsync(string refreshToken);
Task<UserEntity?> GetUserByTokenAsync(string refreshToken);
Task StoreRefreshTokenAsync(RefreshTokenEntity entity);
Task DeleteAllWithUserIdAsync(int userId);
Task DeleteAllWithUserIdAsync(UserId userId);
Task RevokeRefreshToken(string refreshToken);
}
5 changes: 3 additions & 2 deletions fullstack2026BE/Data.Access/Repositories/UserRepository.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

using Data.Access.Helpers;
using Data.Model.BusinessStructs;
using Data.Model.Entities;
using Infrastructure.DependencyInjection;
using Infrastructure.Helpers;
Expand Down Expand Up @@ -34,7 +35,7 @@ await conn.SqlKata()
.InsertAsync(InsertHelper.ToInsertDictionary(user));
}

public async Task<UserEntity?> GetUserByTokensAsync(string refreshToken)
public async Task<UserEntity?> GetUserByTokenAsync(string refreshToken)
{
var currentTime = DateTimeOffset.UtcNow;
await using var conn = await MainDb.OpenConnectionAsync();
Expand All @@ -54,7 +55,7 @@ await conn.SqlKata()
.InsertAsync(InsertHelper.ToInsertDictionary(entity));
}

public async Task DeleteAllWithUserIdAsync(int userId)
public async Task DeleteAllWithUserIdAsync(UserId userId)
{
await using var conn = await MainDb.OpenConnectionAsync();
await conn.SqlKata()
Expand Down
8 changes: 8 additions & 0 deletions fullstack2026BE/Data.Model/BusinessStructs/UserId.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Infrastructure.Models;

namespace Data.Model.BusinessStructs;

public record UserId(int Value) : StronglyTypedId<int>(Value)
{
public override string ToString() => Value.ToString();
}
5 changes: 3 additions & 2 deletions fullstack2026BE/Data.Model/DTO/UserDto.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System.Text.Json.Serialization;
using Data.Model.BusinessStructs;
using Newtonsoft.Json;

namespace Data.Model.DTO;

public record UserDto
{
[JsonIgnore]
public int? Id { get; init; }
public required UserId Id { get; init; }
public required string Username { get; set; }
public required string Email { get; set; }
public DateTimeOffset CreatedAt { get; set; }
Expand Down
8 changes: 8 additions & 0 deletions fullstack2026BE/Data.Model/Data.Model.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,12 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

</Project>
4 changes: 0 additions & 4 deletions fullstack2026BE/Data.Model/Entities/BaseEntity.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
using System.ComponentModel.DataAnnotations;

namespace Data.Model.Entities;

public class BaseEntity
{
[Key]
public int? Id { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
10 changes: 7 additions & 3 deletions fullstack2026BE/Data.Model/Entities/UserEntity.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Data.Model.BusinessStructs;

namespace Data.Model.Entities;

[Table("Users")]
public class UserEntity : BaseEntity
{
public required string Username { get; set; }
public required string Password { get; set; }
public required string Email { get; set; }
[Key]
public UserId Id { get; init; } = new UserId(0);
public required string Username { get; init; }
public required string Password { get; init; }
public required string Email { get; init; }
}
5 changes: 5 additions & 0 deletions fullstack2026BE/Data.Model/Results/TokenCreationResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using Data.Model.BusinessStructs;

namespace Data.Model.Results;

public record TokenCreationResult(UserId UserId, string JwtToken);
88 changes: 88 additions & 0 deletions fullstack2026BE/Infrastructure/Helpers/StronglyTypedIdConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Globalization;
using Infrastructure.Models;

namespace Infrastructure.Helpers;

public class StronglyTypedIdConverter<TValue>(Type type) : TypeConverter
where TValue : notnull
{
private static readonly TypeConverter IdValueConverter = GetIdValueConverter();

private static TypeConverter GetIdValueConverter()
{
var converter = TypeDescriptor.GetConverter(typeof(TValue));
if (!converter.CanConvertFrom(typeof(string)))
throw new InvalidOperationException(
$"Type '{typeof(TValue)}' doesn't have a converter that can convert from string");
return converter;
}

public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return sourceType == typeof(string)
|| sourceType == typeof(TValue)
|| base.CanConvertFrom(context, sourceType);
}

public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType)
{
return destinationType == typeof(string)
|| destinationType == typeof(TValue)
|| base.CanConvertTo(context, destinationType);
}

public override object ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (value is string s)
{
value = IdValueConverter.ConvertFrom(s) ?? throw new InvalidOperationException();
}

if (value is TValue idValue)
{
var factory = StronglyTypedIdHelper.GetFactory<TValue>(type);
return factory(idValue);
}

return base.ConvertFrom(context, culture, value) ?? throw new InvalidOperationException();
}

public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
ArgumentNullException.ThrowIfNull(value);

var stronglyTypedId = (StronglyTypedId<TValue>)value;
var idValue = stronglyTypedId.Value;
if (destinationType == typeof(string))
return idValue.ToString() ?? throw new InvalidOperationException();
return (destinationType == typeof(TValue) ? idValue : base.ConvertTo(context, culture, value, destinationType)) ?? throw new InvalidOperationException();
}
}
public class StronglyTypedIdConverter(Type stronglyTypedIdType) : TypeConverter
{
private static readonly ConcurrentDictionary<Type, TypeConverter> ActualConverters = new();

private readonly TypeConverter _innerConverter = ActualConverters.GetOrAdd(stronglyTypedIdType, CreateActualConverter);

public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) =>
_innerConverter.CanConvertFrom(context, sourceType);
public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) =>
_innerConverter.CanConvertTo(context, destinationType);
public override object ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) =>
_innerConverter.ConvertFrom(context, culture, value) ?? throw new InvalidOperationException();
public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) =>
_innerConverter.ConvertTo(context, culture, value, destinationType) ?? throw new InvalidOperationException();


private static TypeConverter CreateActualConverter(Type stronglyTypedIdType)
{
if (!StronglyTypedIdHelper.IsStronglyTypedId(stronglyTypedIdType, out var idType))
throw new InvalidOperationException($"The type '{stronglyTypedIdType}' is not a strongly typed id");

var actualConverterType = typeof(StronglyTypedIdConverter<>).MakeGenericType(idType);
var activator = Activator.CreateInstance(actualConverterType, stronglyTypedIdType) ?? throw new InvalidOperationException();
return (TypeConverter)activator;
}
}
Loading
Loading