remove IExternalUrl

This commit is contained in:
NicolasDorier 2017-09-27 15:16:30 +09:00
parent 8dfe3c179b
commit d499ef0977
12 changed files with 36 additions and 135 deletions

View File

@ -55,7 +55,6 @@ namespace BTCPayServer.Configuration
Explorer = conf.GetOrDefault<Uri>("explorer.url", networkInfo.DefaultExplorerUrl);
CookieFile = conf.GetOrDefault<string>("explorer.cookiefile", networkInfo.DefaultExplorerCookieFile);
ExternalUrl = conf.GetOrDefault<Uri>("externalurl", null);
RequireHttps = conf.GetOrDefault<bool>("requirehttps", false);
}
@ -63,10 +62,5 @@ namespace BTCPayServer.Configuration
{
get; set;
}
public Uri ExternalUrl
{
get; set;
}
}
}

View File

@ -27,7 +27,6 @@ namespace BTCPayServer.Configuration
app.Option("--testnet | -testnet", $"Use testnet", CommandOptionType.BoolValue);
app.Option("--regtest | -regtest", $"Use regtest", CommandOptionType.BoolValue);
app.Option("--requirehttps", $"Will redirect to https version of the website (default: false)", CommandOptionType.BoolValue);
app.Option("--externalurl", $"The external url of the website", CommandOptionType.SingleValue);
app.Option("--explorerurl", $"Url of the NBxplorer (default: : Default setting of NBXplorer for the network)", CommandOptionType.SingleValue);
app.Option("--explorercookiefile", $"Path to the cookie file (default: Default setting of NBXplorer for the network)", CommandOptionType.SingleValue);
@ -78,7 +77,6 @@ namespace BTCPayServer.Configuration
builder.AppendLine("#requirehttps=0");
builder.AppendLine("#port=" + network.DefaultPort);
builder.AppendLine("#bind=127.0.0.1");
builder.AppendLine("#externalurl=http://127.0.0.1/");
builder.AppendLine();
builder.AppendLine("### NBXplorer settings ###");
builder.AppendLine("#explorer.url=" + network.DefaultExplorerUrl.AbsoluteUri);

View File

@ -38,7 +38,7 @@ namespace BTCPayServer.Controllers
if(invoice == null)
throw new BitpayHttpException(404, "Object not found");
var resp = invoice.EntityToDTO(_ExternalUrl);
var resp = invoice.EntityToDTO();
return new DataWrapper<InvoiceResponse>(resp);
}
@ -73,7 +73,7 @@ namespace BTCPayServer.Controllers
var entities = (await _InvoiceRepository.GetInvoices(query))
.Select((o) => o.EntityToDTO(_ExternalUrl)).ToArray();
.Select((o) => o.EntityToDTO()).ToArray();
return DataWrapper.Create(entities);
}

View File

@ -23,7 +23,7 @@ namespace BTCPayServer.Controllers
if(invoice == null || invoice.IsExpired())
return NotFound();
var dto = invoice.EntityToDTO(_ExternalUrl);
var dto = invoice.EntityToDTO();
PaymentRequest request = new PaymentRequest
{
DetailsVersion = 1
@ -34,7 +34,7 @@ namespace BTCPayServer.Controllers
request.Details.Outputs.Add(new PaymentOutput() { Amount = dto.BTCDue, Script = BitcoinAddress.Create(dto.BitcoinAddress, _Network).ScriptPubKey });
request.Details.MerchantData = Encoding.UTF8.GetBytes(invoice.Id);
request.Details.Time = DateTimeOffset.UtcNow;
request.Details.PaymentUrl = new Uri(_ExternalUrl.GetAbsolute($"i/{invoice.Id}"), UriKind.Absolute);
request.Details.PaymentUrl = new Uri(invoice.ServerUrl.WithTrailingSlash() + ($"i/{invoice.Id}"), UriKind.Absolute);
var store = await _StoreRepository.FindStore(invoice.StoreId);
if(store == null)

View File

@ -29,7 +29,7 @@ namespace BTCPayServer.Controllers
if(invoice == null)
return NotFound();
var store = await _StoreRepository.FindStore(invoice.StoreId);
var dto = invoice.EntityToDTO(_ExternalUrl);
var dto = invoice.EntityToDTO();
var model = new PaymentModel()
{

View File

@ -33,6 +33,7 @@ using BTCPayServer.Servcices.Invoices;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Wallets;
using BTCPayServer.Validations;
using Microsoft.AspNetCore.Mvc.Routing;
namespace BTCPayServer.Controllers
{
@ -40,7 +41,6 @@ namespace BTCPayServer.Controllers
{
TokenRepository _TokenRepository;
InvoiceRepository _InvoiceRepository;
IExternalUrlProvider _ExternalUrl;
BTCPayWallet _Wallet;
IRateProvider _RateProvider;
private InvoiceWatcher _Watcher;
@ -55,7 +55,6 @@ namespace BTCPayServer.Controllers
UserManager<ApplicationUser> userManager,
TokenRepository tokenRepository,
BTCPayWallet wallet,
IExternalUrlProvider externalUrl,
IRateProvider rateProvider,
StoreRepository storeRepository,
InvoiceWatcher watcher,
@ -65,7 +64,6 @@ namespace BTCPayServer.Controllers
_Network = network ?? throw new ArgumentNullException(nameof(network));
_TokenRepository = tokenRepository ?? throw new ArgumentNullException(nameof(tokenRepository));
_InvoiceRepository = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository));
_ExternalUrl = externalUrl;
_Wallet = wallet ?? throw new ArgumentNullException(nameof(wallet));
_RateProvider = rateProvider ?? throw new ArgumentNullException(nameof(rateProvider));
_Watcher = watcher ?? throw new ArgumentNullException(nameof(watcher));
@ -86,7 +84,7 @@ namespace BTCPayServer.Controllers
notificationUri = null;
EmailAddressAttribute emailValidator = new EmailAddressAttribute();
entity.ExpirationTime = entity.InvoiceTime + TimeSpan.FromMinutes(15.0);
entity.ServerUrl = _ExternalUrl.GetAbsolute("");
entity.ServerUrl = HttpContext.Request.GetAbsoluteRoot();
entity.FullNotifications = invoice.FullNotifications;
entity.NotificationURL = notificationUri?.AbsoluteUri;
entity.BuyerInformation = Map<Invoice, BuyerInformation>(invoice);
@ -103,7 +101,7 @@ namespace BTCPayServer.Controllers
entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity);
await _Wallet.MapAsync(entity.DepositAddress, entity.Id);
await _Watcher.WatchAsync(entity.Id);
var resp = entity.EntityToDTO(_ExternalUrl);
var resp = entity.EntityToDTO();
return new DataWrapper<InvoiceResponse>(resp) { Facade = "pos/invoice" };
}

View File

@ -35,7 +35,6 @@ namespace BTCPayServer.Controllers
TokenRepository _TokenRepository;
private readonly BTCPayWallet _Wallet;
IHostingEnvironment _Env;
private readonly IExternalUrlProvider _UrlProvider;
StoreRepository _StoreRepository;
@ -50,8 +49,7 @@ namespace BTCPayServer.Controllers
TokenRepository tokenRepository,
BTCPayWallet wallet,
StoreRepository storeRepository,
IHostingEnvironment env,
IExternalUrlProvider urlProvider)
IHostingEnvironment env)
{
_userManager = userManager;
_signInManager = signInManager;
@ -61,7 +59,6 @@ namespace BTCPayServer.Controllers
_TokenRepository = tokenRepository;
_Wallet = wallet;
_Env = env;
_UrlProvider = urlProvider;
_StoreRepository = storeRepository;
}

View File

@ -1,5 +1,6 @@
using BTCPayServer.Authentication;
using BTCPayServer.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@ -11,6 +12,21 @@ namespace BTCPayServer
{
public static class Extensions
{
public static string WithTrailingSlash(this string str)
{
if(str.EndsWith("/"))
return str;
return str + "/";
}
public static string GetAbsoluteRoot(this HttpRequest request)
{
return string.Concat(
request.Scheme,
"://",
request.Host.ToUriComponent(),
request.PathBase.ToUriComponent());
}
public static IServiceCollection ConfigureBTCPayServer(this IServiceCollection services, IConfiguration conf)
{

View File

@ -1,96 +0,0 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Http.Extensions;
namespace BTCPayServer
{
public interface IExternalUrlProvider
{
string GetEncodedUrl();
string GetAbsolute(string path);
}
public class DefaultExternalUrlProvider : IExternalUrlProvider
{
IHttpContextAccessor _ContextAccessor;
public DefaultExternalUrlProvider(IHttpContextAccessor contextAccessor)
{
if(contextAccessor == null)
throw new ArgumentNullException(nameof(contextAccessor));
_ContextAccessor = contextAccessor;
}
public string GetAbsolute(string path)
{
var request = _ContextAccessor.HttpContext.Request;
var builder = new UriBuilder()
{
Scheme = request.Scheme,
Host = request.Host.Host,
};
if(request.Host.Port.HasValue)
builder.Port = request.Host.Port.Value;
return builder.Uri.AbsoluteUri + path;
}
public string GetEncodedUrl()
{
var request = _ContextAccessor.HttpContext.Request;
return request.GetEncodedUrl();
}
}
public class FixedExternalUrlProvider : IExternalUrlProvider
{
string _Url;
IHttpContextAccessor _ContextAccessor;
public FixedExternalUrlProvider(Uri url, IHttpContextAccessor contextAccessor)
{
if(url == null)
throw new ArgumentNullException(nameof(url));
_ContextAccessor = contextAccessor;
_Url = url.AbsoluteUri;
}
public string GetAbsolute(string path)
{
var uri = new Uri(_Url, UriKind.Absolute);
var builder = new UriBuilder()
{
Scheme = uri.Scheme,
Host = uri.Host,
};
if(!uri.IsDefaultPort)
builder.Port = uri.Port;
return builder.Uri.AbsoluteUri + path;
}
public string GetEncodedUrl()
{
var req = _ContextAccessor.HttpContext.Request;
return BuildAbsolute(req.Path, req.QueryString);
}
private string BuildAbsolute(PathString path = new PathString(),
QueryString query = new QueryString(),
FragmentString fragment = new FragmentString())
{
var combinedPath = path.HasValue ? path.Value.Substring(1) : "";
var encodedQuery = query.ToString();
var encodedFragment = fragment.ToString();
// PERF: Calculate string length to allocate correct buffer size for StringBuilder.
var length = _Url.Length + combinedPath.Length + encodedQuery.Length + encodedFragment.Length;
return new StringBuilder(length)
.Append(_Url)
.Append(combinedPath)
.Append(encodedQuery)
.Append(encodedFragment)
.ToString();
}
}
}

View File

@ -135,13 +135,6 @@ namespace BTCPayServer.Hosting
services.TryAddSingleton<InvoiceNotificationManager>();
services.TryAddSingleton<IHostedService>(o => o.GetRequiredService<InvoiceWatcher>());
services.TryAddScoped<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IExternalUrlProvider>(o =>
{
var op = o.GetRequiredService<BTCPayServerOptions>();
if(op.ExternalUrl != null)
return new FixedExternalUrlProvider(op.ExternalUrl, o.GetRequiredService<IHttpContextAccessor>());
return new DefaultExternalUrlProvider(o.GetRequiredService<IHttpContextAccessor>());
});
services.TryAddSingleton<IAuthorizationHandler, OwnStoreHandler>();
services.AddTransient<AccessTokenController>();
// Add application services.

View File

@ -18,6 +18,9 @@ using BTCPayServer.Logging;
using Newtonsoft.Json;
using BTCPayServer.Models;
using BTCPayServer.Configuration;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Http.Extensions;
namespace BTCPayServer.Hosting
{
@ -25,10 +28,8 @@ namespace BTCPayServer.Hosting
{
TokenRepository _TokenRepository;
RequestDelegate _Next;
IExternalUrlProvider _ExternalUrl;
public BTCPayMiddleware(RequestDelegate next, TokenRepository tokenRepo, IExternalUrlProvider externalUrl)
public BTCPayMiddleware(RequestDelegate next, TokenRepository tokenRepo)
{
_ExternalUrl = externalUrl ?? throw new ArgumentNullException(nameof(externalUrl));
_TokenRepository = tokenRepo ?? throw new ArgumentNullException(nameof(tokenRepo));
_Next = next ?? throw new ArgumentNullException(nameof(next));
}
@ -53,7 +54,7 @@ namespace BTCPayServer.Hosting
httpContext.Request.Body.Position = 0;
}
var url = _ExternalUrl.GetEncodedUrl();
var url = httpContext.Request.GetEncodedUrl();
try
{
var key = new PubKey(id);

View File

@ -255,9 +255,9 @@ namespace BTCPayServer.Servcices.Invoices
}
public InvoiceResponse EntityToDTO(IExternalUrlProvider urlProvider = null)
public InvoiceResponse EntityToDTO()
{
urlProvider = urlProvider ?? new FixedExternalUrlProvider(new Uri(ServerUrl, UriKind.Absolute), null);
ServerUrl = ServerUrl ?? "";
InvoiceResponse dto = new InvoiceResponse
{
Id = Id,
@ -268,7 +268,7 @@ namespace BTCPayServer.Servcices.Invoices
ExpirationTime = ExpirationTime,
BTCPrice = Money.Coins((decimal)(1.0 / Rate)).ToString(),
Status = Status,
Url = urlProvider.GetAbsolute("invoice?id=" + Id),
Url = ServerUrl.WithTrailingSlash() + "invoice?id=" + Id,
Currency = ProductInformation.Currency,
Flags = new Flags() { Refundable = Refundable }
};
@ -280,9 +280,9 @@ namespace BTCPayServer.Servcices.Invoices
};
dto.PaymentUrls = new InvoicePaymentUrls()
{
BIP72 = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}&r={urlProvider.GetAbsolute($"i/{Id}")}",
BIP72b = $"bitcoin:?r={urlProvider.GetAbsolute($"i/{Id}")}",
BIP73 = urlProvider.GetAbsolute($"i/{Id}"),
BIP72 = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}&r={ServerUrl.WithTrailingSlash() + ($"i/{Id}")}",
BIP72b = $"bitcoin:?r={ServerUrl.WithTrailingSlash() + ($"i/{Id}")}",
BIP73 = ServerUrl.WithTrailingSlash() + ($"i/{Id}"),
BIP21 = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}",
};
dto.BitcoinAddress = DepositAddress.ToString();