Compare commits

..

No commits in common. "573c12fe30426b742d17bf6ae320e31d5b73aadc" and "c778f7e46bc83405703b05e3a5af869e752ddf86" have entirely different histories.

17 changed files with 69 additions and 207 deletions

View file

@ -12,10 +12,8 @@
"DOTNET",
"ecdsa",
"envsubst",
"Hsts",
"Newtonsoft",
"Npgsql",
"PKCE",
"postit",
"pschneider",
"SLNDIR",

View file

@ -25,7 +25,7 @@ public partial class App : Application
/// <c>DataValidationErrors.SetErrors</c>.
/// </summary>
public IServiceProvider? Services { get; private set; }
private MainWindow window;
public App()
{
}
@ -137,7 +137,7 @@ public partial class App : Application
var homePage = provider.GetRequiredService<HomePage>();
homePage.DataContext = provider.GetRequiredService<HomePageViewModel>();
window = new MainWindow();
var window = new MainWindow();
window.SessionBanner.DataContext = sessionStatus;
// Build the navigation stack from scratch: HomePage is the
@ -165,7 +165,7 @@ public partial class App : Application
sessionStatus.LoginSucceeded += () =>
{
var w = (MainWindow)((IClassicDesktopStyleApplicationLifetime)ApplicationLifetime!).MainWindow!;
_ = PushMainPageAsync();
_ = PushMainPageAsync(provider, w);
};
// When the user clicks the "Paramètres" button on the
@ -196,7 +196,7 @@ public partial class App : Application
_ = w.NavRoot.PushAsync(settingsPage);
};
window.Opened += async (_, _) => await BootAsync(provider, api);
window.Opened += async (_, _) => await BootAsync(provider, api, window);
}
else if (ApplicationLifetime is ISingleViewApplicationLifetime singleView)
{
@ -223,14 +223,15 @@ public partial class App : Application
/// </summary>
private static async Task BootAsync(
IServiceProvider provider,
YavscApiClient api)
YavscApiClient api,
MainWindow window)
{
var refreshed = await api.TrySilentLoginAsync().ConfigureAwait(true);
var sessionStatus = provider.GetRequiredService<SessionStatusViewModel>();
sessionStatus.Refresh();
if (!refreshed) return;
await PushMainPageAsync().ConfigureAwait(true);
await PushMainPageAsync(provider, window).ConfigureAwait(true);
}
/// <summary>
@ -240,13 +241,12 @@ public partial class App : Application
/// (interactive login from the banner). Pulled out as a helper so
/// the two callers can't drift apart.
/// </summary>
public static async Task PushMainPageAsync()
private static async Task PushMainPageAsync(IServiceProvider provider, MainWindow window)
{
var app = (App)Current;
var mainVm = app.Services.GetRequiredService<MainPageViewModel>();
var mainPage = app.Services.GetRequiredService<MainPage>();
var mainVm = provider.GetRequiredService<MainPageViewModel>();
var mainPage = provider.GetRequiredService<MainPage>();
mainPage.DataContext = mainVm;
await app.window.FindControl<NavigationPage>("NavRoot").PushAsync(mainPage).ConfigureAwait(true);
await window.NavRoot.PushAsync(mainPage).ConfigureAwait(true);
}
private bool TryHandOffCustomSchemeUrl()

View file

@ -1,7 +1,6 @@
using CommunityToolkit.Mvvm.Input;
using PostIt;
using PostIt.Services;
namespace PostIt.ViewModels;
using PostIt.ViewModels;
public class HomePageViewModel : ViewModelBase
{
@ -23,7 +22,7 @@ public class HomePageViewModel : ViewModelBase
Api = api;
Settings = settings;
}
public RelayCommand OpenBlogs { get; set; } = new RelayCommand(() => App.PushMainPageAsync());
/// <summary>
/// Avalonia designer constructor. Builds a self-contained VM
/// with a freshly-constructed Settings so the XAML preview can

View file

@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
@ -179,20 +178,10 @@ public partial class Settings : ViewModelBase
RedirectUri = Authentication.RedirectUri,
Scope = string.Join(' ', MergeScopes(this.Authentication.Scopes)),
TokenClientCredentialStyle = IdentityModel.Client.ClientCredentialStyle.PostBody,
PostLogoutRedirectUri = Authentication.Authority,
PostLogoutRedirectUri = "https//yavsc.pschneider.fr",
// PKCE is enabled by default when no client_secret is provided.
};
if (IsDevelopmentEnvironment())
{
// Dev only: allow local/self-signed TLS for discovery/token
// endpoints when the machine does not trust a custom root.
options.BackchannelHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
}
if (browser is not null)
options.Browser = browser;
@ -242,14 +231,6 @@ public partial class Settings : ViewModelBase
}
}
private static bool IsDevelopmentEnvironment()
{
return string.Equals(
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
"Development",
StringComparison.OrdinalIgnoreCase);
}
internal void Load()
{
if (Loaded) return;

View file

@ -1,12 +1,7 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
x:Class="PostIt.Views.HomePage"
x:DataType="vm:HomePageViewModel"
Header="Home">
<Design.DataContext>
<vm:HomePageViewModel />
</Design.DataContext>
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center"
Spacing="12">
@ -14,8 +9,5 @@
FontSize="22"
FontWeight="SemiBold"
HorizontalAlignment="Center"/>
<Button Content="Open Blog Interface"
Command="{Binding OpenBlogs}"
HorizontalAlignment="Center"/>
</StackPanel>
</ContentPage>

View file

View file

@ -27,6 +27,7 @@
<StackPanel Grid.Row="0" Spacing="12"
HorizontalAlignment="Stretch"
VerticalAlignment="Top">
<TextBlock Text="PostIt Blog API Interface" FontSize="20" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Command="{Binding LoadPosts}" Content="Load posts" />
@ -92,4 +93,4 @@
</Grid>
</Border>
</Grid>
</ContentPage>
</ContentPage>

View file

@ -20,7 +20,7 @@
-->
<DockPanel LastChildFill="True">
<views:SessionStatusBanner x:Name="SessionBanner"
DockPanel.Dock="Bottom"/>
DockPanel.Dock="Top"/>
<NavigationPage x:Name="NavRoot"/>
</DockPanel>

View file

@ -791,12 +791,12 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
{
if (userId == null || code == null)
{
return this.ErrorView<AccountController>("Error: userId or code is null.");
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return this.ErrorView<AccountController>("Error: user not found.");
return View("Error");
}
IdentityResult result = null;
try
@ -819,12 +819,12 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
{
if (userId == null || code == null)
{
return this.ErrorView<AccountController>("Error: userId or code is null.");
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return this.ErrorView<AccountController>("Error: user not found.");
return View("Error");
}
bool result = false;
try
@ -837,7 +837,7 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
_logger.LogError(ex.StackTrace);
_logger.LogError(ex.Message);
}
return result ? View("EmailConfirmed") : this.ErrorView<AccountController>("Error confirming two factor token.");
return View(result ? "EmailConfirmed" : "Error");
}
//

View file

@ -1,5 +1,6 @@
using System.Security.Claims;
using System.IO;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
@ -489,7 +490,12 @@ namespace Yavsc.Controllers
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
@ -516,7 +522,15 @@ namespace Yavsc.Controllers
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });

View file

@ -16,7 +16,6 @@ using System.Collections.Generic;
using System;
using Yavsc;
using Yavsc.Extensions;
using Yavsc.Models;
namespace IdentityServerHost.Quickstart.UI
{
@ -54,10 +53,9 @@ namespace IdentityServerHost.Quickstart.UI
{
return View("Index", vm);
}
return this.ErrorView<ConsentController>("No consent request matching request: " + returnUrl);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
@ -90,8 +88,8 @@ namespace IdentityServerHost.Quickstart.UI
{
return View("Index", result.ViewModel);
}
return this.ErrorView<ConsentController>($"ReturnUrl: {model}, result: {result}" );
return View("Error");
}
/*****************************************/
@ -172,6 +170,11 @@ namespace IdentityServerHost.Quickstart.UI
{
return CreateConsentViewModel(model, returnUrl, request);
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
@ -196,7 +199,7 @@ namespace IdentityServerHost.Quickstart.UI
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
var apiScopes = new List<ScopeViewModel>();
foreach (var parsedScope in request.ValidatedResources.ParsedScopes)
foreach(var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)

View file

@ -16,7 +16,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Models.Access;
namespace Yavsc.Controllers
@ -50,7 +49,7 @@ namespace Yavsc.Controllers
if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture");
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return this.ErrorView<DeviceController>($"ViewModel is null! userCodeParamName: {userCodeParamName}, userCode: {userCode}" );;
if (vm == null) return View("Error");
vm.ConfirmUserCode = true;
return View("UserCodeConfirmation", vm);
@ -61,7 +60,7 @@ namespace Yavsc.Controllers
public async Task<IActionResult> UserCodeCapture(string userCode)
{
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return this.ErrorView<DeviceController>($"UserCodeCapture: ViewModel is null! userCode: {userCode}" );
if (vm == null) return View("Error");
return View("UserCodeConfirmation", vm);
}
@ -73,20 +72,7 @@ namespace Yavsc.Controllers
if (model == null) throw new ArgumentNullException(nameof(model));
var result = await ProcessConsent(model);
if (result.HasValidationError)
{
if (HttpContext.RequestServices.GetRequiredService<IHostEnvironment>().IsDevelopment())
{
throw new InvalidOperationException("Device Authorization Input validation error: " + result.ValidationError);
}
return View("Error",
new ErrorViewModel {
RequestId = HttpContext.TraceIdentifier,
Description = "Device Authorization Input validation error: " + result.ValidationError
}
);
}
if (result.HasValidationError) return View("Error");
return View("Success");
}

View file

@ -15,24 +15,18 @@ namespace Yavsc.Controllers
public class HomeController : Controller
{
readonly ApplicationDbContext _dbContext;
readonly ILogger<HomeController> _logger;
private readonly bool _isDevelopment;
readonly IHtmlLocalizer _localizer;
private SiteSettings siteSettings;
public HomeController(ILogger<HomeController> logger,
IHtmlLocalizer<HomeController> localizer,
ApplicationDbContext context,
IOptions<SiteSettings> settingsOptions,
IWebHostEnvironment env
)
IOptions<SiteSettings> settingsOptions)
{
_localizer = localizer;
_dbContext = context;
siteSettings = settingsOptions.Value;
_logger = logger;
_isDevelopment = env.IsDevelopment();
}
public async Task<IActionResult> Index(string id)
@ -105,44 +99,18 @@ namespace Yavsc.Controllers
public IActionResult Error()
{
if (_isDevelopment)
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
if (feature == null) return View();
var errorType = feature?.Error;
if (errorType == null) return View();
if (errorType is NotSupportedException notSupported)
{
_logger.LogInformation(
"Home/Error requested in Development. This endpoint is disabled because DeveloperExceptionPage should handle unhandled exceptions.");
return NotFound(
"In Development, /Home/Error is disabled. Unhandled exceptions are rendered by DeveloperExceptionPage.");
return View(new ErrorViewModel {
Description = notSupported.Message,
RequestId = this.HttpContext.TraceIdentifier
});
}
var errorViewModel = new ErrorViewModel
{
RequestId = HttpContext.TraceIdentifier
};
var exceptionHandlerPathFeature =
HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature is null)
{
_logger.LogWarning(
"Home/Error called without IExceptionHandlerPathFeature in non-development environment.");
return View("~/Views/Shared/Error.cshtml", errorViewModel);
}
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
errorViewModel.Description = "The file was not found.";
}
if (exceptionHandlerPathFeature?.Path == "/")
{
errorViewModel.Description ??= string.Empty;
errorViewModel.Description += " Page: Home.";
}
return View("~/Views/Shared/Error.cshtml", errorViewModel);
return View("~/Views/Shared/Error.cshtml", feature?.Error);
}
public IActionResult Status(int id)
{

View file

@ -967,12 +967,12 @@ public static class HostingExtensions
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
await app.MigrateDatabaseAsync();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
logger.LogInformation("⨝ Running in production mode. Ensure the database is migrated.");
logger.LogInformation("Running in production mode. Ensure the database is migrated.");
await app.MigrateDatabaseAsync();
}

View file

@ -1,52 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
public static class ErrorViewHelpers
{
public static IActionResult ErrorView<T>(this Controller controller, string message)
{
var logger = controller.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>()
.CreateLogger<T>();
logger.LogError(message);
Dictionary<string, string> dictionary = new Dictionary<string, string>();
if (!controller.ModelState.IsValid)
{
foreach (var modelState in controller.ModelState.Values)
{
foreach (var error in modelState.Errors)
{
logger.LogError("ModelState error: {0}", error.ErrorMessage);
foreach (var key in controller.ModelState.Keys)
{
logger.LogError("ModelState key: {0}", key);
dictionary.Add(key,
string.Join("\n",
controller.ModelState[key].Errors.Select( e => e.ErrorMessage).ToArray()));
}
}
}
}
if (controller.HttpContext.Request.Headers.ContainsKey("Accept")
&& controller.HttpContext.Request.Headers["Accept"].ToString().Contains("application/json"))
{
return controller.Json(new
{
RequestId = controller.HttpContext.TraceIdentifier,
Description = message,
ModelErrors = dictionary
});
}
return controller.View("Error",
new ErrorViewModel
{
RequestId = controller.HttpContext.TraceIdentifier,
Description = message,
ModelErrors = dictionary
}
);
}
}

View file

@ -1,41 +1,14 @@
@using Microsoft.AspNetCore.Hosting
@using Yavsc.Models
@inject IWebHostEnvironment Env
@model object
@model ErrorViewModel
@{
ViewBag.Title = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Env.IsDevelopment())
@if (Model!=null) if (Model.ShowRequestId)
{
<h2 class="text-danger">An unhandled exception occurred while processing your request.</h2>
if (Model is Exception exception)
{
<pre class="text-danger">@exception.ToString()</pre>
}
else if (Model is ErrorViewModel errorViewModel && !string.IsNullOrWhiteSpace(errorViewModel.Description))
{
<pre class="text-danger">@errorViewModel.Description</pre>
}
}
else
{
<h2 class="text-danger">An error occurred while processing your request.</h2>
if (Model is ErrorViewModel errorViewModel)
{
if (errorViewModel.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@errorViewModel.RequestId</code>
</p>
}
if (!string.IsNullOrWhiteSpace(errorViewModel.Description))
{
<p class="text-danger">@errorViewModel.Description</p>
}
}
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

View file

@ -7,5 +7,4 @@ public class ErrorViewModel
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public Dictionary<string, string> ModelErrors { get; set; }
}