//Edit for R184
 public LogObject AuthenticationItem_ToLogObject(string RequestId, string User, string Type, string Name, AuthenticationObject Parameters, ErrorObject WebServiceResponse = null)
 {
     LogObject logObject = new LogObject();
     Dictionary<string, string> response = new Dictionary<string, string>();
     Dictionary<string, string> parameters = new Dictionary<string, string>();
     logObject.TimeStamp = DateTime.Now;
     logObject.RequestId = RequestId;
     logObject.User = User;
     logObject.Type = Type;
     logObject.Name = Name;
     parameters.Add("Authentication Type", Parameters.AuthenticationType);
     parameters.Add("ApiUser", Parameters.ApiUser);
     parameters.Add("SharedSecret", Parameters.SharedSecret);
     logObject.Parameters = parameters;
     if (WebServiceResponse == null)
     {
         response.Add("REQUEST_SUCCESSFUL", "The request was successful.");
     }
     else
     {
         response.Add(WebServiceResponse.ErrorKey, WebServiceResponse.Message);
     }
     logObject.Response = response;
     return logObject;
 }
        protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            ErrorUtil errorUtil = new ErrorUtil();
            LogObject logObject = new LogObject();
            int Error = 0;
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            string _requestId;

            var QueryValues = request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
            QueryValues.TryGetValue("requestId", out _requestId);

            if (String.IsNullOrEmpty(_requestId))
                _requestId = Guid.NewGuid().ToString();

            log.ProcessingDebug(_requestId, "Full request URL:" + request.RequestUri.AbsoluteUri);
            request.Properties.Add("requestId", _requestId);
            AuthenticationResponse _responseEnvelope = new AuthenticationResponse(_requestId);

            if (new CommonMethods().IsArgumentFormat(request.RequestUri.OriginalString))
                request = new CommonMethods().CombobulateArgumentRequest(request);

            if (new CommonMethods().IsLegacyFormat(request.RequestUri.OriginalString))
                request = new CommonMethods().CombobulateRequest(request);

            AuthenticationObject authenticationObject = new CommonMethods().GetAuthenticationHeader(request);

            //If header does not contain the required credentials then add an error to the response envelope else
            if (authenticationObject == null || authenticationObject.AuthenticationType == null || authenticationObject.ApiUser == null || authenticationObject.SharedSecret == null)
            {
                Error = ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
                authenticationObject = new AuthenticationObject();
            }

            //Check authentication
            else
            {
                Error = Authenticate(authenticationObject, _requestId);
            }

            if (Error != 0)
            {
                Dictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("ApiUser", authenticationObject.ApiUser);
                _responseEnvelope.Data.Errors.Add(new ErrorObject(Error, parameters));
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                var response = FormatErrorResponse(request, HttpStatusCode.OK, _responseEnvelope);
                tsc.SetResult(response);

                return tsc.Task;
            }
            else
            {
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                var Response = base.SendAsync(request, cancellationToken);
                return Response;
            }
        }
        private int Authenticate(AuthenticationObject authenticationObject, string _requestId)
        {
            HourlyDigest hourlyDigest = new HourlyDigest(AdminUser, AdminPassword, AdminKey);
            string AdminSharedSecret = hourlyDigest.CalculateDigest(DateTime.UtcNow);
            if (authenticationObject.ApiUser == AdminUser && authenticationObject.SharedSecret == AdminSharedSecret)
            {
                HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(authenticationObject.ApiUser, authenticationObject.AuthenticationType), new String[] { "Admin" });
                return 0;
            }

            else
                return ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
        }
        protected override Task<HttpResponseMessage> SendAsync(
                 HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            string _requestId = request.Properties["requestId"].ToString();
            ErrorUtil errorUtil = new ErrorUtil();
            RpcAuthenticationResponse _responseEnvelope = new RpcAuthenticationResponse(_requestId);
            LogObject logObject = new LogObject();
            var errorResponse = new HttpResponseMessage();
            var tsc = new TaskCompletionSource<HttpResponseMessage>();

            //Initialize the error to 0 to be able to check later if there is any error in the request
            int Error = 0;

            if (new CommonMethods().IsLegacyFormat(request.RequestUri.OriginalString))
                request = new CommonMethods().CombobulateRequest(request);

            AuthenticationObject authenticationObject = new CommonMethods().GetAuthenticationHeader(request);
            if (authenticationObject == null || authenticationObject.AuthenticationType == null || authenticationObject.ApiUser == null || authenticationObject.SharedSecret == null)
            {
                Error = ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
                authenticationObject = new AuthenticationObject();
            }

            //Authenticate with pmp
            else
            {
                Error = PmpAuth(authenticationObject);
            }

            //The following logic has been added to enforce xml output by default if no or incompatible application value is specified in the request header
            var responseType = request.GetRequestContext().Url.Request.Headers.Accept.LastOrDefault();
            if (responseType != null && responseType.ToString().ToLower().Equals("application/json"))
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            else
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            if (Error != 0)
            {
                _responseEnvelope.Data.Errors.Add(new ErrorObject(Error));
                errorResponse = new MethodsApi().FormatRpcErrorResponse(request, HttpStatusCode.Unauthorized, _responseEnvelope);
                //R185 Modification
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                tsc.SetResult(errorResponse);
                return tsc.Task;
            }

            //Authentication succeeded...continue with the request
            else
            {
                // This piece of code has been added to unit test this handler
                // In case of success we are returning an empty RpcAuthenticationResponse
                if (xunit)
                {
                    tsc.SetResult(new MethodsApi().FormatRpcErrorResponse(request, HttpStatusCode.OK, _responseEnvelope));
                    return tsc.Task;
                }

                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                var rpcResponse = base.SendAsync(request, cancellationToken);

                //Check if request has missing parameters (e.g. does not specify the term id or the offer id in the url)
                if (rpcResponse.Result.StatusCode == HttpStatusCode.NotFound)
                {
                    _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_MISSING_DATA_ARGUMENTS));
                    //Log the error
                    Dictionary<string, string> parameters = new Dictionary<string, string>();
                    parameters.Add("URL", rpcResponse.Result.RequestMessage.RequestUri.PathAndQuery);
                    log.InfoJson(new Methods().Error_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, operationName.ApiCall.ToString(), parameters, _responseEnvelope.Data.Errors));
                    errorResponse = new MethodsApi().FormatRpcErrorResponse(request, HttpStatusCode.NotFound, _responseEnvelope);
                    tsc.SetResult(errorResponse);
                    return tsc.Task;
                }

                return rpcResponse;
            }
        }
 private int PmpAuth(AuthenticationObject authenticationObject)
 {
     int error = 0;
     try
     {
         IPmp Pmp = PMP();
         //If Pmp failed to authenticated the request then set the error to authentication failed
         if (!Pmp.Authenticate(authenticationObject.ApiUser, authenticationObject.SharedSecret))
         {
             error = ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
         }
     }
     catch
     {
         //Something bad happened (E.g. connection to pmp failed)
         error = ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
     }
     return error;
 }
        protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            ErrorUtil errorUtil = new ErrorUtil();
            LogObject logObject = new LogObject();
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            string _requestId = request.Properties["requestId"].ToString();
            ProviderAuthenticationResponse _responseEnvelope = new ProviderAuthenticationResponse(_requestId);
            //Initialize the error to 0 to be able to check later if there is any error in the request
            int Error = 0;

            //Get the authentication credentials
            AuthenticationObject authenticationObject = new CommonMethods().GetAuthenticationHeader(request);

            //If header does not contain the required credentials then add an error to the response envelope else
            if (authenticationObject == null || authenticationObject.AuthenticationType == null || authenticationObject.ApiUser == null || authenticationObject.SharedSecret == null)
            {
                Error = ErrorKey.ERR_PROVIDER_AUTHENTICATION_FAILED;
                authenticationObject = new AuthenticationObject();
            }

            //Authenticate with pmp
            else
            {
                Error = PmpAuth(authenticationObject, _requestId);
            }

            //Error different then 0, send back the request with an error message
            if (Error != 0)
            {

                Dictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("ApiUser", authenticationObject.ApiUser);

                //Add the error in the response envelope
                //Edit for R184
                _responseEnvelope.Data.Errors.Add(new ErrorObject(Error, parameters));
                //R185 Modification
                //_responseEnvelope.Data.Errors.Add(new ErrorObject(Error, parameters));

                //Log the error
                //Edit for R184
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                //R185 Modification
                //logObject = new Methods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);

                var response = new MethodsApi().FormatProviderErrorResponse(request, HttpStatusCode.OK, _responseEnvelope);

                //Return back the results
                tsc.SetResult(response);

                return tsc.Task;
            }

            //Authentication succeeded...continue with the request
            else
            {
                //Authentication and authorization were successful, log the request and  continue processing
                //Edit for R184
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                //R185 Modification
                //logObject = new Methods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);

                // This piece of code has been added to unit test this handler
                // In case of success we are returning an empty ProviderAuthenticationResponse
                if (xunit)
                {
                    tsc.SetResult(new MethodsApi().FormatProviderErrorResponse(request, HttpStatusCode.OK, _responseEnvelope));
                    return tsc.Task;
                }

                var providerResponse = base.SendAsync(request, cancellationToken);

                //Check if request has missing action name (e.g. does not specify the action for liveoffers)
                if (providerResponse.Result.StatusCode == HttpStatusCode.InternalServerError)
                {
                    _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_PROVIDER_MISSING_ACTION));
                    var response = new MethodsApi().FormatProviderErrorResponse(request, HttpStatusCode.OK, _responseEnvelope);
                    //Log the error
                    Dictionary<string, string> parameters = new Dictionary<string, string>();
                    parameters.Add("URL", providerResponse.Result.RequestMessage.RequestUri.AbsolutePath);
                    log.InfoJson(new Methods().Error_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, operationName.ApiCall.ToString(), parameters, _responseEnvelope.Data.Errors));
                    tsc.SetResult(response);
                    return tsc.Task;
                }

                return providerResponse;
            }
        }
        /// <summary>
        /// Method that will contact pmp and check if the request sent is authenticated.
        /// If it is authenticated it will check if the provider is authorized to use the offer service
        /// </summary>
        /// <param name="message"></param>
        /// <param name="Error"></param>
        private int PmpAuth(AuthenticationObject authenticationObject, string _requestId)
        {
            bool isPmpAuthenticated = false;
            bool isAuthorized = false;
            int error = 0;

            try
            {
                IPmp Pmp = PMP();
                //Communicate with pmp the provider apiUser and SharedSecret

                isPmpAuthenticated = Pmp.Authenticate(authenticationObject.ApiUser, authenticationObject.SharedSecret);
                if (isPmpAuthenticated)
                {
                    isAuthorized = Pmp.Authorize(authenticationObject.ApiUser, offerServiceUserResource);

                    if (isAuthorized)
                    {
                        //Provider is authorized, mark the request as authorized and continue processing
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(authenticationObject.ApiUser, authenticationObject.AuthenticationType), new String[] { "Provider" });
                        }

                        var localProvider = ProviderRepository().SelectByProviderId(authenticationObject.ApiUser);
                        //Checking local database for provider URL Code
                        if (localProvider == null || (DateTime.Now - localProvider.Update_Date).TotalMinutes > Convert.ToInt32(ConfigurationManager.AppSettings["PROVIDER_MANAGEMENT_CHECK_INTERVAL"]))
                        {
                            LoggerFactory.GetLogger().Debug("The provider is either not up to date or does not exist in Offer Service database. Calling the showMainstreamProviders service to get the updated information.");
                            var providerExist = true;
                            var providerEnabled = true;//Enabled status in this context means that he is enabled + has at least 1 welcomeUrlCode

                            //Call the netmr web service
                            var showMainstreamProviderResponse = CSSProviders().GetMainstreamProviderInfo(authenticationObject.ApiUser);
                            if (showMainstreamProviderResponse.Errors != null && showMainstreamProviderResponse.MainstreamProviderObject == null)
                            {
                                providerExist = false;
                                LoggerFactory.GetLogger().ErrorJson(new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, new List<ErrorObject>() { new ErrorObject() { ErrorKey = "ERR_GTM_PROVIDER_NOT_FOUND", Message = "Provider was not found in GTM database." } }));
                                if (localProvider != null)
                                {
                                    ProviderRepository().Delete(localProvider.Id);
                                }
                            }
                            else
                            {
                                if (!showMainstreamProviderResponse.MainstreamProviderObject.Exists(msp => msp.Enabled == true))
                                {
                                    providerEnabled = false;
                                }
                            }

                            if (providerExist)
                            {
                                var providerFromServiceResponse = showMainstreamProviderResponse.MainstreamProviderObject.Find(msp => msp.ProviderId == authenticationObject.ApiUser);

                                //Initializing the new provider information
                                ProviderObject provider = new ProviderObject();
                                if (providerFromServiceResponse != null)
                                {
                                    provider.ProviderId = providerFromServiceResponse.ProviderId;
                                    provider.WelcomeURLCode = providerFromServiceResponse.WelcomeUrlCode;
                                    provider.Enabled = providerFromServiceResponse.Enabled;
                                }

                                if (localProvider != null)
                                {
                                    //The provider exists in the database. Updating the database row.
                                    provider.Id = localProvider.Id;
                                    ProviderRepository().Update(provider);
                                }
                                else
                                {
                                    //The provider does not exist in the database. Inserting the provider to the database.
                                    ProviderRepository().Insert(provider);
                                }

                                if (!providerEnabled)
                                {
                                    error = ErrorKey.ERR_PROVIDER_DEACTIVATED;
                                    LoggerFactory.GetLogger().ErrorJson(new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, new List<ErrorObject>() { new ErrorObject() { ErrorKey = "ERR_GTM_PROVIDER_NOTENABLED", Message = "Provider was not found as enabled in the GTM database. Please make sure that he has the status enabled and has at least one enabled welcome URL." } }));
                                }
                            }
                            else
                            {
                                //return error not exist in hummingbird
                                error = ErrorKey.ERR_PROVIDER_NOT_FOUND;
                            }
                        }
                        //Exists in database AND updated in the last 30 minutes
                        else
                        {
                            LoggerFactory.GetLogger().Debug("Provider is found in the database and is up to date.");
                            //If provider is enabled
                            if (!localProvider.Enabled)
                            {
                                error = ErrorKey.ERR_PROVIDER_DEACTIVATED;
                                LoggerFactory.GetLogger().ErrorJson(new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, new List<ErrorObject>() { new ErrorObject() { ErrorKey = "ERR_OS_PROVIDER_NOTENABLED", Message = "Provider was not found as enabled in the Offer Service database." } }));
                            }
                        }
                    }
                    else
                    {
                        //Provider authorization failed on pmp
                        error = ErrorKey.ERR_PROVIDER_AUTHORIZATION_FAILED;
                    }

                }
                else
                {
                    //Provider authentication failed on pmp
                    error = ErrorKey.ERR_PROVIDER_AUTHENTICATION_FAILED;
                }
            }
            catch (Exception e)
            {
                //Something bad happened (E.g. connection to pmp failed)
                error = ErrorKey.ERR_PROVIDER_AUTHENTICATION_FAILED;
                LoggerFactory.GetLogger().ErrorJson(new Methods().Exception_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, e));
            }
            return error;
        }