forked from xiongyuxing/tiku-backend.net
57 lines
1.7 KiB
C#
57 lines
1.7 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Tiku.Application.Security;
|
|
|
|
namespace Tiku.Api.Options;
|
|
|
|
public static class OptionsValidation
|
|
{
|
|
public const string DevelopmentSigningKey = "development-only-tiku-signing-key-change-before-production";
|
|
|
|
public static string ResolveDatabaseConnectionString(
|
|
IConfiguration configuration,
|
|
bool isDevelopment)
|
|
{
|
|
var connectionString =
|
|
configuration.GetConnectionString("Database") ??
|
|
configuration["DATABASE_URL"];
|
|
if (!string.IsNullOrWhiteSpace(connectionString))
|
|
{
|
|
return connectionString;
|
|
}
|
|
|
|
if (isDevelopment)
|
|
{
|
|
return $"Host=localhost;Database=tiku;Username={Environment.UserName}";
|
|
}
|
|
|
|
throw new InvalidOperationException(
|
|
"Database connection is required outside Development. Configure ConnectionStrings:Database or DATABASE_URL.");
|
|
}
|
|
|
|
public static bool BeValidJwtOptions(JwtOptions options, bool isProduction)
|
|
{
|
|
return !isProduction ||
|
|
!string.Equals(
|
|
options.SigningKey,
|
|
DevelopmentSigningKey,
|
|
StringComparison.Ordinal);
|
|
}
|
|
|
|
public static bool BeValidCorsOptions(CorsOptions options)
|
|
{
|
|
if (options.AllowCredentials && options.AllowedOrigins.Length == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return options.AllowedOrigins.All(IsHttpOrigin);
|
|
}
|
|
|
|
private static bool IsHttpOrigin(string origin)
|
|
{
|
|
return Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
|
(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) &&
|
|
string.IsNullOrEmpty(uri.PathAndQuery.Trim('/'));
|
|
}
|
|
}
|