protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var config  = Context.Items.Get <StormpathConfiguration>(OwinKeys.StormpathConfiguration);
            var scheme  = Context.Items.Get <string>(OwinKeys.StormpathUserScheme);
            var account = Context.Items.Get <IAccount>(OwinKeys.StormpathUser);

            var deleteCookieAction = new Action <WebCookieConfiguration>(cookie =>
            {
                Response.Cookies.Delete(cookie.Name, new CookieOptions()
                {
                    Domain = cookie.Domain,
                    Path   = cookie.Path
                });
            });
            var setStatusCodeAction = new Action <int>(code => Response.StatusCode = code);
            var redirectAction      = new Action <string>(location => Response.Redirect(location));

            this.handler = new RouteProtector(
                config.Web,
                deleteCookieAction,
                setStatusCodeAction,
                redirectAction,
                this.stormpathLogger);

            if (!this.handler.IsAuthenticated(scheme, Options.AuthenticationScheme, account))
            {
                return(Task.FromResult(AuthenticateResult.Fail("Request is not properly authenticated.")));
            }

            var principal = AccountIdentityTransformer.CreatePrincipal(account, scheme);
            var ticket    = new AuthenticationTicket(principal, new AuthenticationProperties(), scheme);

            return(Task.FromResult(AuthenticateResult.Success(ticket)));
        }
        private static void GetUserIdentity(HttpContext httpContext, ILogger logger)
        {
            var config  = httpContext.Items.Get <StormpathConfiguration>(OwinKeys.StormpathConfiguration);
            var scheme  = httpContext.Items.Get <string>(OwinKeys.StormpathUserScheme);
            var account = httpContext.Items.Get <IAccount>(OwinKeys.StormpathUser);

            var handler = new RouteProtector(config.Web, null, null, null, logger);
            var isAuthenticatedRequest = handler.IsAuthenticated(scheme, scheme, account);

            if (isAuthenticatedRequest)
            {
                httpContext.User = AccountIdentityTransformer.CreatePrincipal(account, scheme);
            }

            if (httpContext.User == null)
            {
                httpContext.User = new GenericPrincipal(new GenericIdentity(""), new string[0]);
            }
        }
        private static void GetUserIdentity(HttpContext httpContext, ILogger logger)
        {
            var client = httpContext.Items.Get<IClient>(OwinKeys.StormpathClient);
            var config = httpContext.Items.Get<StormpathConfiguration>(OwinKeys.StormpathConfiguration);
            var scheme = httpContext.Items.Get<string>(OwinKeys.StormpathUserScheme);
            var account = httpContext.Items.Get<IAccount>(OwinKeys.StormpathUser);

            var handler = new RouteProtector(client, config, null, null, null, null, logger);
            var isAuthenticatedRequest = handler.IsAuthenticated(scheme, scheme, account);

            if (isAuthenticatedRequest)
            {
                httpContext.User = AccountIdentityTransformer.CreatePrincipal(account, scheme);
            }

            if (httpContext.User == null)
            {
                httpContext.User = new GenericPrincipal(new GenericIdentity(""), new string[0]);
            }
        }
        public void Configuration(IAppBuilder app)
        {
            var logger = new ConsoleLogger(LogLevel.Trace);

            // Initialize the Stormpath middleware
            var stormpath = StormpathMiddleware.Create(new StormpathOwinOptions()
            {
                LibraryUserAgent       = "nowin/0.22.2",
                ViewRenderer           = new PrecompiledViewRenderer(logger),
                Logger                 = logger,
                PreRegistrationHandler = (ctx, ct) =>
                {
                    ctx.Account.CustomData["source"] = "Nowin";
                    return(Task.FromResult(true));
                },
                PostRegistrationHandler = async(ctx, ct) =>
                {
                    var customData = await ctx.Account.GetCustomDataAsync(ct);
                },
                PreLoginHandler = (ctx, ct) =>
                {
                    return(Task.FromResult(true));
                },
                PostLoginHandler = async(ctx, ct) =>
                {
                    var customData = await ctx.Account.GetCustomDataAsync(ct);
                }
            });

            // Insert it into the OWIN pipeline
            app.Use(stormpath);

            // Add a sample middleware that responds to GET /
            app.Use(new Func <AppFunc, AppFunc>(next => (async env =>
            {
                if (env["owin.RequestPath"] as string != "/")
                {
                    await next.Invoke(env);
                    return;
                }
                using (var writer = new StreamWriter(env["owin.ResponseBody"] as Stream))
                {
                    await writer.WriteAsync("<h1>Hello from OWIN!</h1>");

                    if (!env.ContainsKey(OwinKeys.StormpathUser))
                    {
                        await writer.WriteAsync("<a href=\"/login\">Log in</a> or <a href=\"/register\">Register</a>");
                    }
                    else
                    {
                        var user = env[OwinKeys.StormpathUser] as IAccount;

                        await writer.WriteAsync($"<p>Logged in as {user?.FullName} ({user?.Email})</p>");

                        await writer.WriteAsync(@"
<form action=""/logout"" method=""post"" id=""logout_form"">
  <a onclick=""document.getElementById('logout_form').submit();"" style=""cursor: pointer;"">
    Log Out
  </a>
</form>");
                    }

                    await writer.FlushAsync();
                }
            })));

            // Add a "protected" route
            app.Use(new Func <AppFunc, AppFunc>(next => (async env =>
            {
                if (env["owin.RequestPath"] as string != "/protected")
                {
                    await next.Invoke(env);
                    return;
                }

                if (!env.ContainsKey(OwinKeys.StormpathUser))
                {
                    var deleteCookieAction =
                        new Action <Configuration.Abstractions.Immutable.WebCookieConfiguration>(_ => { }); // TODO
                    var setStatusCodeAction = new Action <int>(code => env["owin.ResponseStatusCode"] = code);
                    var setHeaderAction = new Action <string, string>((name, value) =>
                                                                      (env["owin.ResponseHeaders"] as IDictionary <string, string[]>).SetString(name, value));
                    var redirectAction = new Action <string>(location =>
                    {
                        setStatusCodeAction(302);
                        setHeaderAction("Location", location);
                    });
                    var routeProtector = new RouteProtector(
                        stormpath.GetClient(),
                        stormpath.Configuration,
                        deleteCookieAction,
                        setStatusCodeAction,
                        setHeaderAction,
                        redirectAction,
                        null);
                    routeProtector.OnUnauthorized("text/html", "/protected");
                }
                else
                {
                    using (var writer = new StreamWriter(env["owin.ResponseBody"] as Stream))
                    {
                        await writer.WriteAsync("<p>Zomg secret!</p>");
                        await writer.FlushAsync();
                    }
                }
            })));
        }