private Microsoft.Owin.CookieOptions CreateCookieOptions(bool?persistent, DateTimeOffset?expires = null)
        {
            var path   = context.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();
            var secure =
                identityServerOptions.AuthenticationOptions.CookieOptions.SecureMode == CookieSecureMode.Always ||
                context.Request.Scheme == Uri.UriSchemeHttps;

            var options = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = false,
                Secure   = secure,
                Path     = path
            };

            if (persistent != false)
            {
                if (persistent == true || this.identityServerOptions.AuthenticationOptions.CookieOptions.IsPersistent)
                {
                    if (persistent == true)
                    {
                        expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.RememberMeDuration);
                    }
                    else
                    {
                        expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.ExpireTimeSpan);
                    }
                    options.Expires = expires.Value.UtcDateTime;
                }
            }

            return(options);
        }
        void SetCookie(string value)
        {
            DateTime?expires = null;

            if (String.IsNullOrWhiteSpace(value))
            {
                var existingValue = GetCookie();
                if (existingValue == null)
                {
                    // no need to write cookie to clear if we don't already have one
                    return;
                }

                value   = ".";
                expires = DateTime.Now.AddYears(-1);
            }
            else
            {
                // encode the value
                var bytes = Encoding.UTF8.GetBytes(value);
                value = Base64Url.Encode(bytes);
            }

            var opts = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = true,
                Secure   = Secure,
                Path     = CookiePath,
                Expires  = expires
            };

            this.ctx.Response.Cookies.Append(CookieName, value, opts);
        }
        /// <summary>
        /// Add a new cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public void Append(string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue = options.Expires.HasValue;

            string setCookieValue = string.Concat(
                Uri.EscapeDataString(key),
                "=",
                Uri.EscapeDataString(value ?? string.Empty),
                !domainHasValue ? null : "; domain=",
                !domainHasValue ? null : options.Domain,
                !pathHasValue ? null : "; path=",
                !pathHasValue ? null : options.Path,
                !expiresHasValue ? null : "; expires=",
                !expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ", CultureInfo.InvariantCulture) + "GMT",
                !options.Secure ? null : "; secure",
                !options.HttpOnly ? null : "; HttpOnly");
            Headers.AppendValues("Set-Cookie", setCookieValue);
        }
Example #4
0
        internal void SetValue(string username)
        {
            if (options.AuthenticationOptions.RememberLastUsername)
            {
                var cookieName = options.AuthenticationOptions.CookieOptions.Prefix + LastUsernameCookieName;
                var secure     =
                    options.AuthenticationOptions.CookieOptions.SecureMode == CookieSecureMode.Always ||
                    ctx.Request.Scheme == Uri.UriSchemeHttps;
                var path = ctx.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();

                var cookieOptions = new Microsoft.Owin.CookieOptions
                {
                    HttpOnly = true,
                    Secure   = secure,
                    Path     = path
                };

                if (!String.IsNullOrWhiteSpace(username))
                {
                    var bytes = Encoding.UTF8.GetBytes(username);
                    bytes    = options.DataProtector.Protect(bytes, cookieName);
                    username = Base64Url.Encode(bytes);
                    cookieOptions.Expires = DateTimeHelper.UtcNow.AddYears(1);
                }
                else
                {
                    username = "******";
                    cookieOptions.Expires = DateTimeHelper.UtcNow.AddYears(-1);
                }

                ctx.Response.Cookies.Append(cookieName, username, cookieOptions);
            }
        }
        private Microsoft.Owin.CookieOptions CreateCookieOptions(bool? persistent, DateTimeOffset? expires = null)
        {
            var path = context.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();

            var options = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = false,
                Secure = context.Request.IsSecure,
                Path = path
            };

            if (persistent != false)
            {
                if (persistent == true || this.identityServerOptions.AuthenticationOptions.CookieOptions.IsPersistent)
                {
                    if (persistent == true)
                    {
                        expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.RememberMeDuration);
                    }
                    else
                    {
                        expires = expires ?? DateTimeHelper.UtcNow.Add(this.identityServerOptions.AuthenticationOptions.CookieOptions.ExpireTimeSpan);
                    }
                    options.Expires = expires.Value.UtcDateTime;
                }
            }

            return options;
        }
Example #6
0
        protected override void AddNonceToMessage(OpenIdConnectMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            var properties = new AuthenticationProperties();
            var nonce = Options.ProtocolValidator.GenerateNonce();
            properties.Dictionary.Add(
                NonceProperty, nonce);
            message.Nonce = nonce;

            //computing the hash of nonce and appending it to the cookie name
            string nonceKey = GetNonceKey(nonce);
            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure,
            };
            var nonceId = Convert.ToBase64String(Encoding.UTF8.GetBytes((Options.StateDataFormat.Protect(properties))));
            Response.Cookies.Append(
                nonceKey,
                nonceId,
                cookieOptions);
        }
 /// <summary>
 /// Helper method to convert <see cref="CookieAuthenticationOptions"/> to <see cref="CookieOptions"/>.
 /// </summary>
 /// <param name="cookieOptions">Cookies Authentication middleware options <see cref="CookieAuthenticationOptions"/>.</param>
 /// <param name="expires"> When should the cookie expires</param>
 /// <returns> A new instance of <see cref="CookieOptions"/>.</returns>
 public static CookieOptions ToCookieOptions(this CookieAuthenticationOptions cookieOptions, DateTime expires)
 {
     CookieOptions options = new CookieOptions();
     options.Domain = cookieOptions.CookieDomain;
     options.Expires = expires;
     options.HttpOnly = cookieOptions.CookieHttpOnly;
     options.Path = cookieOptions.CookiePath;
     options.Secure = !options.HttpOnly;
     return options;
 }
		public void Append(string key, string value, CookieOptions options) {
			Microsoft.Owin.CookieOptions owinOptions = new Microsoft.Owin.CookieOptions {
				Path = options.Path,
				Domain = options.Domain,
				Secure = options.Secure,
				HttpOnly = options.HttpOnly,
				Expires = options.Expires
			};
			_cookies.Append(key, value, owinOptions);
		}
 public void Append(string key, string value, CookieOptions options)
 {
     Microsoft.Owin.CookieOptions owinOptions = new Microsoft.Owin.CookieOptions {
         Path     = options.Path,
         Domain   = options.Domain,
         Secure   = options.Secure,
         HttpOnly = options.HttpOnly,
         Expires  = options.Expires
     };
     _cookies.Append(key, value, owinOptions);
 }
        private Microsoft.Owin.CookieOptions CreateCookieOptions()
        {
            var path = context.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();

            var options = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = false,
                Secure   = context.Request.IsSecure,
                Path     = path
            };

            return(options);
        }
        private Microsoft.Owin.CookieOptions CreateCookieOptions()
        {
            var path = context.Request.Environment.GetIdentityServerBasePath();
            if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1);
            if (String.IsNullOrWhiteSpace(path)) path = "/";

            var options = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = false,
                Secure = context.Request.IsSecure,
                Path = path
            };
            return options;
        }
 private void AfterAccessNotification(TokenCacheNotificationArgs args)
 {
     if (this.HasStateChanged)
     {
         var state = this.Serialize();
         var value = Convert.ToBase64String(state);
         // This should cover enough time during which the tokens themselves should remain valid,
         // since refresh tokens themselves are only valid for 14 days.
         // See http://www.cloudidentity.com/blog/2015/03/20/azure-ad-token-lifetime/
         var expirationTime = DateTime.UtcNow.AddDays(14);
         var options = new CookieOptions { Expires = expirationTime, HttpOnly = true, Secure = true };
         this.cookieManager.AppendResponseCookie(this.context, CookieName, value, options);
     }
 }
Example #13
0
 public void DeleteCookie(string cookieName, CookieOptions cookieOptions)
 {
     if (cookieOptions == null)
     {
         throw new ArgumentNullException("cookieOptions");
     }
     _response.DeleteCookie(cookieName, new global::Owin.Types.Helpers.CookieOptions
     {
         Domain = cookieOptions.Domain,
         Path = cookieOptions.Path,
         Expires = cookieOptions.Expires,
         Secure = cookieOptions.Secure,
         HttpOnly = cookieOptions.HttpOnly,
     });
 }
        public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue = options.Expires.HasValue;

            var cookie = new HttpCookie(key, value);
            if (domainHasValue)
            {
                cookie.Domain = options.Domain;
            }
            if (pathHasValue)
            {
                cookie.Path = options.Path;
            }
            if (expiresHasValue)
            {
                cookie.Expires = options.Expires.Value;
            }
            if (options.Secure)
            {
                cookie.Secure = true;
            }
            if (options.HttpOnly)
            {
                cookie.HttpOnly = true;
            }

            webContext.Response.AppendCookie(cookie);
        }
        public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            AppendResponseCookie(
                context,
                key,
                string.Empty,
                new CookieOptions
                    {
                        Path = options.Path,
                        Domain = options.Domain,
                        Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                    });
        }
Example #16
0
        private Microsoft.Owin.CookieOptions CreateCookieOptions()
        {
            var path = context.Request.Environment.GetIdentityServerBasePath();

            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            if (String.IsNullOrWhiteSpace(path))
            {
                path = "/";
            }

            var options = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = false,
                Secure   = context.Request.IsSecure,
                Path     = path
            };

            return(options);
        }
        public void DeleteCookie(Microsoft.Owin.IOwinContext context, string key, Microsoft.Owin.CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            AppendResponseCookie(
                context, key,
                string.Empty,
                new CookieOptions
            {
                Path    = options.Path,
                Domain  = options.Domain,
                Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            });
        }
        public override async Task Invoke(IOwinContext context)
        {
            // Check for the SSL Cookie
            var forceSSL = context.Request.Cookies[CookieName];
            if (!String.IsNullOrEmpty(forceSSL) && !context.Request.IsSecure)
            {
                _logger.WriteVerbose("Force SSL Cookie found. Redirecting to SSL");
                // Presence of the cookie is all we care about, value is ignored
                context.Response.Redirect(new UriBuilder(context.Request.Uri)
                {
                    Scheme = Uri.UriSchemeHttps,
                    Port = SslPort
                }.Uri.AbsoluteUri);
            }
            else
            {
                // Invoke the rest of the pipeline
                await Next.Invoke(context);

                var cookieOptions = new CookieOptions() { HttpOnly = true };
                if (context.Authentication.AuthenticationResponseGrant != null)
                {
                    _logger.WriteVerbose("Auth Grant found, writing Force SSL cookie");
                    // We're granting new authentication, so drop a force ssl cookie
                    // for later.
                    context.Response.Cookies.Append(CookieName, "true", cookieOptions);
                }
                else if (context.Authentication.AuthenticationResponseRevoke != null)
                {
                    _logger.WriteVerbose("Auth Revoke found, removing Force SSL cookie");
                    // We're revoking authentication, so remove the force ssl cookie
                    context.Response.Cookies.Delete(CookieName, new CookieOptions()
                    {
                        HttpOnly = true
                    });
                }
            }
        }
        public void AppendResponseCookie(Microsoft.Owin.IOwinContext context, string key, string value, Microsoft.Owin.CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var webContext = context.Get <HttpContextBase>(typeof(HttpContextBase).FullName);

            bool domainHasValue  = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue    = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue = options.Expires.HasValue;

            var cookie = new HttpCookie(key, value);

            if (domainHasValue)
            {
                cookie.Domain = options.Domain;
            }

            if (pathHasValue)
            {
                cookie.Path = options.Path;
            }

            if (expiresHasValue)
            {
                cookie.Expires = options.Expires.Value;
            }

            if (options.Secure)
            {
                cookie.Secure = true;
            }

            if (options.HttpOnly)
            {
                cookie.HttpOnly = true;
            }

            webContext.Response.AppendCookie(cookie);
        }
        internal void SetValue(string username)
        {
            if (options.AuthenticationOptions.RememberLastUsername)
            {
                var cookieName = options.AuthenticationOptions.CookieOptions.Prefix + "username";
                var secure = ctx.Request.Scheme == Uri.UriSchemeHttps;
                var path = ctx.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();

                var cookieOptions = new Microsoft.Owin.CookieOptions
                {
                    HttpOnly = true,
                    Secure = secure,
                    Path = path
                };

                if (!String.IsNullOrWhiteSpace(username))
                {
                    var bytes = Encoding.UTF8.GetBytes(username);
                    bytes = options.DataProtector.Protect(bytes, cookieName);
                    username = Base64Url.Encode(bytes);
                    cookieOptions.Expires = DateTimeHelper.UtcNow.AddYears(1);
                }
                else
                {
                    username = "******";
                    cookieOptions.Expires = DateTimeHelper.UtcNow.AddYears(-1);
                }

                ctx.Response.Cookies.Append(cookieName, username, cookieOptions);
            }
        }
        /// <summary>
        /// Sets an expired cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="options"></param>
        public void Delete(string key, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);

            Func<string, bool> rejectPredicate;
            if (domainHasValue)
            {
                rejectPredicate = value =>
                    value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase) &&
                        value.IndexOf("domain=" + options.Domain, StringComparison.OrdinalIgnoreCase) != -1;
            }
            else if (pathHasValue)
            {
                rejectPredicate = value =>
                    value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase) &&
                        value.IndexOf("path=" + options.Path, StringComparison.OrdinalIgnoreCase) != -1;
            }
            else
            {
                rejectPredicate = value => value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase);
            }

            IList<string> existingValues = Headers.GetValues(Constants.Headers.SetCookie);
            if (existingValues != null)
            {
                Headers.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !rejectPredicate(value)).ToArray());
            }

            Append(key, string.Empty, new CookieOptions
            {
                Path = options.Path,
                Domain = options.Domain,
                Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            });
        }
 private void SetupDomain(IOwinContext context, CookieOptions options)
 {
     //here we assign the cookie domain, so first resolve our general settings
     var generalSettings = mobSocialEngine.ActiveEngine.Resolve<GeneralSettings>();
     options.Domain = generalSettings.ApplicationCookieDomain;
 }
 public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
 {
     SetupDomain(context, options);
     _defaultCookieManager.DeleteCookie(context, key, options);
 }
 public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
 {
     SetupDomain(context, options);
     _defaultCookieManager.AppendResponseCookie(context, key, value, options);
 }
Example #25
0
        public override async Task Invoke(IOwinContext context)
        {
            var customerService = new CustomerService();
            var commerceService = new CommerceService();
            var ctx = SiteContext.Current;

            ctx.LoginProviders = GetExternalLoginProviders(context).ToArray();

            // Need to load language for all files, since translations are used within css and js
            // the order of execution is very important when initializing context
            // 1st: initialize some sort of context, especially get a list of all shops first
            // other methods will rely on that to be performance efficient
            // 2nd: find current shop from url, which context with shops will be used for
            ctx.Shops = await commerceService.GetShopsAsync();

            // Get current language
            var language = this.GetLanguage(context).ToSpecificLangCode();
            ctx.Language = language;

            var shop = this.GetStore(context, language);

            if (shop == null)
            {
                using (var reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath("~/App_data/Help/nostore.html")))
                {
                    var content = await reader.ReadToEndAsync();
                    await context.Response.WriteAsync(content);
                }
            }
            else
            {
                var currency = GetStoreCurrency(context, shop);
                shop.Currency = currency;
                ctx.Shop = shop;
                ctx.Themes = await commerceService.GetThemesAsync(SiteContext.Current);

                // if language is not set, set it to default shop language
                if (String.IsNullOrEmpty(ctx.Language))
                {
                    language = shop.DefaultLanguage;
                    if (String.IsNullOrEmpty(language))
                    {
                        throw new HttpException(404, "Store language not found");
                    }

                    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(language);
                    ctx.Language = language;
                }

                if (!this.IsResourceFile()) // only load settings for resource files, no need for other contents
                {
                    // save info to the cookies
                    context.Response.Cookies.Append(StoreCookie, shop.StoreId, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });
                    context.Response.Cookies.Append(LanguageCookie, ctx.Language, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });
                    context.Response.Cookies.Append(CurrencyCookie, shop.Currency, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });

                    if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated)
                    {
                        ctx.Customer = await customerService.GetCustomerAsync(
                            context.Authentication.User.Identity.Name, shop.StoreId);

                        if (ctx.Customer == null)
                        {
                            context.Authentication.SignOut();
                        }
                        else
                        {
                            ctx.CustomerId = ctx.Customer.Id;
                        }
                    }

                    if (ctx.Customer == null)
                    {
                        var cookie = context.Request.Cookies[AnonymousCookie];

                        if (string.IsNullOrEmpty(cookie))
                        {
                            cookie = Guid.NewGuid().ToString();

                            var cookieOptions = new CookieOptions
                            {
                                Expires = DateTime.UtcNow.AddDays(30)
                            };

                            context.Response.Cookies.Append(AnonymousCookie, cookie, cookieOptions);
                        }

                        ctx.CustomerId = cookie;
                    }

                    // TODO: detect if shop exists, user has access
                    // TODO: store anonymous customer id in cookie and update and merge cart once customer is logged in

                    ctx.Linklists = await commerceService.GetListsAsync(SiteContext.Current);
                    ctx.PageTitle = ctx.Shop.Name;
                    ctx.Collections = await commerceService.GetCollectionsAsync(SiteContext.Current);
                    ctx.Pages = new PageCollection();
                    ctx.Forms = commerceService.GetForms();


                    var cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId);
                    if (cart == null)
                    {
                        var dtoCart = new ApiClient.DataContracts.Cart.ShoppingCart
                        {
                            CreatedBy = ctx.CustomerId,
                            CreatedDate = DateTime.UtcNow,
                            Currency = shop.Currency,
                            CustomerId = ctx.CustomerId,
                            CustomerName = ctx.Customer != null ? ctx.Customer.Name : null,
                            LanguageCode = ctx.Language,
                            Name = "default",
                            StoreId = shop.StoreId
                        };

                        await commerceService.CreateCartAsync(dtoCart);
                        cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId);
                    }

                    ctx.Cart = cart;

                    if (context.Authentication.User.Identity.IsAuthenticated)
                    {
                        var anonymousCookie = context.Request.Cookies[AnonymousCookie];

                        if (anonymousCookie != null)
                        {
                            var anonymousCart = await commerceService.GetCartAsync(ctx.StoreId, anonymousCookie);

                            if (anonymousCart != null)
                            {
                                ctx.Cart = await commerceService.MergeCartsAsync(anonymousCart);
                            }
                        }

                        context.Response.Cookies.Delete(AnonymousCookie);
                    }

                    ctx.PriceLists = await commerceService.GetPriceListsAsync(ctx.Shop.Catalog, shop.Currency, new TagQuery());
                    ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context));

                    // update theme files
                    await commerceService.UpdateThemeCacheAsync(SiteContext.Current);

                    ctx.Blogs = commerceService.GetBlogs(SiteContext.Current);
                }
                else
                {
                    ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context));
                }

                ctx.Settings = commerceService.GetSettings(
                    ctx.Theme.ToString(),
                    context.Request.Path.HasValue && context.Request.Path.Value.Contains(".scss") ? "''" : null);

                ctx.CountryOptionTags = commerceService.GetCountryTags();

                if (ctx.Shop.Currency.Equals("GBP", StringComparison.OrdinalIgnoreCase) || ctx.Shop.Currency.Equals("USD", StringComparison.OrdinalIgnoreCase))
                {
                    ctx.Shop.MoneyFormat = commerceService.CurrencyDictionary[ctx.Shop.Currency] + "{{ amount }}";
                }
                else
                {
                    ctx.Shop.MoneyFormat = "{{ amount }} " + commerceService.CurrencyDictionary[ctx.Shop.Currency];
                }

                context.Set("vc_sitecontext", ctx);

                await this.Next.Invoke(context);
            }
        }
Example #26
0
        public override async Task Invoke(IOwinContext context)
        {
            if (!context.Request.Path.StartsWithSegments(new PathString("/admin"))
                && !context.Request.Path.StartsWithSegments(new PathString("/areas/admin"))
                && !context.Request.Path.StartsWithSegments(new PathString("/api"))
                && !context.Request.Path.StartsWithSegments(new PathString("/favicon.ico"))
                )
            {
                var customerService = _customerServce;
                var commerceService = _commerceServce;
                var ctx = SiteContext.Current;

                ctx.LoginProviders = GetExternalLoginProviders(context).ToArray();

                // Need to load language for all files, since translations are used within css and js
                // the order of execution is very important when initializing context
                // 1st: initialize some sort of context, especially get a list of all shops first
                // other methods will rely on that to be performance efficient
                // 2nd: find current shop from url, which context with shops will be used for
                ctx.Shops = await commerceService.GetShopsAsync();

                // Get current language
                var language = this.GetLanguage(context).ToSpecificLangCode();
                ctx.Language = language;

                var shop = this.GetStore(context, language);

                if (shop == null)
                {
                    await RenderHtmlContents(context, "nostore");
                    return;
                }

                if (await RenderGettingStarted(context))
                {
                    return;
                }

                var currency = GetStoreCurrency(context, shop);
                shop.Currency = currency;
                ctx.Shop = shop;
                ctx.Themes = await commerceService.GetThemesAsync(SiteContext.Current);

                if (ctx.Themes == null || !ctx.Themes.Any())
                {
                    await RenderHtmlContents(context, "notheme");
                    return;
                }

                // if language is not set, set it to default shop language
                if (String.IsNullOrEmpty(ctx.Language))
                {
                    language = shop.DefaultLanguage;
                    if (String.IsNullOrEmpty(language))
                    {
                        throw new HttpException(404, "Store language not found");
                    }

                    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(language);
                    ctx.Language = language;
                }

                if (!this.IsResourceFile()) // only load settings for resource files, no need for other contents
                {
                    // save info to the cookies
                    context.Response.Cookies.Append(
                        StoreCookie,
                        shop.StoreId,
                        new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });
                    context.Response.Cookies.Append(
                        LanguageCookie,
                        ctx.Language,
                        new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });
                    context.Response.Cookies.Append(
                        CurrencyCookie,
                        shop.Currency,
                        new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });

                    if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated)
                    {
                        ctx.Customer =
                            await customerService.GetCustomerAsync(context.Authentication.User.Identity.Name, shop.StoreId);

                        if (ctx.Customer == null)
                        {
                            context.Authentication.SignOut();
                        }
                        else
                        {
                            ctx.CustomerId = ctx.Customer.Id;
                        }
                    }

                    if (ctx.Customer == null)
                    {
                        var cookie = context.Request.Cookies[AnonymousCookie];

                        if (string.IsNullOrEmpty(cookie))
                        {
                            cookie = Guid.NewGuid().ToString();

                            var cookieOptions = new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) };

                            context.Response.Cookies.Append(AnonymousCookie, cookie, cookieOptions);
                        }

                        ctx.CustomerId = cookie;
                    }

                    // TODO: detect if shop exists, user has access
                    // TODO: store anonymous customer id in cookie and update and merge cart once customer is logged in

                    ctx.Linklists = await commerceService.GetListsAsync(SiteContext.Current);
                    ctx.PageTitle = ctx.Shop.Name;
                    ctx.Collections = await commerceService.GetCollectionsAsync(SiteContext.Current);
                    ctx.Pages = new PageCollection();
                    ctx.Forms = commerceService.GetForms();

                    var cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId);

                    if (cart == null)
                    {
                        cart = new Cart(SiteContext.Current.StoreId, SiteContext.Current.CustomerId, SiteContext.Current.Shop.Currency, SiteContext.Current.Language);
                    }

                    ctx.Cart = cart;

                    if (ctx.Shop.QuotesEnabled)
                    {
                        ctx.ActualQuoteRequest = await _quoteService.GetCurrentQuoteRequestAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId);
                        if (ctx.ActualQuoteRequest == null)
                        {
                            ctx.ActualQuoteRequest = new QuoteRequest(SiteContext.Current.StoreId, SiteContext.Current.CustomerId);
                            ctx.ActualQuoteRequest.Currency = ctx.Shop.Currency;
                            ctx.ActualQuoteRequest.Tag = "actual";
                        }
                        if (ctx.Customer != null)
                        {
                            ctx.ActualQuoteRequest.CustomerName = ctx.Customer.Name;
                        }
                    }

                    if (context.Authentication.User.Identity.IsAuthenticated)
                    {
                        var anonymousCookie = context.Request.Cookies[AnonymousCookie];

                        if (anonymousCookie != null)
                        {
                            var anonymousCart = await commerceService.GetCartAsync(ctx.StoreId, anonymousCookie);

                            if (anonymousCart != null)
                            {
                                ctx.Cart.MergeCartWith(anonymousCart);

                                if (ctx.Cart.IsTransient)
                                {
                                    await commerceService.CreateCartAsync(ctx.Cart);
                                }
                                else
                                {
                                    await commerceService.SaveChangesAsync(ctx.Cart);
                                }

                                await commerceService.DeleteCartAsync(anonymousCart.Key);
                            }

                            if (ctx.Shop.QuotesEnabled)
                            {
                                var anonymousQuote = await _quoteService.GetCurrentQuoteRequestAsync(ctx.StoreId, anonymousCookie);

                                if (anonymousQuote != null)
                                {
                                    ctx.ActualQuoteRequest.MergeQuoteWith(anonymousQuote);

                                    await _quoteService.UpdateQuoteRequestAsync(ctx.ActualQuoteRequest);

                                    await _quoteService.DeleteAsync(anonymousQuote.Id);
                                }
                            }
                        }

                        context.Response.Cookies.Delete(AnonymousCookie);
                    }

                    ctx.PriceLists =
                        await commerceService.GetPriceListsAsync(ctx.Shop.Catalog, shop.Currency, new TagQuery());
                    ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context));

                    // update theme files
                    await commerceService.UpdateThemeCacheAsync(SiteContext.Current);

                    ctx.Blogs = commerceService.GetBlogs(SiteContext.Current);
                }
                else
                {
                    ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context));
                }

                ctx.Settings = commerceService.GetSettings(
                    ctx.Theme.ToString(),
                    context.Request.Path.HasValue && context.Request.Path.Value.Contains(".scss") ? "''" : null);

                ctx.CountryOptionTags = commerceService.GetCountryTags();

                if (ctx.Shop.Currency.Equals("GBP", StringComparison.OrdinalIgnoreCase)
                    || ctx.Shop.Currency.Equals("USD", StringComparison.OrdinalIgnoreCase))
                {
                    ctx.Shop.MoneyFormat = commerceService.CurrencyDictionary[ctx.Shop.Currency] + "{{ amount }}";
                }
                else
                {
                    ctx.Shop.MoneyFormat = "{{ amount }} " + commerceService.CurrencyDictionary[ctx.Shop.Currency];
                }

                if (ctx.Settings["google_analytics_tracking_id"] == null)
                {
                    var gaTrackingId = ConfigurationManager.AppSettings["GoogleAnalytics:AccountId"];
                    if (!string.IsNullOrEmpty(gaTrackingId))
                    {
                        ctx.Settings.Set("google_analytics_tracking_id", gaTrackingId);
                    }
                }

                if (ctx.Settings["facebook_tracking_id"] == null)
                {
                    var fbTrackingId = ConfigurationManager.AppSettings["FacebookTracker:AddPixelId"];
                    if (!string.IsNullOrEmpty(fbTrackingId))
                    {
                        ctx.Settings.Set("facebook_tracking_id", fbTrackingId);
                    }
                }

                context.Set("vc_sitecontext", ctx);
            }

            await Next.Invoke(context);
        }
        void SetCookie(string value)
        {
            DateTime? expires = null;
            if (String.IsNullOrWhiteSpace(value))
            {
                var existingValue = GetCookie();
                if (existingValue == null)
                {
                    // no need to write cookie to clear if we don't already have one
                    return;
                }

                value = ".";
                expires = DateTime.Now.AddYears(-1);
            }

            var opts = new Microsoft.Owin.CookieOptions
            {
                HttpOnly = true,
                Secure = Secure,
                Path = CookiePath,
                Expires = expires
            };

            this.ctx.Response.Cookies.Append(CookieName, value, opts);
        }
Example #28
0
        protected override string RetrieveNonce(OpenIdConnectMessage message)
        {
            if (message.IdToken == null)
            {
                return null;
            }

            JwtSecurityToken token = new JwtSecurityToken(message.IdToken);
            if (token == null)
            {
                return null;
            }

            //computing the hash of nonce and appending it to the cookie name
            string nonceKey = GetNonceKey(token.Payload.Nonce);
            string nonceCookie = Request.Cookies[nonceKey];
            if (string.IsNullOrWhiteSpace(nonceCookie))
            {
                _logger.WriteWarning("The nonce cookie was not found.");
                return null;
            }

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };

            Response.Cookies.Delete(nonceKey, cookieOptions);

            string nonce = null;
            AuthenticationProperties nonceProperties =
                Options.StateDataFormat.Unprotect(Encoding.UTF8.GetString(Convert.FromBase64String(nonceCookie)));
            if (nonceProperties != null)
            {
                nonceProperties.Dictionary.TryGetValue(NonceProperty, out nonce);
            }
            else
            {
                _logger.WriteWarning("Failed to un-protect the nonce cookie.");
            }

            return nonce;
        }
        public void ResponseSignIn(FormsResponseSignInContext context)
        {
            var authResult = new AuthenticationResult
            {
                Success = true
            };

            ChatUser loggedInUser = GetLoggedInUser(context);

            var principal = new ClaimsPrincipal(context.Identity);

            // Do nothing if it's authenticated
            if (principal.IsAuthenticated())
            {
                EnsurePersistentCookie(context);
                return;
            }

            ChatUser user = _repository.GetUser(principal);
            authResult.ProviderName = principal.GetIdentityProvider();

            // The user exists so add the claim
            if (user != null)
            {
                if (loggedInUser != null && user != loggedInUser)
                {
                    // Set an error message
                    authResult.Message = String.Format("This {0} account has already been linked to another user.", authResult.ProviderName);
                    authResult.Success = false;

                    // Keep the old user logged in
                    context.Identity.AddClaim(new Claim(JabbRClaimTypes.Identifier, loggedInUser.Id));
                }
                else
                {
                    // Login this user
                    AddClaim(context, user);
                }

            }
            else if (principal.HasRequiredClaims())
            {
                ChatUser targetUser = null;

                // The user doesn't exist but the claims to create the user do exist
                if (loggedInUser == null)
                {
                    // New user so add them
                    user = _membershipService.AddUser(principal);

                    targetUser = user;
                }
                else
                {
                    // If the user is logged in then link
                    _membershipService.LinkIdentity(loggedInUser, principal);

                    _repository.CommitChanges();

                    authResult.Message = String.Format("Successfully linked {0} account.", authResult.ProviderName);

                    targetUser = loggedInUser;
                }

                AddClaim(context, targetUser);
            }
            else if(!principal.HasPartialIdentity())
            {
                // A partial identity means the user needs to add more claims to login
                context.Identity.AddClaim(new Claim(JabbRClaimTypes.PartialIdentity, "true"));
            }

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true
            };

            context.Response.Cookies.Append(Constants.AuthResultCookie,
                                       JsonConvert.SerializeObject(authResult),
                                       cookieOptions);
        }