Exemplo n.º 1
0
        public async Task RedeemVoucherAsync([FromBody] VoucherRedemptionRequest request)
        {
            var requestModel = _mapper.Map <VoucherRedeptionModel>(request);

            requestModel.SellerCustomerId = Guid.Parse(_requestContext.UserId);
            var error = await _smartVouchersClient.VouchersApi.RedeemVoucherAsync(requestModel);

            switch (error)
            {
            case RedeemVoucherErrorCodes.None:
                return;

            case RedeemVoucherErrorCodes.VoucherNotFound:
                throw LykkeApiErrorException.NotFound(ApiErrorCodes.Service.SmartVoucherNotFound);

            case RedeemVoucherErrorCodes.WrongValidationCode:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.WrongSmartVoucherValidationCode);

            case RedeemVoucherErrorCodes.VoucherCampaignNotFound:
                throw LykkeApiErrorException.NotFound(ApiErrorCodes.Service.SmartVoucherCampaignNotFound);

            case RedeemVoucherErrorCodes.VoucherCampaignNotActive:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SmartVoucherCampaignNotActive);

            case RedeemVoucherErrorCodes.SellerCustomerIsNotALinkedPartner:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SellerCustomerIsNotALinkedPartner);

            case RedeemVoucherErrorCodes.SellerCustomerIsNotTheVoucherIssuer:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SellerCustomerIsNotTheVoucherIssuer);

            case RedeemVoucherErrorCodes.VoucherIsNotInCorrectStatusToBeRedeemed:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.VoucherIsNotInCorrectStatusToBeRedeemed);
            }
        }
        public async Task BlockWallet([FromQuery] string customerId)
        {
            try
            {
                var response = await _walletManagementClient.Api.CustomerWalletBlockAsync(new CustomerWalletBlockRequest
                {
                    CustomerId = customerId
                });

                if (response.Error != CustomerWalletBlockError.None)
                {
                    switch (response.Error)
                    {
                    case CustomerWalletBlockError.CustomerNotFound:
                        throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerNotFound);

                    case CustomerWalletBlockError.CustomerWalletAlreadyBlocked:
                        throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerWalletAlreadyBlocked);
                    }
                }
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }
            await _auditLogPublisher.PublishAuditLogAsync(_requestContext.UserId, customerId.ToJson(), ActionType.BlockWallet);
        }
Exemplo n.º 3
0
        public async Task <CustomerPublicWalletAddressResponse> GetPublicWalletAddressAsync(
            [Required][FromQuery] string customerId)
        {
            if (_settingsService.IsPublicBlockchainFeatureDisabled())
            {
                return new CustomerPublicWalletAddressResponse {
                           Status = PublicAddressStatus.NotLinked
                }
            }
            ;

            var customerPublicWalletAddressResponse =
                await _crossChainWalletLinkerClient.CustomersApi.GetLinkedPublicAddressAsync(Guid.Parse(customerId));

            if (customerPublicWalletAddressResponse.Error != PublicAddressError.None)
            {
                switch (customerPublicWalletAddressResponse.Error)
                {
                case PublicAddressError.InvalidCustomerId:
                    throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCustomerId);
                }
            }

            return(_mapper.Map <CustomerPublicWalletAddressResponse>(customerPublicWalletAddressResponse));
        }
Exemplo n.º 4
0
        public async Task <RegistrationResponseModel> GoogleRegisterAsync([FromBody] GoogleRegistrationRequestModel model)
        {
            var result = await _customerService.GoogleRegisterAsync(_mapper.Map <GoogleRegistrationRequestDto>(model));

            switch (result.Error)
            {
            case CustomerError.None:
                return(_mapper.Map <RegistrationResponseModel>(result));

            case CustomerError.AlreadyRegistered:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.LoginAlreadyInUse);

            case CustomerError.AlreadyRegisteredWithGoogle:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AlreadyRegisteredWithGoogle);

            case CustomerError.InvalidOrExpiredGoogleAccessToken:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidOrExpiredGoogleAccessToken);

            case CustomerError.InvalidCountryOfNationalityId:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCountryOfNationalityId);

            default:
                throw new InvalidOperationException($"Unexpected error during Register with access token {model.AccessToken} - {result.Error}");
            }
        }
Exemplo n.º 5
0
        public async Task UpdatePinCodeAsync([FromBody] PinRequestModel request)
        {
            var customerId = _requestContext.UserId;

            var result = await _credentialsClient.Api.UpdatePinAsync(new SetPinRequest
            {
                CustomerId = customerId,
                PinCode    = request.Pin
            });

            switch (result.Error)
            {
            case PinCodeErrorCodes.None:
                return;

            case PinCodeErrorCodes.CustomerDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerDoesNotExist);

            case PinCodeErrorCodes.InvalidPin:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidPin);

            case PinCodeErrorCodes.PinIsNotSet:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.PinIsNotSet);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 6
0
 private static void ThrowIfError(PartnerManagementError errorCode, string message)
 {
     if (errorCode != PartnerManagementError.None)
     {
         throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(errorCode.ToString(), message));
     }
 }
        public async Task <SmartVoucherDetailsResponse> GetSmartVoucherByShortCodeAsync([FromQuery] string voucherShortCode)
        {
            var voucherResponse = await _smartVouchersClient.VouchersApi.GetByShortCodeAsync(voucherShortCode);

            if (voucherResponse == null)
            {
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SmartVoucherNotFound);
            }

            var result = _mapper.Map <SmartVoucherDetailsResponse>(voucherResponse);

            var campaign = await _smartVouchersClient.CampaignsApi.GetByIdAsync(voucherResponse.CampaignId);

            if (campaign == null)
            {
                _log.Warning("Smart voucher campaign is missing for existing voucher", context: new { VoucherShortCode = voucherResponse.ShortCode, voucherResponse.CampaignId });
                return(result);
            }

            var partner = await _partnerManagementClient.Partners.GetByIdAsync(campaign.PartnerId);

            result.CampaignName   = campaign.GetContentValue(Localization.En, VoucherCampaignContentType.Name);
            result.PartnerId      = campaign.PartnerId;
            result.ExpirationDate = campaign.ToDate;
            result.PartnerName    = partner?.Name;
            result.ImageUrl       = campaign.GetContentValue(Localization.En, VoucherCampaignContentType.ImageUrl);
            result.Description    = campaign.GetContentValue(Localization.En, VoucherCampaignContentType.Description);
            result.Price          = campaign.VoucherPrice;
            result.Currency       = campaign.Currency;

            return(result);
        }
        public async Task <AdminModel> CreateAdminAsync([FromBody] AdminCreateModel model)
        {
            var(error, admin) = await _adminsService.RegisterAsync(
                model.Email,
                model.Password,
                model.PhoneNumber,
                model.FirstName,
                model.LastName,
                model.Company,
                model.Department,
                model.JobTitle);

            switch (error)
            {
            case AdminServiceCreateResponseError.None:
                return(_mapper.Map <AdminModel>(admin));

            case AdminServiceCreateResponseError.AlreadyRegistered:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminAlreadyRegistered);

            case AdminServiceCreateResponseError.InvalidEmailOrPasswordFormat:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailOrPasswordFormat);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordModel model)
        {
            var(adminServiceResponseError, admin) = await _adminsService.GetAsync(_requestContext.UserId);

            var email = admin.Email;

            var error = await _adminsService.ChangePasswordAsync(email, model.CurrentPassword, model.NewPassword);

            if (error == AdminChangePasswordErrorCodes.None)
            {
                await _auditLogPublisher.PublishAuditLogAsync(_requestContext.UserId, null, ActionType.ChangeAdminPassword);

                return(Ok());
            }

            switch (error)
            {
            case AdminChangePasswordErrorCodes.AdminNotActive:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotActive);

            case AdminChangePasswordErrorCodes.LoginNotFound:
            case AdminChangePasswordErrorCodes.PasswordMismatch:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCredentials);

            case AdminChangePasswordErrorCodes.InvalidEmailOrPasswordFormat:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailOrPasswordFormat);

            case AdminChangePasswordErrorCodes.NewPasswordInvalid:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.NewPasswordInvalid);

            default:
                throw new InvalidOperationException($"Unexpected error during change password for {email.SanitizeEmail()} - {error}");
            }
        }
        public async Task GeneratePhoneVerificationAsync()
        {
            var customerId = _requestContext.UserId;

            var result = await _customerManagementClient.PhonesApi.RequestVerificationAsync(
                new VerificationCodeRequestModel
            {
                CustomerId = customerId
            });

            switch (result.Error)
            {
            case VerificationCodeError.None:
                return;

            case VerificationCodeError.AlreadyVerified:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.PhoneIsAlreadyVerified);

            case VerificationCodeError.CustomerDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerDoesNotExist);

            case VerificationCodeError.ReachedMaximumRequestForPeriod:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ReachedMaximumRequestForPeriod);

            case VerificationCodeError.CustomerPhoneIsMissing:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerPhoneIsMissing);

            default:
                throw new InvalidOperationException($"Unexpected error during GeneratePhoneVerificationAsync for {customerId} - {result}");
            }
        }
        public async Task <RealEstatePropertiesResponse> GetRealEstatePropertiesAsync([FromQuery] Guid spendRuleId)
        {
            var customerId = _requestContext.UserId;

            var(response, error) = await _realEstateResponseFormatter.FormatAsync(customerId, spendRuleId.ToString());

            switch (error)
            {
            case RealEstateErrorCodes.None:
                return(response);

            case RealEstateErrorCodes.CustomerProfileDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerProfileDoesNotExist);

            case RealEstateErrorCodes.SalesForceError:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SalesForceError);

            case RealEstateErrorCodes.ConversionRateNotFound:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ConversionRateNotFound);

            case RealEstateErrorCodes.SpendRuleNotFound:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SpendRuleNotFound);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public async Task <AdminModel> RegisterPartnerAdminAsync([FromBody] AdminRegisterModel model)
        {
            try
            {
                var(error, admin) = await _adminsService.RegisterPartnerAdminAsync(model);

                if (error == AdminServiceCreateResponseError.None)
                {
                    model.Password = null;
                    model.Email    = model.Email.SanitizeEmail();
                    await _auditLogPublisher.PublishAuditLogAsync(admin.Id, model.ToJson(), ActionType.PartnerAdminCreate);

                    return(_mapper.Map <AdminModel>(admin));
                }

                switch (error)
                {
                case AdminServiceCreateResponseError.AlreadyRegistered:
                    throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminAlreadyRegistered);

                case AdminServiceCreateResponseError.InvalidEmailOrPasswordFormat:
                    throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailOrPasswordFormat);

                default:
                    throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(error.ToString()));
                }
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }
        }
        public async Task <AdminModel> ResetPasswordAsync([FromBody] AdminResetPasswordModel model)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.AdminUsers);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (model.AdminId != _requestContext.UserId)
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var(error, admin) = await _adminsService.ResetPasswordAsync(model.AdminId);

            if (error == AdminResetPasswordErrorCodes.None)
            {
                await _auditLogPublisher.PublishAuditLogAsync(_requestContext.UserId, model.ToJson(), ActionType.ResetAdminPassword);

                return(_mapper.Map <AdminModel>(admin));
            }
            switch (error)
            {
            case AdminResetPasswordErrorCodes.AdminUserDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotFound);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public async Task <AdminModel> GetAdminByIdAsync([FromQuery][Required] Guid adminUserId)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.AdminUsers);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (adminUserId != Guid.Parse(_requestContext.UserId))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var(error, admin) = await _adminsService.GetAsync(adminUserId.ToString());

            switch (error)
            {
            case AdminServiceResponseError.None:
                return(_mapper.Map <AdminModel>(admin));

            case AdminServiceResponseError.AdminUserDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotFound);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public async Task <ConfirmReferralHotelResponse> ConfirmReferralHotelAsync(ConfirmReferralHotelRequest model)
        {
            var result = await _referralClient.ReferralHotelsApi.ConfirmAsync(new ReferralHotelConfirmRequest
            {
                ConfirmationToken = model.ConfirmationCode
            });

            switch (result.ErrorCode)
            {
            case ReferralHotelConfirmErrorCode.None:
                var customerInfo = await _customerService.GetCustomerInfoAsync(result.HotelReferral.ReferrerId);

                if (customerInfo == null)
                {
                    throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ReferralNotFound);
                }

                return(new ConfirmReferralHotelResponse
                {
                    Email = customerInfo.Email
                });

            case ReferralHotelConfirmErrorCode.ReferralDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ReferralNotFound);

            case ReferralHotelConfirmErrorCode.ReferralExpired:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ReferralExpired);

            default:
                throw new InvalidOperationException($"Unexpected error occured: {model.ConfirmationCode} - {result}");
            }
        }
Exemplo n.º 16
0
        public async Task <IActionResult> ChangePasswordAnonymous([FromBody] ChangePasswordAnonymousModel model)
        {
            if (!model.Email.IsValidEmailAndRowKey())
            {
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailFormat);
            }

            var error = await _adminsService.ChangePasswordAsync(model.Email, model.CurrentPassword, model.NewPassword);

            switch (error)
            {
            case AdminChangePasswordErrorCodes.None:
                return(Ok());

            case AdminChangePasswordErrorCodes.AdminNotActive:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotActive);

            case AdminChangePasswordErrorCodes.LoginNotFound:
            case AdminChangePasswordErrorCodes.PasswordMismatch:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCredentials);

            case AdminChangePasswordErrorCodes.InvalidEmailOrPasswordFormat:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailOrPasswordFormat);

            case AdminChangePasswordErrorCodes.NewPasswordInvalid:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.NewPasswordInvalid);

            default:
                throw new InvalidOperationException($"Unexpected error during change password for {model.Email.SanitizeEmail()} - {error}");
            }
        }
 private static void ThrowIfError(CampaignServiceErrorCodes errorCode, string message)
 {
     if (errorCode != CampaignServiceErrorCodes.None)
     {
         throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(errorCode.ToString(), message));
     }
 }
Exemplo n.º 18
0
        public async Task <IActionResult> Login([FromBody] LoginModel model)
        {
            if (!model.Email.IsValidEmailAndRowKey())
            {
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailFormat);
            }

            var(error, admin, token) = await _adminsService.AuthenticateAsync(model.Email, model.Password);

            switch (error)
            {
            case AdminServiceCreateResponseError.None:
                return(Ok(new LoginResponseModel
                {
                    Token = token,
                    AdminUser = _mapper.Map <AdminModel>(admin)
                }));

            case AdminServiceCreateResponseError.AdminNotActive:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotActive);

            case AdminServiceCreateResponseError.LoginNotFound:
            case AdminServiceCreateResponseError.PasswordMismatch:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCredentials);

            case AdminServiceCreateResponseError.AdminEmailIsNotVerified:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminEmailIsNotVerified);

            case AdminServiceCreateResponseError.InvalidEmailOrPasswordFormat:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailOrPasswordFormat);

            default:
                throw new InvalidOperationException($"Unexpected error during Authenticate for {model.Email.SanitizeEmail()} - {error}");
            }
        }
        public async Task <ReserveSmartVoucherResponse> ReserveSmartVoucherAsync([FromBody] ReserveSmartVoucherRequest request)
        {
            var customerId = Guid.Parse(_requestContext.UserId);
            var result     = await _smartVouchersClient.VouchersApi.ReserveVoucherAsync(new VoucherProcessingModel
            {
                CustomerId        = customerId,
                VoucherCampaignId = request.SmartVoucherCampaignId
            });

            switch (result.ErrorCode)
            {
            case ProcessingVoucherErrorCodes.None:
                return(new ReserveSmartVoucherResponse {
                    PaymentUrl = result.PaymentUrl
                });

            case ProcessingVoucherErrorCodes.VoucherCampaignNotFound:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SmartVoucherCampaignNotFound);

            case ProcessingVoucherErrorCodes.VoucherCampaignNotActive:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SmartVoucherCampaignNotActive);

            case ProcessingVoucherErrorCodes.NoAvailableVouchers:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.NoAvailableVouchers);

            case ProcessingVoucherErrorCodes.InvalidPartnerPaymentConfiguration:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.PaymentProviderError);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> GetHistoryAsync(string assetId, TimeInterval timeInterval)
        {
            if (string.IsNullOrWhiteSpace(assetId))
            {
                throw FieldShouldNotBeEmpty(nameof(assetId));
            }

            if (timeInterval == TimeInterval.Unspecified)
            {
                throw FieldShouldBeSpecified(nameof(timeInterval));
            }

            IList <HistoryElement> result;

            try
            {
                result = await _indicesFacadeClient.Api.GetHistoryAsync(assetId, timeInterval);
            }
            catch
            {
                throw LykkeApiErrorException.NotFound(LykkeApiErrorCodes.Service.AssetNotFound);
            }

            return(Ok(result));
        }
Exemplo n.º 21
0
        public async Task LinkToPartnerAsync([FromBody] Models.PartnersLinking.LinkPartnerRequest request)
        {
            var result = await _partnerManagementClient.Linking.LinkPartnerAsync(new LinkPartnerRequest
            {
                PartnerCode        = request.PartnerCode,
                PartnerLinkingCode = request.PartnerLinkingCode,
                CustomerId         = Guid.Parse(_requestContext.UserId),
            });

            switch (result.Error)
            {
            case PartnerLinkingErrorCode.None:
                break;

            case PartnerLinkingErrorCode.CustomerDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerDoesNotExist);

            case PartnerLinkingErrorCode.CustomerAlreadyLinked:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerAlreadyLinkedToAPartner);

            case PartnerLinkingErrorCode.PartnerLinkingInfoDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.PartnerLinkingInfoDoesNotExist);

            case PartnerLinkingErrorCode.PartnerLinkingInfoDoesNotMatch:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.PartnerLinkingInfoDoesNotMatch);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 22
0
        public async Task <IActionResult> GoogleLogin([FromBody] GoogleLoginRequestModel model)
        {
            var result = await _authService.GoogleAuthenticateAsync(model.AccessToken);

            switch (result.Error)
            {
            case CustomerError.None:
                return(Ok(_mapper.Map <LoginResponseModel>(result)));

            case CustomerError.LoginNotFound:
                throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.InvalidCredentials);

            case CustomerError.LoginExistsWithDifferentProvider:
                throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.LoginExistsWithDifferentProvider);

            case CustomerError.InvalidOrExpiredGoogleAccessToken:
                throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.InvalidOrExpiredGoogleAccessToken);

            case CustomerError.CustomerBlocked:
                throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.CustomerBlocked);

            case CustomerError.CustomerProfileDeactivated:
                throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.CustomerIsNotActive);

            default:
                throw new InvalidOperationException(
                          $"Unexpected error during Authenticate with access token {model.AccessToken} - {result.Error}");
            }
        }
Exemplo n.º 23
0
        public async Task GenerateResetPasswordLink([FromBody] GenerateResetPasswordLinkRequestModel model)
        {
            if (!model.Email.IsValidEmailAndRowKey())
            {
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidEmailFormat);
            }

            var result = await _customerManagementServiceClient.CustomersApi.GenerateResetPasswordLink(new GenerateResetPasswordRequest { Email = model.Email });

            switch (result.Error)
            {
            case PasswordResetError.None:
                return;

            case PasswordResetError.NoCustomerWithSuchEmail:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.NoCustomerWithSuchEmail);

            case PasswordResetError.ThereIsNoIdentifierForThisCustomer:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ThereIsNoIdentifierForThisCustomer);

            case PasswordResetError.ReachedMaximumRequestForPeriod:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.ReachedMaximumRequestForPeriod);

            case PasswordResetError.CustomerIsNotVerified:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerIsNotVerified);

            default:
                throw new InvalidOperationException($"Unexpected error during GenerateResetPasswordLink for {model.Email.SanitizeEmail()} - {result}");
            }
        }
Exemplo n.º 24
0
        public async Task <IActionResult> SetupGoogle2FaRequest()
        {
            try
            {
                if (await _confirmationCodesClient.Google2FaClientHasSetupAsync(_requestContext.ClientId))
                {
                    throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.SecondFactorAlreadySetup);
                }

                var resp = await _confirmationCodesClient.Google2FaRequestSetupAsync(
                    new RequestSetupGoogle2FaRequest { ClientId = _requestContext.ClientId });

                return(Ok(new GoogleSetupRequestResponse {
                    ManualEntryKey = resp.ManualEntryKey
                }));
            }
            catch (ApiException e)
            {
                switch (e.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                    throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.InconsistentState);

                case HttpStatusCode.Forbidden:
                    throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.SecondFactorSetupInProgress);
                }

                throw;
            }
        }
        public async Task VerifyEmailAsync([FromBody] EmailVerificationRequest model)
        {
            var result = await _adminManagementServiceClient.AdminsApi.ConfirmEmailAsync(new VerificationCodeConfirmationRequestModel
            {
                VerificationCode = model.VerificationCode
            });

            if (result.Error != VerificationCodeError.None)
            {
                switch (result.Error)
                {
                case VerificationCodeError.AlreadyVerified:
                    _log.Warning(result.Error.ToString());
                    throw LykkeApiErrorException.BadRequest(
                              new LykkeApiErrorCode("EmailIsAlreadyVerified", "Email has been already verified"));

                case VerificationCodeError.VerificationCodeDoesNotExist:
                    _log.Warning(result.Error.ToString());
                    throw LykkeApiErrorException.BadRequest(
                              new LykkeApiErrorCode(result.Error.ToString(), "Verification code does not exist"));

                case VerificationCodeError.VerificationCodeMismatch:
                    _log.Warning(result.Error.ToString());
                    throw LykkeApiErrorException.BadRequest(
                              new LykkeApiErrorCode(result.Error.ToString(), "Verification code mismatch"));

                case VerificationCodeError.VerificationCodeExpired:
                    _log.Warning(result.Error.ToString());
                    throw LykkeApiErrorException.BadRequest(
                              new LykkeApiErrorCode(result.Error.ToString(), "Verification code has expired"));
                }
            }

            _log.Info($"Email verification success with code '{model.VerificationCode}'");
        }
Exemplo n.º 26
0
        public async Task <IActionResult> ConfirmGoogle2FaSetup()
        {
            try
            {
                if (await _confirmationCodesClient.Google2FaClientHasSetupAsync(_requestContext.ClientId))
                {
                    throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.SecondFactorAlreadySetup);
                }

                IPersonalData client = await _personalDataService.GetAsync(_requestContext.ClientId);

                SmsConfirmationResponse smsRequestResult = await _confirmationCodesClient.SendSmsConfirmCodeAsync(
                    new SmsConfirmCodeRequest
                {
                    ClientId  = _requestContext.ClientId,
                    Phone     = client.ContactPhone,
                    Operation = ConfirmOperations.Google2FaSendSms
                });

                return(Ok(smsRequestResult));
            }
            catch (ApiException e)
            {
                switch (e.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                    throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.InconsistentState);

                case HttpStatusCode.Forbidden:
                    throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.MaxAttemptsReached);
                }

                throw;
            }
        }
Exemplo n.º 27
0
        public async Task <BalanceModel> GetBalanceAsync([FromQuery] string customerId)
        {
            var asset = _settingsService.GetTokenName();
            var isCustomerIdValidGuid = Guid.TryParse(customerId, out var customerIdAsGuid);

            if (!isCustomerIdValidGuid)
            {
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCustomerId);
            }

            var response = await _pbfClient.CustomersApi.GetBalanceAsync(customerIdAsGuid);

            if (response.Error != CustomerBalanceError.None)
            {
                switch (response.Error)
                {
                case CustomerBalanceError.CustomerWalletMissing:
                    throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerWalletNotFound);

                case CustomerBalanceError.InvalidCustomerId:
                    throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.InvalidCustomerId);
                }
            }

            return(new BalanceModel
            {
                Asset = asset,
                Amount = response.Total
            });
        }
        public async Task UpdatePartnerAsync([FromBody] PartnerUpdateRequest request)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.ProgramPartners);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                var existingPartner = await _partnerManagementClient.Partners.GetByIdAsync(request.Id);

                // filter data for current _requestContext.UserId
                if (existingPartner != null &&
                    existingPartner.CreatedBy != Guid.Parse(_requestContext.UserId))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var requestModel = _mapper.Map <PartnerUpdateModel>(request);

            PartnerUpdateResponse response;

            try
            {
                response = await _partnerManagementClient.Partners.UpdateAsync(requestModel);
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }

            ThrowIfError(response.ErrorCode, response.ErrorMessage);
        }
Exemplo n.º 29
0
        public async Task UnblockWallet([FromQuery] string customerId)
        {
            try
            {
                var response = await _walletManagementClient.Api.CustomerWalletUnblockAsync(new CustomerWalletUnblockRequest
                {
                    CustomerId = customerId
                });

                if (response.Error != CustomerWalletUnblockError.None)
                {
                    switch (response.Error)
                    {
                    case CustomerWalletUnblockError.CustomerNotFound:
                        throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerNotFound);

                    case CustomerWalletUnblockError.CustomerWalletNotBlocked:
                        throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerWalletNotBlocked);
                    }
                }
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }
        }
        public async Task <IActionResult> RegisterInstallation([FromBody] PushRegistrationModel model)
        {
            var clientId = _requestContext.ClientId;

            var client = await _clientAccountClient.ClientAccountInformation.GetClientByIdAsync(clientId);

            try
            {
                InstallationResponse response = await _pushNotificationsClient.Installations.RegisterAsync(new InstallationModel
                {
                    ClientId       = clientId,
                    InstallationId = model.InstallationId,
                    NotificationId = client.NotificationsId,
                    Platform       = model.Platform,
                    PushChannel    = model.PushChannel
                });

                return(Ok(response));
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.InvalidInput);
            }
        }