/// <summary>
        /// We must log in to be able to use netserver:
        /// </summary>
        /// <param name="filterContext"></param>
        private void RedirectToSuperOfficeLogin(ActionExecutingContext filterContext)
        {
            SuperOfficeAuthHelper.Context = null;
            var ctx        = filterContext.HttpContext.Request.Params["ctx"];
            var crmAppsKey = filterContext.HttpContext.Request.Params["CrmAppsKey"];

            HttpContext.Current.Session["RedirectUrl"] = filterContext.HttpContext.Request.RawUrl;

            //ToDo: Lookup up request and get customer id
            if (!string.IsNullOrEmpty(crmAppsKey))
            {
                var customer = CustomerDataSource.Instance.Customers.Find(c => c.CustomerKey == crmAppsKey);
                if (customer != null)
                {
                    if (customer.IsOnlineCustomer.HasValue && !customer.IsOnlineCustomer.Value)
                    {
                        //Is OnSite customer
                        var ticket      = filterContext.HttpContext.Request.Params["usec"];
                        var userId      = filterContext.HttpContext.Request.Params["userId"];
                        var redirectUrl = "~/Security/LoginOnSite?ticket=" + ticket + "&customerId=" + crmAppsKey + "&userId=" + userId;
                        filterContext.Result = new RedirectResult(redirectUrl);
                        return;
                    }
                }
            }

            //ToDo: Ask CustomerContext if this is on premise
            //ToDo: Redirect to local login controller for onSite


            //Default is SuperOffice Onlne
            var url = SuperOfficeAuthHelper.GetAuthenticateUrl(ctx);

            filterContext.Result = new RedirectResult(url);
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     //if (!SuperOfficeAuthorizeHelper.IsAuthorized(filterContext.HttpContext))
     if (!SuperOfficeAuthHelper.IsAuthorized())
     {
         RedirectToSuperOfficeLogin(filterContext);
     }
 }
        /// <summary>
        /// Determine if there is a valid context stored in ASP.Net <see cref="HttpContext"/>
        /// </summary>
        /// <returns></returns>
        public static bool IsValid()
        {
            HttpContext currentContext = HttpContext.Current;

            if (currentContext != null && currentContext.Session != null)
            {
                var contextContainer = currentContext.Session[Provider] as SoContextContainer;


                // If this is a Anonymous user, we don't have a contextContainer since we actually don't need to store that data.
                if (contextContainer == null &&
                    SoContext.CurrentPrincipal != null &&
                    SoContext.CurrentPrincipal.UserType == UserType.AnonymousAssociate)
                {
                    return(true);
                }

                return(SuperOfficeAuthHelper.IsAuthenticatedWithNetServer());
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Does the actual authentication
        /// </summary>
        /// <param name="context"></param>
        /// <param name="errorReason"></param>
        /// <returns></returns>
        public static bool TryLogin(SuperOfficeContext context, out string errorReason)
        {
            Context = context;

            //If we are allready authorized, then logout first, before creating a cookie....
            if (SuperOffice.SoContext.IsAuthenticated)
            {
                SuperOffice.SoContext.CloseCurrentSession();
                SuperOfficeAuthHelper.Logout();
            }

            // Use forms authentication - this is optional
            var soFormsTicket          = new FormsAuthenticationTicket(context.Email, false, 3600);
            var soFormsTicketEncrypted = FormsAuthentication.Encrypt(soFormsTicket);

            var httpContext = HttpContext.Current;

            httpContext.Session[ConfigManager.SoAuthCookie] = soFormsTicketEncrypted;
            httpContext.Response.Cookies.Add(new HttpCookie(ConfigManager.SoAuthCookie, soFormsTicketEncrypted));



            try
            {
                // If request is not authenticated, and a controller with the
                // SuperOfficeAuthorize attribute is accessed, the called controller
                // will continue to send the user to SuperID. If already authenticated there
                // this user will always return here and be stuck in an endless loop.
                // Therefore, it is important to authenticate with NetServer, and allow the
                // context provider to store the current session. Thus, the SuperOfficeAuthorize
                // attibute will be able to locate the session and proceed unimpeded

                //Authenticate with NetServer using web services if necessary.

                /*
                 * //    From Jens on DevNet:
                 * //    The SuperOffice.Configuration.ConfigFile.WebServices.RemoteBaseUrl is the value actually being used by the proxy to communicate with the server.
                 * //    This value is read from SuperOffice.Configuration.ConfigFile.Services.RemoteBaseUrl if it is not defined.
                 * //    The values of SuperOffice.Configuration.ConfigFile.Services are stored in a value that is static throughout the NetServer process,
                 * //    and shared between tenants in a multi-tenant configuration.
                 * //    The values SuperOffice.Configuration.ConfigFile.WebServices are tenant specific configuration values.
                 * //    */
                //}

                SoSession session = null;

                if (string.IsNullOrEmpty(context.AccessToken))
                {
                    session = SoSession.Authenticate(new SoCredentials()
                    {
                        Ticket = context.Ticket
                    });
                }
                else
                {
                    session = SoSession.Authenticate(new SoAccessTokenSecurityToken(context.AccessToken));
                }

                var principal = SoContext.CurrentPrincipal;
                OverrideContextIdentifier(principal, context.ContextIdentifier);
                var contact = new ContactAgent().GetContact(principal.ContactId);

                context.Company     = contact.FullName;
                context.Name        = principal.FullName;
                context.Username    = principal.Associate;
                context.AssociateId = principal.AssociateId;

                errorReason = String.Empty;

                return(true);
            }
            catch (Exception ex)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                errorReason = ex.Message;
                SuperOfficeAuthHelper.Logout();
                return(false);
            }
        }