Add project files.

This commit is contained in:
KhasanovAM
2026-01-18 00:30:29 +04:00
parent 9c5a7ce993
commit 61a598aceb
27 changed files with 1974 additions and 0 deletions

80
Services/AuthService.cs Normal file
View File

@@ -0,0 +1,80 @@
using LogisticsApp.Server.Data;
using LogisticsApp.Server.DTOs;
using LogisticsApp.Server.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace LogisticsApp.Server.Services
{
public interface IAuthService
{
Task<LoginResponse?> LoginAsync(LoginRequest request);
string GenerateJwtToken(User user);
}
public class AuthService : IAuthService
{
private readonly ApplicationDbContext _context;
private readonly IConfiguration _configuration;
public AuthService(ApplicationDbContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
public async Task<LoginResponse?> LoginAsync(LoginRequest request)
{
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Username == request.Username);
if (user == null || !VerifyPassword(request.Password, user.PasswordHash))
{
return null;
}
var token = GenerateJwtToken(user);
return new LoginResponse
{
Token = token,
Username = user.Username,
Role = user.Role,
Expires = DateTime.UtcNow.AddHours(24)
};
}
public string GenerateJwtToken(User user)
{
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key not configured")));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Role, user.Role)
};
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddHours(24),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
private static bool VerifyPassword(string password, string passwordHash)
{
return BCrypt.Net.BCrypt.Verify(password, passwordHash);
}
}
}