using System;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Umbraco.Core;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Security;
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)}.");
}
}
}