Compare commits

..

No commits in common. "1c27bffa7355744fc30f9562061822601bc388ea" and "098fca5df8693ecf479d8df0e32693a66cc27a75" have entirely different histories.

25 changed files with 935 additions and 225 deletions

18
.env
View File

@ -9,7 +9,7 @@
# General
# The path to save the data
# The path to save the data.
# string
# (optional)
# Saving logs (if the full path is not specified),
@ -18,22 +18,6 @@
# If you want to change this value, you need to change the values in Settings.json and move the file itself to the desired location.
PATH_TO_SAVE=
# The actual sub path to the api
# string
# (optional)
ACTUAL_SUB_PATH=
# The sub path to the swagger
# string
# (optional)
SWAGGER_SUB_PATH=swagger
# Internal port configuration
# integer
# (optional)
# Specify the internal port on which the server will listen.
INTERNAL_PORT=8080
# Security
# JWT signature token

View File

@ -75,7 +75,6 @@ jobs:
-e SECURITY_HASH_SIZE=$SECURITY_HASH_SIZE \
-e SECURITY_HASH_TOKEN=$SECURITY_HASH_TOKEN \
-e SECURITY_SALT_SIZE=$SECURITY_SALT_SIZE \
-e ACTUAL_SUB_PATH=api \
$DOCKER_IMAGE
"

View File

@ -15,10 +15,9 @@ ENV NUGET_PASSWORD=$NUGET_PASSWORD
RUN dotnet restore ./Backend.sln --configfile nuget.config
WORKDIR /app
WORKDIR /src
RUN dotnet publish ./Endpoint/Endpoint.csproj -c Release --self-contained false -p:PublishSingleFile=false -o /app
RUN dotnet publish ./Endpoint/Endpoint.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=build /app .
RUN find . -name "*.pdb" -type f -delete
ENTRYPOINT ["dotnet", "Mirea.Api.Endpoint.dll"]

View File

@ -0,0 +1,10 @@
namespace Mirea.Api.Endpoint.Common.Model;
public class Admin
{
public const string PathToSave = "admin.json";
public required string Username { get; set; }
public required string Email { get; set; }
public required string PasswordHash { get; set; }
public required string Salt { get; set; }
}

View File

@ -1,46 +0,0 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
namespace Mirea.Api.Endpoint.Common.Services;
public static class UrlHelper
{
public static string CurrentDomain(HttpContext context) =>
context.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? context.Request.Host.Host;
private static string CreateSubPath(string? path)
{
if (string.IsNullOrEmpty(path))
return "/";
return "/" + path.Trim('/') + "/";
}
public static string GetSubPath => CreateSubPath(Environment.GetEnvironmentVariable("ACTUAL_SUB_PATH"));
public static string GetSubPathWithoutFirstApiName
{
get
{
var path = GetSubPath;
if (string.IsNullOrEmpty(path) || path == "/")
return CreateSubPath(null);
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
if (!parts[i].Equals("api", StringComparison.CurrentCultureIgnoreCase)) continue;
parts = parts.Take(i).Concat(parts.Skip(i + 1)).ToArray();
break;
}
return CreateSubPath(string.Join("/", parts));
}
}
public static string GetSubPathSwagger => CreateSubPath(Environment.GetEnvironmentVariable("SWAGGER_SUB_PATH"));
}

View File

@ -1,25 +0,0 @@
using Mirea.Api.Endpoint.Common.Services;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Mirea.Api.Endpoint.Common.Settings;
public class Admin : ISaveSettings
{
[JsonIgnore] private const string FileName = "admin.json";
[JsonIgnore]
public static string FilePath => PathBuilder.Combine(FileName);
public required string Username { get; set; }
public required string Email { get; set; }
public required string PasswordHash { get; set; }
public required string Salt { get; set; }
public void SaveSetting()
{
File.WriteAllText(FilePath, JsonSerializer.Serialize(this));
}
}

View File

@ -1,33 +0,0 @@
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Configuration.General.Settings;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Mirea.Api.Endpoint.Common.Settings;
public class GeneralConfig : ISaveSettings
{
[JsonIgnore] private const string FileName = "Settings.json";
[JsonIgnore]
public static string FilePath => PathBuilder.Combine(FileName);
public DbSettings? DbSettings { get; set; }
public CacheSettings? CacheSettings { get; set; }
public ScheduleSettings? ScheduleSettings { get; set; }
public EmailSettings? EmailSettings { get; set; }
public LogSettings? LogSettings { get; set; }
public string? SecretForwardToken { get; set; }
public void SaveSetting()
{
File.WriteAllText(
FilePath,
JsonSerializer.Serialize(this, new JsonSerializerOptions
{
WriteIndented = true
})
);
}
}

View File

@ -1,5 +0,0 @@
namespace Mirea.Api.Endpoint.Common.Settings;
public interface ISaveSettings
{
void SaveSetting();
}

View File

@ -1,6 +1,6 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.General;
using Mirea.Api.Endpoint.Configuration.General.Settings;
namespace Mirea.Api.Endpoint.Configuration.AppConfig;

View File

@ -9,9 +9,9 @@ namespace Mirea.Api.Endpoint.Configuration.AppConfig;
public static class EnvironmentConfiguration
{
private static Dictionary<string, string> LoadEnvironment(string envFile)
private static IDictionary<string, string> LoadEnvironment(string envFile)
{
Dictionary<string, string> environment = [];
Dictionary<string, string> environment = new();
if (!File.Exists(envFile)) return environment;
@ -46,10 +46,6 @@ public static class EnvironmentConfiguration
{
var variablesFromFile = LoadEnvironment(".env");
#if DEBUG
LoadEnvironment(".env.develop").ToList().ForEach(x => variablesFromFile.Add(x.Key, x.Value));
#endif
var environmentVariables = Environment.GetEnvironmentVariables()
.OfType<DictionaryEntry>()
.ToDictionary(
@ -61,18 +57,12 @@ public static class EnvironmentConfiguration
.AddInMemoryCollection(environmentVariables!)
.AddInMemoryCollection(variablesFromFile!);
if (variablesFromFile.TryGetValue("PATH_TO_SAVE", out var pathToSave))
{
Environment.SetEnvironmentVariable("PATH_TO_SAVE", pathToSave);
if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
}
#if DEBUG
result.AddInMemoryCollection(LoadEnvironment(".env.develop")!);
#endif
if (variablesFromFile.TryGetValue("ACTUAL_SUB_PATH", out var actualSubPath))
Environment.SetEnvironmentVariable("ACTUAL_SUB_PATH", actualSubPath);
if (variablesFromFile.TryGetValue("SWAGGER_SUB_PATH", out var swaggerSubPath))
Environment.SetEnvironmentVariable("SWAGGER_SUB_PATH", swaggerSubPath);
if (variablesFromFile.TryGetValue("PATH_TO_SAVE", out var data))
Environment.SetEnvironmentVariable("PATH_TO_SAVE", variablesFromFile["PATH_TO_SAVE"]);
return result.Build();
}

View File

@ -2,7 +2,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.General;
using Serilog;
using Serilog.Events;
using Serilog.Filters;

View File

@ -1,7 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Mirea.Api.Endpoint.Common.Services.Security;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.General;
using Mirea.Api.Endpoint.Configuration.General.Settings;
using Mirea.Api.Security;
using Mirea.Api.Security.Common.Interfaces;

View File

@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Configuration.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
@ -44,11 +43,8 @@ public static class SwaggerConfiguration
}
});
if (File.Exists(Path.Combine(basePath, "docs.xml")))
options.IncludeXmlComments(Path.Combine(basePath, "docs.xml"));
if (File.Exists(Path.Combine(basePath, "ApiDtoDocs.xml")))
options.IncludeXmlComments(Path.Combine(basePath, "ApiDtoDocs.xml"));
options.IncludeXmlComments(Path.Combine(basePath, "docs.xml"));
options.IncludeXmlComments(Path.Combine(basePath, "ApiDtoDocs.xml"));
});
services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
@ -69,7 +65,6 @@ public static class SwaggerConfiguration
var url = $"/swagger/{description.GroupName}/swagger.json";
var name = description.GroupName.ToUpperInvariant();
options.SwaggerEndpoint(url, name);
options.RoutePrefix = UrlHelper.GetSubPathSwagger.Trim('/');
}
});

View File

@ -0,0 +1,14 @@
using Mirea.Api.Endpoint.Configuration.General.Settings;
namespace Mirea.Api.Endpoint.Configuration.General;
public class GeneralConfig
{
public const string FilePath = "Settings.json";
public DbSettings? DbSettings { get; set; }
public CacheSettings? CacheSettings { get; set; }
public ScheduleSettings? ScheduleSettings { get; set; }
public EmailSettings? EmailSettings { get; set; }
public LogSettings? LogSettings { get; set; }
}

View File

@ -1,5 +1,4 @@
using Microsoft.Extensions.Options;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.General.Attributes;
using Mirea.Api.Endpoint.Configuration.General.Interfaces;
using System;

View File

@ -8,8 +8,9 @@ using Mirea.Api.Dto.Requests.Configuration;
using Mirea.Api.Endpoint.Common.Attributes;
using Mirea.Api.Endpoint.Common.Exceptions;
using Mirea.Api.Endpoint.Common.Interfaces;
using Mirea.Api.Endpoint.Common.Model;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.General;
using Mirea.Api.Endpoint.Configuration.General.Settings;
using Mirea.Api.Endpoint.Configuration.General.Validators;
using Mirea.Api.Security.Services;
@ -23,6 +24,7 @@ using System.IO;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Mirea.Api.Endpoint.Controllers.Configuration;
@ -31,7 +33,7 @@ namespace Mirea.Api.Endpoint.Controllers.Configuration;
[ApiController]
[MaintenanceModeIgnore]
[ApiExplorerSettings(IgnoreApi = true)]
public partial class SetupController(
public class SetupController(
ISetupToken setupToken,
IMaintenanceModeNotConfigureService notConfigureService,
IMemoryCache cache,
@ -53,7 +55,7 @@ public partial class SetupController(
if (!notConfigureService.IsMaintenanceMode)
throw new ControllerArgumentException(
"The token cannot be generated because the server has been configured. " +
$"If you need to restart the configuration, then delete the \"{GeneralConfig.FilePath}\" file and restart the application.");
$"If you need to restart the configuration, then delete the \"{PathBuilder.Combine(GeneralConfig.FilePath)}\" file and restart the application.");
var token = new byte[32];
RandomNumberGenerator.Create().GetBytes(token);
@ -69,11 +71,11 @@ public partial class SetupController(
Response.Cookies.Append("AuthToken", token, new CookieOptions
{
Path = UrlHelper.GetSubPathWithoutFirstApiName + "api",
Domain = UrlHelper.CurrentDomain(ControllerContext.HttpContext),
Secure = true,
HttpOnly = true
HttpOnly = false,
Secure = false,
Path = "/"
});
return Ok(true);
}
@ -206,7 +208,7 @@ public partial class SetupController(
[BadRequestResponse]
public ActionResult<string> CreateAdmin([FromBody] CreateUserRequest user)
{
if (user.Password.Length < 8 || !PasswordExistUpperLetter().IsMatch(user.Password) || !PasswordExistSpecialSymbol().IsMatch(user.Password))
if (user.Password.Length < 8 || !Regex.IsMatch(user.Password, "[A-Z]+") || !Regex.IsMatch(user.Password, "[!@#$%^&*]+"))
throw new ControllerArgumentException("The password must be at least 8 characters long and contain at least one uppercase letter and one special character.");
if (!MailAddress.TryCreate(user.Email, out _))
@ -331,15 +333,19 @@ public partial class SetupController(
if (!cache.TryGetValue(CacheAdminKey, out Admin? admin) || admin == null)
throw new ControllerArgumentException("The administrator's data was not set.");
admin.SaveSetting();
GeneralConfig.SaveSetting();
if (System.IO.File.Exists(PathBuilder.Combine(GeneralConfig.FilePath)))
System.IO.File.Delete(PathBuilder.Combine(GeneralConfig.FilePath));
System.IO.File.WriteAllText(PathBuilder.Combine(Admin.PathToSave), JsonSerializer.Serialize(admin));
System.IO.File.WriteAllText(
PathBuilder.Combine(GeneralConfig.FilePath),
JsonSerializer.Serialize(GeneralConfig, new JsonSerializerOptions
{
WriteIndented = true
})
);
return true;
}
[GeneratedRegex("[A-Z]+")]
private static partial Regex PasswordExistUpperLetter();
[GeneratedRegex("[!@#$%^&*]+")]
private static partial Regex PasswordExistSpecialSymbol();
}

View File

@ -6,8 +6,7 @@ using Microsoft.Extensions.Options;
using Mirea.Api.Dto.Common;
using Mirea.Api.Dto.Requests;
using Mirea.Api.Dto.Responses;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Common.Model;
using Mirea.Api.Security.Common.Dto.Requests;
using Mirea.Api.Security.Services;
using System;
@ -29,8 +28,8 @@ public class AuthController(IOptionsSnapshot<Admin> user, AuthService auth, Pass
var cookieOptions = new CookieOptions
{
Expires = expires,
Path = UrlHelper.GetSubPathWithoutFirstApiName + "api",
Domain = UrlHelper.CurrentDomain(ControllerContext.HttpContext),
Path = "/api",
Domain = Request.Headers["X-Forwarded-Host"],
Secure = true,
HttpOnly = true
};

View File

@ -8,7 +8,7 @@ using Mirea.Api.Dto.Requests;
using Mirea.Api.Dto.Responses;
using Mirea.Api.Endpoint.Common.Attributes;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.General;
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -5,9 +5,9 @@
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<Company>Winsomnia</Company>
<Version>1.0.0-b0</Version>
<AssemblyVersion>1.0.1.0</AssemblyVersion>
<FileVersion>1.0.1.0</FileVersion>
<Version>1.0.0-a0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyName>Mirea.Api.Endpoint</AssemblyName>
<RootNamespace>$(AssemblyName)</RootNamespace>
<OutputType>Exe</OutputType>
@ -31,12 +31,12 @@
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Versioning" Version="2.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.6.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.6.0" />
</ItemGroup>
<ItemGroup>

View File

@ -1,6 +1,4 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
@ -8,13 +6,12 @@ using Mirea.Api.DataAccess.Application;
using Mirea.Api.DataAccess.Persistence;
using Mirea.Api.DataAccess.Persistence.Common;
using Mirea.Api.Endpoint.Common.Interfaces;
using Mirea.Api.Endpoint.Common.Model;
using Mirea.Api.Endpoint.Common.Services;
using Mirea.Api.Endpoint.Common.Settings;
using Mirea.Api.Endpoint.Configuration.AppConfig;
using Mirea.Api.Endpoint.Configuration.General;
using Mirea.Api.Endpoint.Configuration.General.Validators;
using Mirea.Api.Endpoint.Middleware;
using Mirea.Api.Security.Services;
using System;
using System.IO;
@ -39,9 +36,9 @@ public class Program
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddConfiguration(EnvironmentConfiguration.GetEnvironment());
builder.Configuration.AddJsonFile(GeneralConfig.FilePath, optional: true, reloadOnChange: true);
builder.Configuration.AddJsonFile(PathBuilder.Combine(GeneralConfig.FilePath), optional: true, reloadOnChange: true);
builder.Services.Configure<GeneralConfig>(builder.Configuration);
builder.Configuration.AddJsonFile(Admin.FilePath, optional: true, reloadOnChange: true);
builder.Configuration.AddJsonFile(PathBuilder.Combine(Admin.PathToSave), optional: true, reloadOnChange: true);
builder.Services.Configure<Admin>(builder.Configuration);
builder.Host.AddCustomSerilog();
@ -67,26 +64,6 @@ public class Program
});
});
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(
int.Parse(builder.Configuration.GetValue<string>("INTERNAL_PORT") ?? "8080"));
});
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
var secretForward = builder.Configuration.Get<GeneralConfig>();
if (string.IsNullOrEmpty(secretForward!.SecretForwardToken))
{
secretForward.SecretForwardToken = GeneratorKey.GenerateBase64(18);
secretForward.SaveSetting();
}
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.ForwardedForHeaderName = secretForward.SecretForwardToken + "-X-Forwarded-For";
});
builder.Services.AddCustomApiVersioning();
builder.Services.AddCustomSwagger();
@ -95,10 +72,9 @@ public class Program
var app = builder.Build();
app.UseStaticFiles(UrlHelper.GetSubPath.TrimEnd('/'));
app.UseStaticFiles();
app.UseCors("AllowAll");
app.UseCustomSerilog();
app.UseForwardedHeaders();
using (var scope = app.Services.CreateScope())
{

File diff suppressed because one or more lines are too long

View File

@ -5,15 +5,15 @@
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<Company>Winsomnia</Company>
<Version>1.0.0-rc0</Version>
<AssemblyVersion>1.0.2.0</AssemblyVersion>
<FileVersion>1.0.2.0</FileVersion>
<Version>1.0.0-a0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyName>Mirea.Api.Security</AssemblyName>
<RootNamespace>$(AssemblyName)</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
</ItemGroup>

View File

@ -5,9 +5,9 @@
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<Company>Winsomnia</Company>
<Version>1.0.0-rc0</Version>
<AssemblyVersion>1.0.2.0</AssemblyVersion>
<FileVersion>1.0.2.0</FileVersion>
<Version>1.0.0-a0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyName>Mirea.Api.DataAccess.Application</AssemblyName>
<RootNamespace>$(AssemblyName)</RootNamespace>
</PropertyGroup>

View File

@ -5,9 +5,9 @@
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<Company>Winsomnia</Company>
<Version>1.0.0</Version>
<AssemblyVersion>1.0.3.0</AssemblyVersion>
<FileVersion>1.0.3.0</FileVersion>
<Version>1.0.0-a0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyName>Mirea.Api.DataAccess.Domain</AssemblyName>
<RootNamespace>$(AssemblyName)</RootNamespace>
</PropertyGroup>

View File

@ -5,9 +5,9 @@
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<Company>Winsomnia</Company>
<Version>1.0.0-rc0</Version>
<AssemblyVersion>1.0.2.0</AssemblyVersion>
<FileVersion>1.0.2.0</FileVersion>
<Version>1.0.0-a0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyName>Mirea.Api.DataAccess.Persistence</AssemblyName>
<RootNamespace>$(AssemblyName)</RootNamespace>
</PropertyGroup>