using System; using System.Web; using Microsoft.Owin; using Microsoft.Owin.Security; using Umbraco.Core; using Umbraco.Web.Models.Identity; using Umbraco.Web.Security; namespace Umbraco.Web { public static class OwinExtensions { /// /// Gets the for the Umbraco back office cookie /// /// /// internal static ISecureDataFormat GetUmbracoAuthTicketDataProtector(this IOwinContext owinContext) { var found = owinContext.Get(); return found?.Protector; } public static string GetCurrentRequestIpAddress(this IOwinContext owinContext) { if (owinContext == null) { return "Unknown, owinContext is null"; } if (owinContext.Request == null) { return "Unknown, owinContext.Request is null"; } var httpContext = owinContext.TryGetHttpContext(); if (httpContext == false) { return "Unknown, cannot resolve HttpContext from owinContext"; } return httpContext.Result.GetCurrentRequestIpAddress(); } /// /// Nasty little hack to get HttpContextBase from an owin context /// /// /// internal static Attempt TryGetHttpContext(this IOwinContext owinContext) { var ctx = owinContext.Get(typeof(HttpContextBase).FullName); return ctx == null ? Attempt.Fail() : Attempt.Succeed(ctx); } /// /// Gets the back office sign in manager out of OWIN /// /// /// public static BackOfficeSignInManager GetBackOfficeSignInManager(this IOwinContext owinContext) { return owinContext.Get() ?? throw new NullReferenceException($"Could not resolve an instance of {typeof (BackOfficeSignInManager)} from the {typeof(IOwinContext)}."); } /// /// Gets the back office user manager out of OWIN /// /// /// /// /// This is required because to extract the user manager we need to user a custom service since owin only deals in generics and /// developers could register their own user manager types /// public static BackOfficeUserManager GetBackOfficeUserManager(this IOwinContext owinContext) { var marker = owinContext.Get(BackOfficeUserManager.OwinMarkerKey) ?? throw new NullReferenceException($"No {typeof (IBackOfficeUserManagerMarker)}, i.e. no Umbraco back-office, has been registered with Owin."); return marker.GetManager(owinContext) ?? throw new NullReferenceException($"Could not resolve an instance of {typeof (BackOfficeUserManager)} from the {typeof (IOwinContext)}."); } /// /// Adapted from Microsoft.AspNet.Identity.Owin.OwinContextExtensions /// public static T Get(this IOwinContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); return context.Get(GetKey(typeof(T))); } public static IOwinContext Set(this IOwinContext context, T value) { if (context == null) throw new ArgumentNullException(nameof(context)); return context.Set(GetKey(typeof(T)), value); } private static string GetKey(Type t) { return "AspNet.Identity.Owin:" + t.AssemblyQualifiedName; } } }