/// <summary>
        ///   http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx
        /// </summary>
        /// <typeparam name = "TReturnResult"></typeparam>
        /// <typeparam name = "TInputParam"></typeparam>
        /// <param name = "authType"></param>
        /// <param name = "processType"></param>
        /// <returns></returns>
        public IDciContext <TReturnResult, TInputParam> GetAuthenticationContext <TReturnResult, TInputParam>(
            AuthRequestType authType, ProcessType processType) where TInputParam : IDciParameter
        {
            var context = AuthenticationContexts.FirstOrDefault(x =>
                                                                x.Item3.Equals(authType.ToString(),
                                                                               StringComparison.CurrentCulture) &&
                                                                x.Item4.Equals(processType.ToString(),
                                                                               StringComparison.CurrentCulture));

            //Type[] typeArgs = { Type.GetType(context.Item4), Type.GetType(context.Item5) };

            var fileType = Type.GetType(context.Item2);

            //var constructed = fileType.MakeGenericType(typeArgs);

            if (fileType == null)
            {
                throw new Exception("Cannot resolve type for " + context.Item3);
            }

            //if (!typeof(IDciContext<TReturnResult, TInputParam>).IsAssignableFrom(constructed))
            //    throw new Exception(string.Format("{0} must be inherit from IDciContext<TReturnResult, TInputParam>", context.Item3));

            return((IDciContext <TReturnResult, TInputParam>)Activator.CreateInstance(fileType));
        }
        public AuthRequestType ConvertirMTXCA( Autorizacion aut )
        {
            AuthRequestType feAutReq = new AuthRequestType();
            feAutReq.sign = aut.Sign;
            feAutReq.token = aut.Token;
            feAutReq.cuitRepresentada = aut.Cuit;

            return feAutReq;
        }
        /// <summary>
        /// Obtains a new JWT (JSON Web Token) for a guest or registered customer.
        /// </summary>
        /// <param name="requestType">An AuthRequestType value indicating the request type.</param>
        /// <param name="userName">The username, if <paramref name="requestType"/> is "credentials."</param>
        /// <param name="password">The password, if <paramref name="requestType"/> is "credentials."</param>
        /// <returns>A String value containing the token.</returns>
        /// <exception cref="ApiException">Thrown when a <see cref="Fault"/> document is returned.</exception>
        /// <remarks>
        /// Tokens are returned as a HTTP Authorization:Bearer response header entry. These kinds of request are supported, as specified by the type:
        /// <list type="bullet">
        /// <item><term>guest</term><definition>creates a new guest (non-authenticated) customer and returns a token for the customer.</definition></item>
        /// <item><term>credentials</term><definition>authenticates credentials passed in the HTTP Authorization:Basic request header, returning a token for a successfully authenticated customer otherwise results in an AuthenticationFailedException.</definition></item>
        /// <item><term>session</term><definition>authenticates the customer (anonymous or registered) on base of dwsid and dwsecuretoken cookies. It returns a token for a successfully authenticated customer, otherwise results in an AuthenticationFailedException.</definition></item>
        /// <item><term>refresh</term><definition>examines the token passed in the HTTP Authorization:Bearer request header and when valid returns a new token with an updated expiry time.</definition></item>
        /// </list>
        /// <para>
        /// For a request of type credentials:
        /// <list type="bullet">
        /// <item><definition>Updates profile attributes for the customer (for example, "last-visited").</definition></item>
        /// <item><definition>Handles the maximum number of failed login attempts.</definition></item>
        /// </list>
        /// </para>
        /// <para>
        /// For a request of type session:
        /// <list type="bullet">
        /// <item><definition>Does not touch profile attributes for the registered customer (for example, "last-visited"), since this is not a real login.</definition></item>
        /// <item><definition>Returns different tokens for multiple requests with the same session id. Means, there should be only one call per session.</definition></item>
        /// </list>
        /// </para>
        /// </remarks>
        public string CreateJsonWebToken(AuthRequestType requestType, string userName = null, string password = null)
        {
            var requestBody = $"{{\"type\":\"{requestType.GetEnumMemberValue()}\"}}";

            var customerAuthUrl = $"{Configuration.ShopApiConfiguration.Url}{BASE_PATH}auth?client_id={Configuration.Credentials.ClientId}";

            var headers = GetWebHeaders(customerAuthUrl);

            ServiceManager.HttpPost <JwtToken>(customerAuthUrl, headers, GetBytes(requestBody));

            var authorization = headers[HttpRequestHeader.Authorization];

            if (string.IsNullOrEmpty(authorization))
            {
                throw new InvalidOperationException();
            }

            // Authorization header comes back as "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" or "Bearer eyJfdiI6IjXXXXXX.eyJfdiI6IjEiLCJleHAXXXXXXX.-d5wQW4c4O4wt-Zkl7_fiEiALW1XXXX"
            var values = authorization.Split(' ');

            return(values.LastOrDefault());
        }
        private CAERespuestaFe SolicitarCAE( FeCabecera cabFe, AuthRequestType aut )
        {
            ComprobanteType comprobante = this.ObtenerCaeRequest( cabFe );

            SerializadorRequest serializador = new SerializadorRequest();
            serializador.Serializar<ComprobanteType>( comprobante );

            ManagerErroresFe managerErrores = new ManagerErroresFe( this.logueador );
            ResultadoSimpleType resultado;
            ComprobanteCAEResponseType caeResponse;
            CodigoDescripcionType[] observaciones = null;
            CodigoDescripcionType[] errores = null;
            CodigoDescripcionType evento;
            resultado = this.wsfe.autorizarComprobante( aut, comprobante, out caeResponse, out observaciones, out errores, out evento );

            if (this.HuboSolicitudesRechazadas( errores ))
            {
                this.GenerarBackupArchivoSerializado(serializador, comprobante);
            }

            managerErrores.CapturarError( errores, cabFe );

            WrapperCaeRespuestaMTXCA wcrm = new WrapperCaeRespuestaMTXCA();

            return wcrm.Convertir( resultado, caeResponse, observaciones, errores );
        }
        public ActionResult Authenticate(AuthRequestType authType)
        {
            Guard.MakeSureAllInstancesIsNullNot(_mySettings);

            var redirectUrl = string.Empty;

            switch (authType)
            {
                case AuthRequestType.Facebook:
                    var facebookContext = new FacebookAuthRequestProcessingContext();
                    var facebookInputParam = new FacebookAuthRequestProcessingParameter
                                                 {
                                                     RequestUrl = HttpContext.Request.GetUrlBase(),
                                                     RedirectPath = Url.Action("FacebookCallbackAction")
                                                 };

                    facebookContext.Execute(() => facebookInputParam);

                    redirectUrl = facebookContext.ReturnResult;
                    break;

                case AuthRequestType.Twitter:

                    var twitterContext = new TwitterAuthRequestProcessingContext();

                    var twitterCallbackUrl = Request.Url.ToString().Replace("Authenticate", "TwitterCallbackAction");
                    var twitterCallback = new Uri(twitterCallbackUrl);

                    _consumerKey = _mySettings.TwitterConsumerKey;
                    _secretKey = _mySettings.TwitterConsumerSecret;

                    AssertForKeyAndSecretConsummer(_consumerKey, _secretKey);

                    _tokenManager = new InMemoryTokenManager(_consumerKey, _secretKey);

                    var twitterInputParam = new TwitterAuthRequestProcessingParameter
                                                {
                                                    CallBackLink = twitterCallback,
                                                    TokenManager = _tokenManager
                                                };

                    twitterContext.Execute(() => twitterInputParam);

                    HttpContext.Application["TwitterTokenManager"] = _tokenManager;

                    return twitterContext.ReturnResult;

                    break;

                case AuthRequestType.Google:
                    var googleContext = new GoogleAuthRequestProcessingContext();

                    var callbackUrl = Request.Url.ToString().Replace("Authenticate", "GoogleCallbackAction");
                    var callback = new Uri(callbackUrl);

                    _consumerKey = _mySettings.GoogleConsumerKey;
                    _secretKey = _mySettings.GoogleConsumerSecret;

                    AssertForKeyAndSecretConsummer(_consumerKey, _secretKey);

                    _tokenManager = new InMemoryTokenManager(_consumerKey, _secretKey);

                    var googleInputParam = new GoogleAuthRequestProcessingParameter
                                               {
                                                   CallBackLink = callback,
                                                   TokenManager = _tokenManager
                                               };

                    googleContext.Execute(() => googleInputParam);

                    HttpContext.Application["GoogleTokenManager"] = _tokenManager;

                    return googleContext.ReturnResult;

                    break;
            }

            return Redirect(redirectUrl);
        }
        public ActionResult Authenticate(AuthRequestType authType)
        {
            Guard.MakeSureAllInstancesIsNullNot(_mySettings);

            var redirectUrl = string.Empty;

            switch (authType)
            {
            case AuthRequestType.Facebook:
                var facebookContext    = new FacebookAuthRequestProcessingContext();
                var facebookInputParam = new FacebookAuthRequestProcessingParameter
                {
                    RequestUrl   = HttpContext.Request.GetUrlBase(),
                    RedirectPath = Url.Action("FacebookCallbackAction")
                };

                facebookContext.Execute(() => facebookInputParam);

                redirectUrl = facebookContext.ReturnResult;
                break;

            case AuthRequestType.Twitter:

                var twitterContext = new TwitterAuthRequestProcessingContext();

                var twitterCallbackUrl = Request.Url.ToString().Replace("Authenticate", "TwitterCallbackAction");
                var twitterCallback    = new Uri(twitterCallbackUrl);

                _consumerKey = _mySettings.TwitterConsumerKey;
                _secretKey   = _mySettings.TwitterConsumerSecret;

                AssertForKeyAndSecretConsummer(_consumerKey, _secretKey);

                _tokenManager = new InMemoryTokenManager(_consumerKey, _secretKey);

                var twitterInputParam = new TwitterAuthRequestProcessingParameter
                {
                    CallBackLink = twitterCallback,
                    TokenManager = _tokenManager
                };

                twitterContext.Execute(() => twitterInputParam);

                HttpContext.Application["TwitterTokenManager"] = _tokenManager;

                return(twitterContext.ReturnResult);

                break;

            case AuthRequestType.Google:
                var googleContext = new GoogleAuthRequestProcessingContext();

                var callbackUrl = Request.Url.ToString().Replace("Authenticate", "GoogleCallbackAction");
                var callback    = new Uri(callbackUrl);

                _consumerKey = _mySettings.GoogleConsumerKey;
                _secretKey   = _mySettings.GoogleConsumerSecret;

                AssertForKeyAndSecretConsummer(_consumerKey, _secretKey);

                _tokenManager = new InMemoryTokenManager(_consumerKey, _secretKey);

                var googleInputParam = new GoogleAuthRequestProcessingParameter
                {
                    CallBackLink = callback,
                    TokenManager = _tokenManager
                };

                googleContext.Execute(() => googleInputParam);

                HttpContext.Application["GoogleTokenManager"] = _tokenManager;

                return(googleContext.ReturnResult);

                break;
            }

            return(Redirect(redirectUrl));
        }