Esempio n. 1
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}");
            }
        }
Esempio n. 2
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}");
            }
        }
        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> 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();
            }
        }
        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 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 <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();
            }
        }
Esempio n. 9
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);
            }
        }
Esempio n. 10
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 <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}");
            }
        }
Esempio n. 12
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);
            }
        }
Esempio n. 13
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 <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);
        }
Esempio n. 15
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();
            }
        }
Esempio n. 16
0
 private static void ThrowIfError(PartnerManagementError errorCode, string message)
 {
     if (errorCode != PartnerManagementError.None)
     {
         throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(errorCode.ToString(), message));
     }
 }
        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();
            }
        }
 private static void ThrowIfError(CampaignServiceErrorCodes errorCode, string message)
 {
     if (errorCode != CampaignServiceErrorCodes.None)
     {
         throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(errorCode.ToString(), message));
     }
 }
        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);
            }
        }
Esempio n. 20
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;
            }
        }
Esempio n. 21
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}");
            }
        }
Esempio n. 22
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}");
            }
        }
        public async Task <AdminModel> RegisterPartnerAdminAsync([FromBody] AdminRegisterModel model)
        {
            try
            {
                var(error, admin) = await _adminsService.RegisterPartnerAdminAsync(model);

                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 LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(error.ToString()));
                }
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }
        }
Esempio n. 24
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));
        }
Esempio n. 25
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 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);
        }
        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}'");
        }
Esempio n. 28
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();
            }
        }
        public async Task <IActionResult> GetByCustomerAsync()
        {
            var customerId = _requestContext.UserId;

            var walletResult = await _walletOperationsService.GetCustomerWalletAsync(customerId);

            switch (walletResult.Error)
            {
            case WalletsErrorCodes.None:

                var linkedWalletTask = _publicWalletLinkingService.GetLinkedWalletAddressAsync(customerId);

                var tokensStatisticsTask =
                    _operationsHistoryClient.StatisticsApi.GetTokensStatisticsForCustomerAsync(
                        new TokensStatisticsForCustomerRequest {
                    CustomerId = customerId
                });

                await Task.WhenAll(linkedWalletTask, tokensStatisticsTask);

                Money18?linkedWalletBalance = null;

                if (linkedWalletTask.Result.Status == PublicAddressStatus.Linked)
                {
                    var balance =
                        await _ethereumBridgeClient.Wallets.GetBalanceAsync(linkedWalletTask.Result.PublicAddress);

                    linkedWalletBalance = balance.Amount;
                }

                var response = new WalletResponseModel
                {
                    Balance                    = walletResult.Balance.ToDisplayString(),
                    ExternalBalance            = linkedWalletBalance?.ToDisplayString(),
                    AssetSymbol                = walletResult.AssetSymbol,
                    TotalEarned                = tokensStatisticsTask.Result.EarnedAmount.ToDisplayString(),
                    TotalSpent                 = tokensStatisticsTask.Result.BurnedAmount.ToDisplayString(),
                    IsWalletBlocked            = walletResult.IsWalletBlocked,
                    PrivateWalletAddress       = walletResult.Address,
                    PublicWalletAddress        = linkedWalletTask.Result.PublicAddress,
                    PublicAddressLinkingStatus = linkedWalletTask.Result.Status.ToLinkingStatus(),
                    StakedBalance              = walletResult.StakedBalance.ToDisplayString(),
                    TransitAccountAddress      = _settingsService.GetTransitAccountAddress(),
                };
                return(Ok(new List <WalletResponseModel> {
                    response
                }));

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

            case WalletsErrorCodes.CustomerWalletMissing:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.CustomerWalletMissing);

            default:
                throw new InvalidOperationException(
                          $"Unexpected error during Transfer for {_requestContext.UserId} - {walletResult.Error}");
            }
        }
Esempio n. 30
0
        public async Task <IActionResult> ChangePasswordAsync([FromBody] ChangePasswordRequestModel model)
        {
            var customerId = _requestContext.UserId;

            var changePasswordResult = await _customerService.ChangePasswordAsync(customerId, model.Password);

            switch (changePasswordResult.Error)
            {
            case CustomerError.None:
                var customerInfo = await _customerService.GetCustomerInfoAsync(customerId, true);

                if (customerInfo == null)
                {
                    throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.InvalidCredentials);
                }

                var reLoginResult = await _customerManagementServiceClient.AuthApi.AuthenticateAsync(
                    new AuthenticateRequestModel
                {
                    Email         = customerInfo.Email,
                    Password      = model.Password,
                    LoginProvider = LoginProvider.Standard
                });

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

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

                case CustomerManagementError.InvalidLoginFormat:
                    throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.InvalidEmailFormat);

                case CustomerManagementError.InvalidPasswordFormat:
                    throw LykkeApiErrorException.Unauthorized(ApiErrorCodes.Service.InvalidPasswordFormat);

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

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

                default:
                    throw new InvalidOperationException($"Unexpected error during Authenticate for {customerInfo.Email.SanitizeEmail()} - {reLoginResult.Error}");
                }

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

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

            default:
                throw new InvalidOperationException($"Unexpected error during password change for {customerId} - {changePasswordResult}");
            }
        }