dodanie logowania użytkownika - błąd tworzenia tokenu

This commit is contained in:
Maciej Maciejewski 2024-10-23 23:16:01 +02:00
parent 7cbe1129ef
commit 9f395ac634
22 changed files with 620 additions and 30 deletions

View File

@ -0,0 +1,9 @@
namespace FirmTracker_Server.Authentication
{
public class AuthenticationSettings
{
public string JwtSecKey { get; set; }
public int JwtExpireDays { get; set; }
public string JwtIssuer { get; set; }
}
}

View File

@ -16,6 +16,8 @@
*/ */
using FirmTracker_Server.nHibernate.Products; using FirmTracker_Server.nHibernate.Products;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
@ -23,6 +25,7 @@ namespace FirmTracker_Server.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [ApiController]
[Authorize]
public class ProductsController : ControllerBase public class ProductsController : ControllerBase
{ {
private readonly ProductCRUD _productCrud; private readonly ProductCRUD _productCrud;
@ -39,6 +42,7 @@ namespace FirmTracker_Server.Controllers
[HttpPost] [HttpPost]
[ProducesResponseType(200)] // Created [ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request [ProducesResponseType(400)] // Bad Request
[Authorize(Roles = Roles.User)]
public IActionResult CreateProduct([FromBody] Product product) public IActionResult CreateProduct([FromBody] Product product)
{ {
try try
@ -162,6 +166,7 @@ namespace FirmTracker_Server.Controllers
[HttpGet] [HttpGet]
[ProducesResponseType(200)] // Created [ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request [ProducesResponseType(400)] // Bad Request
[Authorize(Roles =Roles.User)]
public IActionResult GetAllProducts() public IActionResult GetAllProducts()
{ {
var products = _productCrud.GetAllProducts(); var products = _productCrud.GetAllProducts();

View File

@ -0,0 +1,50 @@
using FirmTracker_Server.Models;
using FirmTracker_Server.Services;
using FirmTracker_Server;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.Entities;
namespace FirmTracker_Server.Controllers
{
[Route("api/user")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
private readonly IUserService UserService;
public UserController(IUserService userService)
{
UserService = userService;
}
[HttpPost("create")]
[Authorize(Roles = Roles.Admin)]
public ActionResult CreateUser([FromBody] CreateUserDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest("Nieprawidłowa wartość pola. /n" + ModelState);
}
var id = UserService.AddUser(dto);
return Created($"/api/user/{id}", "User dodany poprawnie");
}
[HttpPost("login")]
[AllowAnonymous]
public ActionResult Login([FromBody] LoginDto dto)
{
var token = UserService.CreateTokenJwt(dto);
return Ok(token);
}
// New method to get all users
/* [HttpGet("all")]
[AllowAnonymous]
public ActionResult<IList<User>> GetAllUsers()
{
var users = UserService.GetAllUsers();
return Ok(users);
}*/
}
}

12
Entities/User.cs Normal file
View File

@ -0,0 +1,12 @@
namespace FirmTracker_Server.Entities
{
public class User
{
public virtual int Id { get; set; }
public virtual string Login { get; set; }
public virtual string Email { get; set; }
public virtual string Role { get; set; } = "User";
public virtual string PassHash { get; set; }
public virtual bool NewEncryption { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace FirmTracker_Server.Exceptions
{
public class NoResultsException : Exception
{
public NoResultsException() : base("Brak wyników") { }
public NoResultsException(string message) : base(message) { }
public NoResultsException(string message, Exception innerException) : base(message, innerException) { }
}
}

View File

@ -0,0 +1,11 @@
namespace FirmTracker_Server.Exceptions
{
public class PermissionException : Exception
{
public PermissionException() : base("Brak uprawnień") { }
public PermissionException(string message) : base(message) { }
public PermissionException(string message, Exception innerException) : base(message, innerException) { }
}
}

View File

@ -0,0 +1,11 @@
namespace FirmTracker_Server.Exceptions
{
public class WrongUserOrPasswordException : Exception
{
public WrongUserOrPasswordException() : base("Nieprawidłowy użytkownik lub hasło.") { }
public WrongUserOrPasswordException(string message) : base(message) { }
public WrongUserOrPasswordException(string message, Exception innerException) : base(message, innerException) { }
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>FirmTracker_Server</RootNamespace> <RootNamespace>FirmTracker_Server</RootNamespace>
@ -17,13 +17,27 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentNHibernate" Version="3.3.0" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="FluentNHibernate" Version="3.4.0" />
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.12" />
<PackageReference Include="NHibernate" Version="5.5.1" /> <PackageReference Include="NHibernate" Version="5.5.2" />
<PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="NLog.Database" Version="5.3.4" />
<PackageReference Include="NSwag.Annotations" Version="14.0.7" /> <PackageReference Include="NSwag.Annotations" Version="14.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" /> <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" />
</ItemGroup>
<ItemGroup>
<Reference Include="szyfrowanie">
<HintPath>..\..\..\Desktop\szyfrowanie.dll</HintPath>
</Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

13
Helpers/RolesHelper.cs Normal file
View File

@ -0,0 +1,13 @@
namespace FirmTracker_Server
{
public static class RolesHelper
{
public static IEnumerable<string> GetRoles() => new List<string> { Roles.Admin, Roles.User };
}
public static class Roles
{
public const string Admin = "Admin";
public const string User = "User";
}
}

75
Logger.cs Normal file
View File

@ -0,0 +1,75 @@
using System;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace IntegrationWithCzech
{
public static class Logger
{
private static NLog.Logger log;
public static void ConfigLog()
{
var config = new LoggingConfiguration();
string appDirectory = Directory.GetCurrentDirectory();
string configFilePath = Path.Combine(appDirectory, "appsettings.json");
var config1 = new ConfigurationBuilder()
.AddJsonFile(configFilePath)
.Build();
var connectionstringsection = config1.GetSection("AppSettings:ConnectionString");
string connectionString = connectionstringsection.Value;
// Czech Database Target
var LogDbTarget = new DatabaseTarget("logDBTarget")
{
ConnectionString = connectionString,
CommandText = "INSERT INTO CDN.CzechLogTable(Date, Level, Message, Exception) VALUES(@date, @level, @message, @exception)"
};
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@date", "${longdate}"));
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@level", "${level}"));
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@message", "${message}"));
LogDbTarget.Parameters.Add(new DatabaseParameterInfo("@exception", "${exception}"));
var logconsole = new ConsoleTarget("logconsole")
{
Layout = "${longdate} ${message} ${exception}"
};
// Adding Rules for Poland Logging
config.AddRuleForOneLevel(NLog.LogLevel.Error, LogDbTarget, "PolandLogger");
config.AddRuleForAllLevels(logconsole, "PolandLogger");
LogManager.Configuration = config;
log = LogManager.GetLogger("CzechLogger");
}
public static void LogInfo(string message)
{
log?.Info(message);
}
public static void Write2CzechLogError(string message, Exception ex = null)
{
if (ex is null)
{
log?.Error(message);
}
else
{
log?.Error(ex, message);
}
}
}
}

View File

@ -0,0 +1,24 @@
using AutoMapper;
using FirmTracker_Server.Entities;
using FirmTracker_Server.Models;
using NHibernate.Type;
using NuGet.Packaging.Licenses;
using System.ComponentModel;
namespace FirmTracker_Server.Mappings
{
public class LicenseMappingProfile : Profile
{
public LicenseMappingProfile()
{
// CreateMap<License, LicenseDto>();
// CreateMap<LicenseDto, License>();
// CreateMap<CreateLicenseDto, License>();
// CreateMap<LicType, LicTypeDto>();
// CreateMap<LicTypeDto, LicType>();
CreateMap<UserDto, User>();
CreateMap<User, UserDto>();
CreateMap<CreateUserDto, User>().ForSourceMember(x => x.Password, y => y.DoNotValidate());
}
}
}

View File

@ -0,0 +1,43 @@
using FirmTracker_Server.Exceptions;
namespace FirmTracker_Server.Middleware
{
public class ErrorHandling : IMiddleware
{
private readonly ILogger Logger;
public ErrorHandling(ILogger<ErrorHandling> logger)
{
Logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
catch (WrongUserOrPasswordException ex)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync(ex.Message);
}
catch (PermissionException ex)
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync(ex.Message);
}
catch (NoResultsException ex)
{
context.Response.StatusCode = 404;
await context.Response.WriteAsync(ex.Message);
}
catch (Exception ex)
{
Logger.LogError(ex, "Wystąpił nieoczekiwany błąd.");
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync("Wystąpił nieoczekiwany błąd.");
}
}
}
}

11
Models/CreateUserDto.cs Normal file
View File

@ -0,0 +1,11 @@
namespace FirmTracker_Server.Models
{
public class CreateUserDto
{
public string Login { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Role { get; set; }
public bool NewEncryption { get; set; } = true;
}
}

9
Models/LoginDtocs.cs Normal file
View File

@ -0,0 +1,9 @@
namespace FirmTracker_Server.Models
{
public class LoginDto
{
public string Email { get; set; }
public string Password { get; set; }
}
}

22
Models/UserDto.cs Normal file
View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace FirmTracker_Server.Models
{
public class UserDto
{
[Required]
[MaxLength(16)]
public string Login { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[MinLength(8, ErrorMessage = "Password must be at least 8 characters long.")]
[MaxLength(100, ErrorMessage = "Password cannot be longer than 100 characters.")]
[RegularExpression(@"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$", ErrorMessage = "Password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character.")]
public string Password { get; set; }
}
}

View File

@ -24,13 +24,27 @@ using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server.nHibernate; using FirmTracker_Server.nHibernate;
using FirmTracker_Server.Utilities.Converters; using FirmTracker_Server.Utilities.Converters;
using FirmTracker_Server.Utilities.Swagger; using FirmTracker_Server.Utilities.Swagger;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using AutoMapper;
using Microsoft.AspNetCore.Authentication;
using System.Text;
using FirmTracker_Server.Entities;
using FirmTracker_Server.Middleware;
using FirmTracker_Server.Services;
using System.Reflection;
using FirmTracker_Server.Mappings;
namespace FirmTracker_Server namespace FirmTracker_Server
{ {
public class Program internal static class Program
{ {
public static void Main(string[] args) public static async Task Main(string[] args)
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
string appDirectory = Directory.GetCurrentDirectory(); string appDirectory = Directory.GetCurrentDirectory();
@ -55,6 +69,7 @@ namespace FirmTracker_Server
TestClass test = new TestClass(); TestClass test = new TestClass();
test.AddTestProduct(); test.AddTestProduct();
builder.Services.AddCors(options => builder.Services.AddCors(options =>
{ {
options.AddPolicy("AllowSpecificOrigin", options.AddPolicy("AllowSpecificOrigin",
@ -62,19 +77,24 @@ namespace FirmTracker_Server
.AllowAnyHeader() .AllowAnyHeader()
.AllowAnyMethod()); .AllowAnyMethod());
}); });
builder.Services.ConfigureAutoMapper();
builder.Services.ConfigureServiceInjection();
builder.Services.AddControllers() builder.Services.AddControllers()
.AddJsonOptions(options => .AddJsonOptions(options =>
{ {
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
}); });
; ;
builder.ConfigureAuthentication();
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c => builder.Services.AddSwaggerGen(c =>
{ {
c.SchemaFilter<SwaggerDateTimeSchemaFilter>(); c.SchemaFilter<SwaggerDateTimeSchemaFilter>();
}); });
var app = builder.Build(); var app = builder.Build();
var configSwagger = new ConfigurationBuilder() var configSwagger = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) .SetBasePath(Directory.GetCurrentDirectory())
@ -107,6 +127,7 @@ namespace FirmTracker_Server
app.UseCors("AllowSpecificOrigin"); app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
@ -117,5 +138,43 @@ namespace FirmTracker_Server
app.Run(); app.Run();
} }
private static void ConfigureAuthentication(this WebApplicationBuilder builder)
{
var authenticationSettings = new Authentication.AuthenticationSettings();
builder.Configuration.GetSection("TokenConfig").Bind(authenticationSettings);
builder.Services.AddAuthentication(option => {
option.DefaultAuthenticateScheme = "Bearer";
option.DefaultScheme = "Bearer";
option.DefaultChallengeScheme = "Bearer";
}).AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = authenticationSettings.JwtIssuer,
ValidAudience = authenticationSettings.JwtIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.JwtSecKey)),
};
});
builder.Services.AddSingleton(authenticationSettings);
}
private static void ConfigureAutoMapper(this IServiceCollection services)
{
var mapperConfig = new MapperConfiguration(mc => {
mc.AddProfile<LicenseMappingProfile>();
// mc.AddProfile<PayLinkerMappingProfile>();
});
var mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddAutoMapper(Assembly.GetExecutingAssembly());
}
private static void ConfigureServiceInjection(this IServiceCollection services)
{
services.AddScoped<IUserService, UserService>();
services.AddScoped<ErrorHandling>();
services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
services.AddMvc();
}
} }
} }

144
Services/UserService.cs Normal file
View File

@ -0,0 +1,144 @@
using AutoMapper;
using FirmTracker_Server.Authentication;
using FirmTracker_Server.Entities;
using FirmTracker_Server.Exceptions;
using FirmTracker_Server.Models;
using FirmTracker_Server.Authentication;
using FirmTracker_Server.Exceptions;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using szyfrowanie;
using FirmTracker_Server.nHibernate;
using NHibernate;
using NHibernate.Criterion;
namespace FirmTracker_Server.Services
{
public interface IUserService
{
UserDto GetById(int id);
int AddUser(CreateUserDto dto);
string CreateTokenJwt(LoginDto dto);
}
public class UserService : IUserService
{
// private readonly GeneralDbContext DbContext;
private readonly IMapper Mapper;
private readonly IPasswordHasher<User> PasswordHasher;
private readonly AuthenticationSettings AuthenticationSettings;
private readonly SimplerAES SimplerAES;
//private readonly SessionFactory sessionFactory;
public UserService( IMapper mapper, IPasswordHasher<User> passwordHasher, AuthenticationSettings authenticationSettings)
{
// DbContext = dbContext;
Mapper = mapper;
PasswordHasher = passwordHasher;
AuthenticationSettings = authenticationSettings;
SimplerAES = new SimplerAES();
//SessionFactory = sessionFactory;
}
public UserDto GetById(int id)
{
using (var session = SessionFactory.OpenSession())
{
var user = session.Get<User>(id);
return user == null ? null : Mapper.Map<UserDto>(user);
}
}
public int AddUser(CreateUserDto dto)
{
var user = Mapper.Map<User>(dto);
// Encrypt or hash the password based on NewEncryption flag
user.PassHash = dto.NewEncryption ? SimplerAES.Encrypt(dto.Password) : PasswordHasher.HashPassword(user, dto.Password);
user.Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dto.Role.ToLower());
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
try
{
session.Save(user);
transaction.Commit();
return user.Id;
}
catch
{
transaction.Rollback();
throw;
}
}
}
public string CreateTokenJwt(LoginDto dto)
{
User user = null;
using (var session = SessionFactory.OpenSession())
{
if (!string.IsNullOrEmpty(dto.Email))
{
user = session.Query<User>().FirstOrDefault(x => x.Email == dto.Email);
}
else
{
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
}
if (user == null)
{
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
}
// Password verification logic
if (user.NewEncryption)
{
try
{
Console.WriteLine(SimplerAES.Decrypt(user.PassHash)+" "+SimplerAES.Decrypt(dto.Password));
var ready = SimplerAES.Decrypt(user.PassHash) == SimplerAES.Decrypt(dto.Password);
if (!ready)
{
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
}
}
catch (Exception)
{
throw new WrongUserOrPasswordException("Wystąpił błąd podczas logowania");
}
}
else
{
var ready = PasswordVerificationResult.Failed;
if (SimplerAES.Decrypt(user.PassHash) == SimplerAES.Decrypt(dto.Password)) { ready = PasswordVerificationResult.Success; } //PasswordHasher.VerifyHashedPassword(user, user.PassHash, dto.Password);
if (ready == PasswordVerificationResult.Failed)
{
throw new WrongUserOrPasswordException("Nieprawidłowy login lub hasło.");
}
}
// Generate JWT token
var claims = new List<Claim>() {
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Role, user.Role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AuthenticationSettings.JwtSecKey));
var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(AuthenticationSettings.JwtExpireDays);
var token = new JwtSecurityToken(AuthenticationSettings.JwtIssuer, AuthenticationSettings.JwtIssuer, claims, expires: expires, signingCredentials: credential);
var finalToken = new JwtSecurityTokenHandler();
return finalToken.WriteToken(token);
}
}
}
}

View File

@ -21,6 +21,12 @@ using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server.nHibernate.Transactions; using FirmTracker_Server.nHibernate.Transactions;
using FirmTracker_Server.nHibernate.Expenses; using FirmTracker_Server.nHibernate.Expenses;
using NHibernate; using NHibernate;
using FirmTracker_Server.Entities;
using FirmTracker_Server.Services;
using AutoMapper;
using FirmTracker_Server.Authentication;
using Microsoft.AspNetCore.Identity;
using FirmTracker_Server.Models;
namespace FirmTracker_Server namespace FirmTracker_Server
{ {
@ -162,10 +168,16 @@ namespace FirmTracker_Server
}; };
try try
{ {
FirmTracker_Server.nHibernate.Products.ProductCRUD productCrud = new ProductCRUD(); FirmTracker_Server.nHibernate.Products.ProductCRUD productCrud = new ProductCRUD();
FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD(); FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD();
ExpenseCRUD expenseCrud = new ExpenseCRUD(); ExpenseCRUD expenseCrud = new ExpenseCRUD();
// productCrud.AddProduct(product); // productCrud.AddProduct(product);
productCrud.AddProduct(product2); productCrud.AddProduct(product2);

View File

@ -1,29 +1,35 @@
{ {
"AppSettings": { "AppSettings": {
"ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;" "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;"
}, },
"profiles": { "TokenConfig": {
"http": { "JwtSecKey": "omgi5Rf4tqg351GQwefw",
"commandName": "Project", "JwtExpireDays": 30,
"dotnetRunMessages": true, "JwtIssuer": "http://api.graphcom.pl"
"launchBrowser": true, },
"launchUrl": "swagger", "profiles": {
"applicationUrl": "http://localhost:5045" "http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5045"
}, },
"https": { "https": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"applicationUrl": "https://localhost:7039" "applicationUrl": "https://localhost:7039"
}, },
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger" "launchUrl": "swagger"
}
} }
}
} }

30
nHIbernate/LogsMapping.cs Normal file
View File

@ -0,0 +1,30 @@
/*
* This file is part of FirmTracker - Server.
*
* FirmTracker - Server is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FirmTracker - Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FirmTracker - Server. If not, see <https://www.gnu.org/licenses/>.
*/
using System.Text.Json.Serialization;
namespace FirmTracker_Server.nHibernate
{
public class LogsMapping
{
public virtual int Id { get; set; }
public virtual DateTime Date { get; set; }
public virtual string Level { get; set; }
public virtual string Message { get; set; }
public virtual string Exception { get; set; }
}
}

View File

@ -53,7 +53,10 @@ namespace FirmTracker_Server.nHibernate
.AddFromAssemblyOf<Expenses.ExpenseMapping>() .AddFromAssemblyOf<Expenses.ExpenseMapping>()
.AddFromAssemblyOf<Reports.ReportMapping>() .AddFromAssemblyOf<Reports.ReportMapping>()
.AddFromAssemblyOf<Reports.ReportTransactionMapping>() .AddFromAssemblyOf<Reports.ReportTransactionMapping>()
.AddFromAssemblyOf<Reports.ReportExpenseMapping>(); .AddFromAssemblyOf<Reports.ReportExpenseMapping>()
.AddFromAssemblyOf<LogsMapping>()
.AddFromAssemblyOf<UserMapping>();
}) })
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update
.BuildSessionFactory(); .BuildSessionFactory();

16
nHIbernate/UserMapping.cs Normal file
View File

@ -0,0 +1,16 @@
using FluentNHibernate.Mapping;
using FirmTracker_Server.Entities;
public class UserMapping : ClassMap<User>
{
public UserMapping()
{
Table("Users"); // The name of your table in the database
Id(x => x.Id); // Mapping the Id property
Map(x => x.Email); // Mapping other properties
Map(x => x.PassHash);
Map(x => x.Role);
// Add other mappings as needed
}
}