Ejemplo n.º 1
0
        public async Task <int> DeleteAsync(IUser registrar, CancellationToken token = default(CancellationToken))
        {
            if (IsDeleted)
            {
                throw new IdentityException("Identity has been deleted");
            }
            if (registrar == null)
            {
                throw new ArgumentException("Registrar should be a valid member");
            }
            string deleteURL = "";

            try
            {
                deleteURL = client.GetURL(HFCA_IDENTITY + "/" + EnrollmentId);
                logger.Debug($"identity  url: {deleteURL}, registrar: {registrar.Name}");
                JObject result = await client.HttpDeleteAsync(deleteURL, registrar, token).ConfigureAwait(false);

                statusCode = result["statusCode"]?.Value <int>() ?? 500;
                if (statusCode < 400)
                {
                    GetHFCAIdentity(result);
                    logger.Debug($"identity  url: {deleteURL}, registrar: {registrar} done.");
                }

                IsDeleted = true;
                return(statusCode);
            }
            catch (HTTPException e)
            {
                string            msg = $"[Code: {e.StatusCode}] - Error while deleting user '{EnrollmentId}' from url '{deleteURL}': {e.Message}";
                IdentityException identityException = new IdentityException(msg, e);
                logger.Error(msg);
                throw identityException;
            }
            catch (Exception e)
            {
                string            msg = $"Error while deleting user '{EnrollmentId}' from url '{deleteURL}':  {e.Message}";
                IdentityException identityException = new IdentityException(msg, e);
                logger.Error(msg);
                throw identityException;
            }
        }
        /// <summary>
        /// Validates payment configuration.
        /// </summary>
        /// <param name="paymentConfig">The Payment configuration.</param>
        public static void ValidateConfiguration(PaymentConfiguration paymentConfig)
        {
            string[] supportedPaymentModes = { "sandbox", "live" };

            paymentConfig.AssertNotNull(nameof(paymentConfig));

            paymentConfig.ClientId.AssertNotEmpty(nameof(paymentConfig.ClientId));
            paymentConfig.ClientSecret.AssertNotEmpty(nameof(paymentConfig.ClientSecret));
            paymentConfig.AccountType.AssertNotEmpty(nameof(paymentConfig.AccountType));

            if (!supportedPaymentModes.Contains(paymentConfig.AccountType))
            {
                throw new PartnerDomainException(Resources.InvalidPaymentModeErrorMessage);
            }

            try
            {
                Dictionary <string, string> configMap = new Dictionary <string, string>();
                configMap.Add("clientId", paymentConfig.ClientId);
                configMap.Add("clientSecret", paymentConfig.ClientSecret);
                configMap.Add("mode", paymentConfig.AccountType);
                configMap.Add("connectionTimeout", "120000");

                string accessToken = new OAuthTokenCredential(configMap).GetAccessToken();
                var    apiContext  = new APIContext(accessToken);
            }
            catch (PayPalException paypalException)
            {
                if (paypalException is IdentityException)
                {
                    // thrown when API Context couldn't be setup.
                    IdentityException identityFailure = paypalException as IdentityException;
                    IdentityError     failureDetails  = identityFailure.Details;
                    if (failureDetails != null && failureDetails.error.ToLower() == "invalid_client")
                    {
                        throw new PartnerDomainException(ErrorCode.PaymentGatewayIdentityFailureDuringConfiguration).AddDetail("ErrorMessage", Resources.PaymentGatewayIdentityFailureDuringConfiguration);
                    }
                }

                // if this is not an identity exception rather some other issue.
                throw new PartnerDomainException(ErrorCode.PaymentGatewayFailure).AddDetail("ErrorMessage", paypalException.Message);
            }
        }
        private async Task HandleAsync(HttpContext context, Exception ex)
        {
            var responseStatusCode = HttpStatusCode.InternalServerError;
            var responseText       = string.Empty;

            if (ex is ValidationException valdEx)
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseText       = JsonConvert.SerializeObject(
                    new ValidationErrorResponseModel
                {
                    Message = valdEx.Message,
                    Data    = valdEx.GetData()
                }, NewtonsoftLogic.GetCammelCaseSettings());
            }
            else
            {
                var(statusCode, data) = ex switch
                {
                    NotFoundException _ => (HttpStatusCode.NotFound, ex.GetData()),
                    ApiVersionException _ => ((HttpStatusCode)ex.GetData()[ApiVersionException.StatusCode], ex.GetData()),
                    IdentityException _ => (HttpStatusCode.Unauthorized, ex.GetData()),
                    _ => (HttpStatusCode.InternalServerError, null)
                };

                responseStatusCode = statusCode;
                responseText       = JsonConvert.SerializeObject/*JsonSerializer.Serialize*/ (
                    new ErrorResponseModel <object>
                {
                    Message = statusCode == HttpStatusCode.InternalServerError ? "Operation failed." : ex.Message,
                    Data    = data
                }, NewtonsoftLogic.GetCammelCaseSettings());
            }

            context.Response.StatusCode  = (int)responseStatusCode;
            context.Response.ContentType = "application/json";

            await context.Response.WriteAsync(responseText);
        }
Ejemplo n.º 4
0
        public async void Create(AccountDTO accountDto)
        {
            accountDto.RoleName = accountDto.RoleName ?? "User";

            var userManager = this.UnitOfWork.UserManager;

            var user = await userManager.FindByEmailAsync(accountDto.Email);

            if (user != null)
            {
                throw IdentityException.UserIsExists(accountDto.Email);
            }

            var account = Mapper.Map <AccountDTO, Account>(accountDto);

            user = new AppUser
            {
                Email    = accountDto.Email,
                UserName = accountDto.Email,
                Account  = account
            };

            var userResult = userManager.Create(user, accountDto.Password);

            if (!userResult.Succeeded)
            {
                throw IdentityException.CreateingUserFailure(accountDto.Email);
            }

            var roleResult = UnitOfWork.UserManager.AddToRole(user.Id, accountDto.RoleName);

            if (!roleResult.Succeeded)
            {
                throw IdentityException.AddToRoleUserFailure(accountDto.Email, accountDto.RoleName);
            }
        }
        /// <summary>
        /// Creates Web Experience profile using portal branding and payment configuration.
        /// </summary>
        /// <param name="paymentConfig">The Payment configuration.</param>
        /// <param name="brandConfig">The branding configuration.</param>
        /// <param name="countryIso2Code">The locale code used by the web experience profile. Example-US.</param>
        /// <returns>The created web experience profile id.</returns>
        public static string CreateWebExperienceProfile(PaymentConfiguration paymentConfig, BrandingConfiguration brandConfig, string countryIso2Code)
        {
            try
            {
                Dictionary <string, string> configMap = new Dictionary <string, string>();
                configMap.Add("clientId", paymentConfig.ClientId);
                configMap.Add("clientSecret", paymentConfig.ClientSecret);
                configMap.Add("mode", paymentConfig.AccountType);
                configMap.Add("connectionTimeout", "120000");

                string accessToken = new OAuthTokenCredential(configMap).GetAccessToken();
                var    apiContext  = new APIContext(accessToken);
                apiContext.Config = configMap;

                // Pickup logo & brand name from branding configuration.
                // create the web experience profile.
                var profile = new WebProfile
                {
                    name         = Guid.NewGuid().ToString(),
                    presentation = new Presentation
                    {
                        brand_name  = brandConfig.OrganizationName,
                        logo_image  = brandConfig.HeaderImage?.ToString(),
                        locale_code = countryIso2Code
                    },
                    input_fields = new InputFields()
                    {
                        address_override = 1,
                        allow_note       = false,
                        no_shipping      = 1
                    },
                    flow_config = new FlowConfig()
                    {
                        landing_page_type = "billing"
                    }
                };

                var createdProfile = profile.Create(apiContext);

                // Now that new experience profile is created hence delete the older one.
                if (!string.IsNullOrWhiteSpace(paymentConfig.WebExperienceProfileId))
                {
                    try
                    {
                        WebProfile existingWebProfile = WebProfile.Get(apiContext, paymentConfig.WebExperienceProfileId);
                        existingWebProfile.Delete(apiContext);
                    }
                    catch
                    {
                    }
                }

                return(createdProfile.id);
            }
            catch (PayPalException paypalException)
            {
                if (paypalException is IdentityException)
                {
                    // thrown when API Context couldn't be setup.
                    IdentityException identityFailure = paypalException as IdentityException;
                    IdentityError     failureDetails  = identityFailure.Details;
                    if (failureDetails != null && failureDetails.error.ToLower() == "invalid_client")
                    {
                        throw new PartnerDomainException(ErrorCode.PaymentGatewayIdentityFailureDuringConfiguration).AddDetail("ErrorMessage", Resources.PaymentGatewayIdentityFailureDuringConfiguration);
                    }
                }

                // if this is not an identity exception rather some other issue.
                throw new PartnerDomainException(ErrorCode.PaymentGatewayFailure).AddDetail("ErrorMessage", paypalException.Message);
            }
        }
Ejemplo n.º 6
0
        internal static Exception IdentityNothingConfirmed()
        {
            IdentityException exception = new IdentityException(IdentityErrorCodes.IdentityNothingConfirmed);

            return(exception);
        }
Ejemplo n.º 7
0
        internal static Exception IdentityMobileEmailLoginNameAllNull()
        {
            IdentityException exception = new IdentityException(IdentityErrorCodes.IdentityMobileEmailLoginNameAllNull);

            return(exception);
        }
Ejemplo n.º 8
0
        internal static Exception AuthorizationRefreshTokenExpired()
        {
            IdentityException exception = new IdentityException(IdentityErrorCodes.AuthorizationRefreshTokenExpired);

            return(exception);
        }
 private async Task HandleIdentityExceptionAsync(IdentityException exception, HttpContext context)
 {
     context.Response.StatusCode  = StatusCodes.Status400BadRequest;
     context.Response.ContentType = "text/plain";
     await context.Response.WriteAsync(exception.Message);
 }