Compare commits

..

8 Commits

23 changed files with 326 additions and 15 deletions
+1
View File
@@ -12,6 +12,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../AMessanger.Application/AMessanger.Application.csproj" />
<ProjectReference Include="../AMessanger.Core/AMessanger.Core.csproj" />
</ItemGroup>
+4 -1
View File
@@ -1,4 +1,5 @@
using AMessanger.Core.Hubs;
using AMessanger.Application;
using AMessanger.Application.Hubs;
var builder = WebApplication.CreateBuilder(args);
@@ -12,6 +13,8 @@ builder.Services.AddSwaggerGen();
builder.Services.AddSignalR();
builder.Services.AddAuth(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../AMessanger.Core/AMessanger.Core.csproj" />
<ProjectReference Include="../AMessanger.DataAccess/AMessanger.DataAccess.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" />
</ItemGroup>
</Project>
@@ -0,0 +1,38 @@
using System.Text;
using AMessanger.Application.Settings;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace AMessanger.Application;
public static class ApplicationExtensions
{
public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration)
{
var jwtConf = configuration.GetSection(JwtSettings.SECTION_NAME);
services.Configure<JwtSettings>(jwtConf);
var settings = jwtConf.Get<JwtSettings>()!;
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = settings.Issuer,
ValidAudience = settings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(settings.Key)
)
};
});
return services.AddAuthorization();
}
}
+14
View File
@@ -0,0 +1,14 @@
using AMessanger.Core.Models;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
namespace AMessanger.Application.Hubs;
public class ChatHub(ILogger<ChatHub> logger) : Hub
{
public async Task SendMessage(Message message)
{
logger.LogInformation($"{message.UserName}: {message.Content}");
await Clients.All.SendAsync("ReceiveMessage", message);
}
}
@@ -0,0 +1,38 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AMessanger.Application.Settings;
using AMessanger.Core.Abstraction;
using AMessanger.Core.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace AMessanger.Application.Services;
public class JwtService(IOptions<JwtSettings> options) : IJwtService
{
private readonly JwtSettings _settings = options.Value;
public string GenerateToken(User user)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Key));
var creditnails = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _settings.Issuer,
audience: _settings.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_settings.ExpiresMinutes),
signingCredentials: creditnails
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
@@ -0,0 +1,11 @@
namespace AMessanger.Application.Settings;
public class JwtSettings
{
public const string SECTION_NAME = "Jwt";
public string Issuer { get; set; } = null!;
public string Audience { get; set; } = null!;
public int ExpiresMinutes { get; set; }
public string Key { get; set; } = null!;
}
+1 -1
View File
@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR" />
<PackageReference Include="Newtonsoft.Json" />
</ItemGroup>
</Project>
@@ -0,0 +1,11 @@
using AMessanger.Core.DTO;
using AMessanger.Core.Models;
namespace AMessanger.Core.Abstraction;
public interface IAccountService
{
public Task<Result<Guid>> RegisterAsync(CreateUserDto dto, CancellationToken cancellationToken = default);
public Task<Result<string>> LoginAsync(string userName, string password, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,8 @@
using AMessanger.Core.Models;
namespace AMessanger.Core.Abstraction;
public interface IJwtService
{
public string GenerateToken(User user);
}
@@ -0,0 +1,19 @@
using AMessanger.Core.DTO;
using AMessanger.Core.Models;
namespace AMessanger.Core.Abstraction;
public interface IUserService
{
public Task<Result<User>> CreateAsync(CreateUserDto dto, CancellationToken cancellationToken = default);
public Task<Result<User>> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
public Task<Result<User>> GetByUserNameAsync(string userName, CancellationToken cancellationToken = default);
public Task<Result<IEnumerable<User>>> GetAllAsync(CancellationToken cancellationToken = default);
public Task<Result<User>> UpdateAsync(Guid id, UpdateUserDto dto, CancellationToken cancellationToken = default);
public Task<Result<Guid>> DeleteAsync(Guid id, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,19 @@
using AMessanger.Core.Models;
using AMessanger.Core.DTO;
namespace AMessanger.Core.Abstraction;
public interface IUsersRepository
{
public Task<Result<Guid>> AddAsync(User user, CancellationToken cancellationToken = default);
public Task<Result<User>> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
public Task<Result<User>> GetByUserNameAsync(string userName, CancellationToken cancellationToken = default);
public Task<Result<IEnumerable<User>>> GetAllAsync(CancellationToken cancellationToken = default);
public Task<Result<User>> UpdateAsync(Guid id, UpdateUserDto dto, CancellationToken cancellationToken = default);
public Task<Result<Guid>> DeleteAsync(Guid id, CancellationToken cancellationToken = default);
}
+6
View File
@@ -0,0 +1,6 @@
namespace AMessanger.Core.DTO;
public record class CreateUserDto(
string Name,
string Password
);
+6
View File
@@ -0,0 +1,6 @@
namespace AMessanger.Core.DTO;
public record class UpdateUserDto(
string? Name,
string? Password
);
-13
View File
@@ -1,13 +0,0 @@
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
namespace AMessanger.Core.Hubs;
public class ChatHub(ILogger<ChatHub> logger) : Hub
{
public async Task SendMessage(string user, string message)
{
logger.LogInformation($"{user}: {message}");
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace AMessanger.Core.Models
{
public class Message(string userName, string content)
{
public string UserName { get; set; } = userName;
public string Content { get; set; } = content;
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace AMessanger.Core.Models;
public class User(Guid id, string name, string hashedPassword)
{
public Guid Id { get; private set; } = id;
public string Name { get; set; } = name;
public string HashedPassword { get; set; } = hashedPassword;
}
+21
View File
@@ -0,0 +1,21 @@
namespace AMessanger.Core;
public class Result<T>
{
public T? Value { get; }
public string? ErrorMessage { get; }
public bool IsSuccess { get; }
private Result(T? value, bool isSuccess, string? message)
{
Value = value;
IsSuccess = isSuccess;
ErrorMessage = message;
}
public static Result<T> Error(string message) => new(default, false, message);
public static Result<T> Success(T value) => new(value, true, null);
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../AMessanger.Core/AMessanger.Core.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,8 @@
namespace AMessanger.DataAccess.Entities;
public class UserEntity(Guid id, string name, string hashedPassword)
{
public Guid Id { get; set; } = id;
public string Name { get; set; } = name;
public string HashedPassword { get; set; } = hashedPassword;
}
@@ -0,0 +1,65 @@
using AMessanger.Core;
using AMessanger.Core.Abstraction;
using AMessanger.Core.DTO;
using AMessanger.Core.Models;
using AMessanger.DataAccess.Entities;
namespace AMessanger.DataAccess.Repositories;
public class UsersRepository : IUsersRepository
{
private static readonly List<UserEntity> sUsers = [];
public Task<Result<Guid>> AddAsync(User user, CancellationToken cancellationToken = default)
{
sUsers.Add(new(user.Id, user.Name, user.HashedPassword));
return Task.FromResult(Result<Guid>.Success(user.Id));
}
public Task<Result<Guid>> DeleteAsync(Guid id, CancellationToken cancellationToken = default)
{
var user = sUsers.Find(u => u.Id == id);
if (user == null)
return Task.FromResult(Result<Guid>.Error("Not found"));
sUsers.Remove(user);
return Task.FromResult(Result<Guid>.Success(user.Id));
}
public Task<Result<IEnumerable<User>>> GetAllAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(
Result<IEnumerable<User>>.Success(
sUsers.Select(u => new User(u.Id, u.Name, u.HashedPassword))
)
);
}
public Task<Result<User>> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
var user = sUsers.Find(u => u.Id == id);
if (user == null)
return Task.FromResult(Result<User>.Error("Not found"));
return Task.FromResult(
Result<User>.Success(new User(user.Id, user.Name, user.HashedPassword))
);
}
public Task<Result<User>> GetByUserNameAsync(string userName, CancellationToken cancellationToken = default)
{
var user = sUsers.Find(u => u.Name.Equals(userName, StringComparison.InvariantCultureIgnoreCase));
if (user == null)
return Task.FromResult(Result<User>.Error("Not found"));
return Task.FromResult(
Result<User>.Success(new User(user.Id, user.Name, user.HashedPassword))
);
}
public Task<Result<User>> UpdateAsync(Guid id, UpdateUserDto dto, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
}
+6
View File
@@ -1,4 +1,10 @@
<Solution>
<Project Path="AMessanger.API/AMessanger.API.csproj" />
<Project Path="AMessanger.Application/AMessanger.Application.csproj" />
<Project Path="AMessanger.Core/AMessanger.Core.csproj" />
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR" />
</ItemGroup>
<Project Path="AMessanger.DataAccess/AMessanger.DataAccess.csproj" />
</Solution>
+2
View File
@@ -3,8 +3,10 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR" Version="1.2.12" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.2.3" />
</ItemGroup>
</Project>