using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Security.Claims; using System.Threading.Tasks; using zero.Core.Api; using zero.Core.Entities; using zero.Core.Identity; using zero.Core.Options; using zero.Core.Routing; namespace zero.Core { public class ZeroContext : IZeroContext { /// public IApplication App { get; protected set; } /// public string AppId { get; protected set; } /// public ClaimsPrincipal BackofficeUser { get; protected set; } /// public ClaimsIdentity BackofficeIdentity { get; protected set; } /// public bool IsBackofficeRequest { get; protected set; } /// public IZeroOptions Options { get; protected set; } /// public IRoute Route { get; private set; } /// public IResolvedRoute ResolvedRoute { get; private set; } protected IApplicationContext AppContext { get; private set; } protected ILogger Logger { get; private set; } private bool _resolved = false; public ZeroContext(IZeroOptions options, IApplicationContext appContext, ILogger logger) { Options = options; AppContext = appContext; Logger = logger; } /// public async virtual Task Resolve(HttpContext context) { if (_resolved || context?.Request is null) { return; } _resolved = true; AuthenticateResult authResult = await context.AuthenticateAsync(Constants.Auth.BackofficeScheme); if (authResult?.Principal is not null) { BackofficeUser = authResult.Principal; if (BackofficeUserIdentity.TryGet(authResult.Principal, out BackofficeUserIdentity identity)) { BackofficeIdentity = identity; } } else { BackofficeUser = new ClaimsPrincipal(); } App = await AppContext.Resolve(context, BackofficeUser); AppId = App.Id; IsBackofficeRequest = AppContext.IsBackofficeRequest(context); if (IsBackofficeRequest is false && context.Request.RouteValues.TryGetValue("zero.route", out object route)) { ResolvedRoute = (IResolvedRoute)route; Route = ResolvedRoute.Route; } } } public interface IZeroContext { /// /// Currently loaded application /// IApplication App { get; } /// /// Current loaded application Id /// string AppId { get; } /// /// Resolved backoffice user principal /// ClaimsPrincipal BackofficeUser { get; } /// /// Resolved backoffice user identity /// ClaimsIdentity BackofficeIdentity { get; } /// /// Whether the current request is a backoffice request or not /// bool IsBackofficeRequest { get; } /// /// Global zero options /// IZeroOptions Options { get; } /// /// Matching (frontend) path route /// IRoute Route { get; } /// /// Matching (frontend) resolved route /// IResolvedRoute ResolvedRoute { get; } /// /// Resolves the current application (for backoffice + frontend requests) and /// the currently active backoffice user, as users are not signed in with the default scheme and do therefore not populate HttpContext.User /// Task Resolve(HttpContext context); } }