diff --git a/src/main/java/biz/nynja/account/components/PendingAccountValidator.java b/src/main/java/biz/nynja/account/components/PendingAccountValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..09c4aae6be2b18492f4da27dd1f97cc96a426c7a --- /dev/null +++ b/src/main/java/biz/nynja/account/components/PendingAccountValidator.java @@ -0,0 +1,54 @@ +/** + * Copyright (C) 2018 Nynja Inc. All rights reserved. + */ +package biz.nynja.account.components; + +import org.springframework.stereotype.Service; + +import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; +import biz.nynja.account.grpc.CreatePendingAccountRequest; +import biz.nynja.account.grpc.ErrorResponse.Cause; + +@Service +public class PendingAccountValidator { + + private Validator validator; + + public PendingAccountValidator(Validator validator) { + this.validator = validator; + } + + public Cause validateCreatePendingAccountRequest(CreatePendingAccountRequest request) { + return validator.validateAuthProvider(request.getAuthenticationType(), request.getAuthenticationProvider()); + } + + public Cause validateCompletePendingAccountCreationRequest(CompletePendingAccountCreationRequest request) { + if (request.getAccountId() == null || request.getAccountId().trim().isEmpty()) { + return Cause.MISSING_ACCOUNT_ID; + } + + if (request.getFirstName() != null && request.getFirstName().trim().isEmpty()) { + return Cause.MISSING_FIRST_NAME; + } else if (!validator.isFirstNameValid(request.getFirstName())) { + return Cause.INVALID_FIRST_NAME; + } + + if (request.getLastName() != null && !request.getLastName().trim().isEmpty() + && !validator.isLastNameValid(request.getLastName())) { + return Cause.INVALID_LAST_NAME; + } + + if (request.getUsername() != null && !request.getUsername().trim().isEmpty() + && !validator.isUsernameValid(request.getUsername())) { + return Cause.USERNAME_INVALID; + } + + if (request.getAccountName() != null && !request.getAccountName().trim().isEmpty() + && !validator.isAccountNameValid(request.getAccountName())) { + return Cause.ACCOUNT_NAME_INVALID; + } + + return null; + } + +} diff --git a/src/main/java/biz/nynja/account/components/Validator.java b/src/main/java/biz/nynja/account/components/Validator.java index e78ab54d2cff6548a4a9939a011387b3ea933531..c48ff7dbb976c2806d2babd64097421c92f7f06c 100644 --- a/src/main/java/biz/nynja/account/components/Validator.java +++ b/src/main/java/biz/nynja/account/components/Validator.java @@ -3,48 +3,30 @@ */ package biz.nynja.account.components; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.time.DateTimeException; import java.time.LocalDate; -import java.util.HashMap; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.annotation.PostConstruct; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; -import com.google.i18n.phonenumbers.NumberParseException; -import com.google.i18n.phonenumbers.PhoneNumberUtil; -import com.google.i18n.phonenumbers.Phonenumber; -import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; + +import biz.nynja.account.grpc.AddAuthenticationProviderRequest; import biz.nynja.account.grpc.AuthenticationType; -import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; import biz.nynja.account.grpc.ContactDetails; import biz.nynja.account.grpc.ContactType; -import biz.nynja.account.grpc.CreatePendingAccountRequest; import biz.nynja.account.grpc.Date; import biz.nynja.account.grpc.DeleteAuthenticationProviderRequest; import biz.nynja.account.grpc.ErrorResponse.Cause; import biz.nynja.account.grpc.UpdateAccountRequest; import biz.nynja.account.grpc.UpdateProfileRequest; -import biz.nynja.account.models.CountryInfo; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; - import biz.nynja.account.phone.PhoneNumberValidator; -import biz.nynja.account.validation.Validation; -import biz.nynja.account.validation.ValidationError; -import biz.nynja.account.grpc.AddAuthenticationProviderRequest; -import biz.nynja.account.grpc.AddContactInfoRequest; /** * Component which contains all validation methods. @@ -63,10 +45,10 @@ public class Validator { private static final int MAX_LAST_NAME_LENGTH = 32; private PhoneNumberValidator phoneValidator; - + public Validator(PhoneNumberValidator phoneValidator) { this.phoneValidator = phoneValidator; - + } public boolean isUsernameValid(String username) { @@ -89,10 +71,10 @@ public class Validator { logger.debug("Checking email: {}", email); try { - InternetAddress emailAddr = new InternetAddress(email); - emailAddr.validate(); + InternetAddress emailAddr = new InternetAddress(email); + emailAddr.validate(); } catch (AddressException ex) { - result = false; + result = false; } logger.debug("Email: {} is valid: {}", email, result); return result; @@ -119,9 +101,9 @@ public class Validator { } public boolean isValidUsername(String username) { - if(username == null) { - return false; - } + if (username == null) { + return false; + } return username.matches("[a-zA-Z0-9_]{1,32}"); } @@ -196,39 +178,6 @@ public class Validator { return Optional.empty(); } - public Cause validateCreatePendingAccountRequest(CreatePendingAccountRequest request) { - return validateAuthProvider(request.getAuthenticationType(), request.getAuthenticationProvider()); - } - - public Cause validateCompletePendingAccountCreationRequest(CompletePendingAccountCreationRequest request) { - if (request.getAccountId() == null || request.getAccountId().trim().isEmpty()) { - return Cause.MISSING_ACCOUNT_ID; - } - - if (request.getFirstName() != null && request.getFirstName().trim().isEmpty()) { - return Cause.MISSING_FIRST_NAME; - } else if (!isFirstNameValid(request.getFirstName())) { - return Cause.INVALID_FIRST_NAME; - } - - if (request.getLastName() != null && !request.getLastName().trim().isEmpty() - && !isLastNameValid(request.getLastName())) { - return Cause.INVALID_LAST_NAME; - } - - if (request.getUsername() != null && !request.getUsername().trim().isEmpty() - && !isUsernameValid(request.getUsername())) { - return Cause.USERNAME_INVALID; - } - - if (request.getAccountName() != null && !request.getAccountName().trim().isEmpty() - && !isAccountNameValid(request.getAccountName())) { - return Cause.ACCOUNT_NAME_INVALID; - } - - return null; - } - public boolean validateBirthdayIsSet(Date birthday) { return (birthday != null && birthday.getYear() != 0 && birthday.getMonth() != 0 && birthday.getDay() != 0); } diff --git a/src/main/java/biz/nynja/account/grid/ag/AdminServiceImpl.java b/src/main/java/biz/nynja/account/grid/ag/AdminServiceImpl.java index 211b1fcbcadbe174ed03f458994b36e3deffc77b..535bd2cbc8425b4da8a8290f3e50cfd1a4c01a9a 100644 --- a/src/main/java/biz/nynja/account/grid/ag/AdminServiceImpl.java +++ b/src/main/java/biz/nynja/account/grid/ag/AdminServiceImpl.java @@ -1,14 +1,24 @@ +/** + * Copyright (C) 2018 Nynja Inc. All rights reserved. + */ package biz.nynja.account.grid.ag; import org.lognet.springboot.grpc.GRpcService; -import org.springframework.beans.factory.annotation.Autowired; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import biz.nynja.account.admin.grpc.AccountsAdminResponse; import biz.nynja.account.admin.grpc.AccountsCount; import biz.nynja.account.admin.grpc.AdminAccountServiceGrpc; +import biz.nynja.account.admin.grpc.CreateAccountRequest; import biz.nynja.account.admin.grpc.EmptyRequest; import biz.nynja.account.admin.grpc.GetAllAccountsRequest; +import biz.nynja.account.grpc.AccountResponse; +import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; +import biz.nynja.account.grpc.CreatePendingAccountRequest; +import biz.nynja.account.grpc.CreatePendingAccountResponse; import biz.nynja.account.repositories.AccountRepository; +import biz.nynja.account.services.decomposition.AccountCreator; import io.grpc.stub.StreamObserver; /** @@ -19,14 +29,17 @@ import io.grpc.stub.StreamObserver; @GRpcService public class AdminServiceImpl extends AdminAccountServiceGrpc.AdminAccountServiceImplBase { - private AgGridService agGridService; + private static final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class); + private AgGridService agGridService; private AccountRepository accountRepository; + private final AccountCreator accountCreator; - @Autowired - public AdminServiceImpl(AgGridService agGridService, AccountRepository accountRepository) { + public AdminServiceImpl(AgGridService agGridService, AccountRepository accountRepository, + AccountCreator accountCreator) { this.agGridService = agGridService; this.accountRepository = accountRepository; + this.accountCreator = accountCreator; } @Override @@ -45,4 +58,35 @@ public class AdminServiceImpl extends AdminAccountServiceGrpc.AdminAccountServic responseObserver.onNext(AccountsCount.newBuilder().setCount(Math.toIntExact(count)).build()); responseObserver.onCompleted(); } + + @Override + public void createAccount(CreateAccountRequest request, StreamObserver responseObserver) { + + logger.info("Creating account from admin console..."); + logger.debug("Creating account from admin console: {} ...", request); + + CreatePendingAccountRequest pendingAccountRequest = CreatePendingAccountRequest.newBuilder() + .setAuthenticationProvider(request.getAuthenticationProvider()) + .setAuthenticationType(request.getAuthenticationType()).build(); + CreatePendingAccountResponse pendingAccountResponse = accountCreator + .retrieveCreatePendingAccountResponse(pendingAccountRequest); + + if (pendingAccountResponse.hasError()) { + responseObserver.onNext(AccountResponse.newBuilder().setError(pendingAccountResponse.getError()).build()); + responseObserver.onCompleted(); + return; + } + + CompletePendingAccountCreationRequest completePendingAccount = CompletePendingAccountCreationRequest + .newBuilder().setAccountId(pendingAccountResponse.getPendingAccountDetails().getAccountId()) + .setAvatar(request.getAvatar()).setAccountMark(request.getAccountMark()) + .setAccountName(request.getAccountName()).setFirstName(request.getFirstName()) + .setLastName(request.getLastName()).setUsername(request.getUsername()) + .addAllRoles(request.getRolesList()).setAccessStatus(request.getAccessStatus()) + .setQrCode(request.getQrCode()).build(); + + AccountResponse response = accountCreator.retrieveCompletePendingAccountResponse(completePendingAccount); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } } diff --git a/src/main/java/biz/nynja/account/grid/ag/AgGridService.java b/src/main/java/biz/nynja/account/grid/ag/AgGridService.java index a09d1686039be00edef87687bf7510030713fc8e..19134273e8fe8548fcdf1525b284760d8c355562 100644 --- a/src/main/java/biz/nynja/account/grid/ag/AgGridService.java +++ b/src/main/java/biz/nynja/account/grid/ag/AgGridService.java @@ -1,3 +1,6 @@ +/** + * Copyright (C) 2018 Nynja Inc. All rights reserved. + */ package biz.nynja.account.grid.ag; import java.util.ArrayList; diff --git a/src/main/java/biz/nynja/account/models/Account.java b/src/main/java/biz/nynja/account/models/Account.java index 6920d9d8f2bb71810aedf95da5031a13ec409d71..a5f54e2133569a3a50457691d1562d3316dad099 100644 --- a/src/main/java/biz/nynja/account/models/Account.java +++ b/src/main/java/biz/nynja/account/models/Account.java @@ -29,7 +29,7 @@ public class Account { private String authenticationProviderType; private String firstName; private String lastName; - private ByteBuffer avatar; + private String avatar; private String accountName; private String username; private String qrCode; @@ -96,11 +96,11 @@ public class Account { this.lastName = lastName; } - public ByteBuffer getAvatar() { + public String getAvatar() { return avatar; } - public void setAvatar(ByteBuffer avatar) { + public void setAvatar(String avatar) { this.avatar = avatar; } @@ -354,7 +354,7 @@ public class Account { builder.setQrCode(getQrCode()); } if (getAvatar() != null) { - builder.setAvatar(com.google.protobuf.ByteString.copyFrom(avatar)); + builder.setAvatar(avatar); } if (getRoles() != null) { for (String role : getRoles()) { diff --git a/src/main/java/biz/nynja/account/models/AccountByAuthenticationProvider.java b/src/main/java/biz/nynja/account/models/AccountByAuthenticationProvider.java index bdfa04f39265090c0f3d7ae95c00aa643285bd2b..92788ccaef19504bd9a28528340f57c9bf9f317b 100644 --- a/src/main/java/biz/nynja/account/models/AccountByAuthenticationProvider.java +++ b/src/main/java/biz/nynja/account/models/AccountByAuthenticationProvider.java @@ -22,7 +22,7 @@ public class AccountByAuthenticationProvider { private String authenticationProviderType; private String firstName; private String lastName; - private ByteBuffer avatar; + private String avatar; private String accountName; private String username; private Long creationTimestamp; @@ -89,11 +89,11 @@ public class AccountByAuthenticationProvider { this.lastName = lastName; } - public ByteBuffer getAvatar() { + public String getAvatar() { return avatar; } - public void setAvatar(ByteBuffer avatar) { + public void setAvatar(String avatar) { this.avatar = avatar; } @@ -339,7 +339,7 @@ public class AccountByAuthenticationProvider { builder.setQrCode(getQrCode()); } if (avatar != null) { - builder.setAvatar(com.google.protobuf.ByteString.copyFrom(avatar)); + builder.setAvatar(avatar); } if (contactsInfo != null) { for (ContactInfo c : contactsInfo) { diff --git a/src/main/java/biz/nynja/account/models/AccountByProfileId.java b/src/main/java/biz/nynja/account/models/AccountByProfileId.java index fe37f192bae897b104380175bfcc66cecc0d36c0..adf01aa7f6252371c72fde5d398b8d77fe827820 100644 --- a/src/main/java/biz/nynja/account/models/AccountByProfileId.java +++ b/src/main/java/biz/nynja/account/models/AccountByProfileId.java @@ -23,7 +23,7 @@ public class AccountByProfileId { private String authenticationProviderType; private String firstName; private String lastName; - private ByteBuffer avatar; + private String avatar; private String accountName; private String username; private Long creationTimestamp; @@ -90,11 +90,11 @@ public class AccountByProfileId { this.lastName = lastName; } - public ByteBuffer getAvatar() { + public String getAvatar() { return avatar; } - public void setAvatar(ByteBuffer avatar) { + public void setAvatar(String avatar) { this.avatar = avatar; } @@ -341,7 +341,7 @@ public class AccountByProfileId { builder.setQrCode(getQrCode()); } if (getAvatar() != null) { - builder.setAvatar(com.google.protobuf.ByteString.copyFrom(avatar)); + builder.setAvatar(avatar); } if (getContactsInfo() != null) { for (ContactInfo c : contactsInfo) { diff --git a/src/main/java/biz/nynja/account/models/AccountByQrCode.java b/src/main/java/biz/nynja/account/models/AccountByQrCode.java index f80d84f263caaed54a51c501be434a515a3972a2..e2b8f689697bb560a454c568d5aa8d295cea8e29 100644 --- a/src/main/java/biz/nynja/account/models/AccountByQrCode.java +++ b/src/main/java/biz/nynja/account/models/AccountByQrCode.java @@ -21,7 +21,7 @@ public class AccountByQrCode { private String authenticationProviderType; private String firstName; private String lastName; - private ByteBuffer avatar; + private String avatar; private String accountName; private String username; private Long creationTimestamp; @@ -87,11 +87,11 @@ public class AccountByQrCode { this.lastName = lastName; } - public ByteBuffer getAvatar() { + public String getAvatar() { return avatar; } - public void setAvatar(ByteBuffer avatar) { + public void setAvatar(String avatar) { this.avatar = avatar; } @@ -322,7 +322,7 @@ public class AccountByQrCode { builder.setQrCode(getQrCode()); } if (getAvatar() != null) { - builder.setAvatar(com.google.protobuf.ByteString.copyFrom(avatar)); + builder.setAvatar(avatar); } if (getRoles() != null) { for (String role : getRoles()) { diff --git a/src/main/java/biz/nynja/account/models/AccountByUsername.java b/src/main/java/biz/nynja/account/models/AccountByUsername.java index ed40828a67ef508733e32e18410c77d9f4711d8a..52a1a12c1c754d9778a47c42cc8845f4619cdfe1 100644 --- a/src/main/java/biz/nynja/account/models/AccountByUsername.java +++ b/src/main/java/biz/nynja/account/models/AccountByUsername.java @@ -22,7 +22,7 @@ public class AccountByUsername { private String authenticationProviderType; private String firstName; private String lastName; - private ByteBuffer avatar; + private String avatar; private String accountName; private String username; private Long creationTimestamp; @@ -89,11 +89,11 @@ public class AccountByUsername { this.lastName = lastName; } - public ByteBuffer getAvatar() { + public String getAvatar() { return avatar; } - public void setAvatar(ByteBuffer avatar) { + public void setAvatar(String avatar) { this.avatar = avatar; } @@ -340,7 +340,7 @@ public class AccountByUsername { builder.setQrCode(getQrCode()); } if (getAvatar() != null) { - builder.setAvatar(com.google.protobuf.ByteString.copyFrom(avatar)); + builder.setAvatar(avatar); } if (getRoles() != null) { for (String role : getRoles()) { diff --git a/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditional.java b/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditional.java index 3503b4236be83bffa281342e3d73a454e54f8d73..bdcc16e76a3fa3c78ccfe3187950c31ec6b09e62 100644 --- a/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditional.java +++ b/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditional.java @@ -5,16 +5,12 @@ package biz.nynja.account.repositories; import java.util.UUID; +import biz.nynja.account.models.*; import org.springframework.stereotype.Repository; import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; import biz.nynja.account.grpc.UpdateAccountRequest; import biz.nynja.account.grpc.UpdateProfileRequest; -import biz.nynja.account.models.Account; -import biz.nynja.account.models.AuthenticationProvider; -import biz.nynja.account.models.ContactInfo; -import biz.nynja.account.models.PendingAccountByAuthenticationProvider; -import biz.nynja.account.models.Profile; @Repository public interface AccountRepositoryAdditional { @@ -44,4 +40,6 @@ public interface AccountRepositoryAdditional { boolean deleteContactInfo(UUID accountId, ContactInfo contactInfo); boolean editContactInfo(UUID accountId, ContactInfo oldContactInfo, ContactInfo editedContactInfo); + + PendingAccount savePendingAccount(PendingAccount updatedPendingAccount); } diff --git a/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditionalImpl.java b/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditionalImpl.java index 3254ff1b73434172817e16fac86e184db66537df..dc5d6c02694d117e3193b67ba60e999f9ab55771 100644 --- a/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditionalImpl.java +++ b/src/main/java/biz/nynja/account/repositories/AccountRepositoryAdditionalImpl.java @@ -1,5 +1,5 @@ /** - * Copyright (C) 2018 Nynja Inc. All rights reserved. + * Copyright (C) 2018 Nynja Inc. All rights reserved. */ package biz.nynja.account.repositories; @@ -97,17 +97,11 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio PendingAccount pendingAccount = pendingAccountRepository .findByAccountId(UUID.fromString(request.getAccountId())); if (pendingAccount == null) { - logger.info("Existing pending account with the provided id was not found."); - logger.debug("Existing pending account with the provided id {} was not found.", request.getAccountId()); + logger.info("Existing pending account with the provided id was not found or creation timeout expired."); + logger.debug("Existing pending account with the provided id {} was not found or creation timeout expired.", request.getAccountId()); return null; } Long timeCreated = Instant.now().toEpochMilli(); - Long checkMinutes = timeCreated - pendingAccount.getCreationTimestamp(); - if (checkMinutes > COMPLETE_PENDING_ACCOUNT_TIMEOUT_IN_MINUTES * 60 * 1000) { - logger.info("Account creation timeout expired."); - pendingAccountRepository.deleteById(UUID.fromString(request.getAccountId())); - return null; - } WriteResult wr = null; try { newAccountInsert(batchOperations, request, pendingAccount, timeCreated); @@ -131,7 +125,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void newAccountInsert(CassandraBatchOperations batchOps, CompletePendingAccountCreationRequest request, - PendingAccount pendingAccount, Long creationTimestamp) { + PendingAccount pendingAccount, Long creationTimestamp) { Account newAccount = new Account(); newAccount.setAccountId(pendingAccount.getAccountId()); newAccount.setProfileId(pendingAccount.getProfileId()); @@ -140,7 +134,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio newAccount.setAuthenticationProviderType(pendingAccount.getAuthenticationProviderType()); newAccount.setFirstName(request.getFirstName()); newAccount.setLastName(request.getLastName()); - newAccount.setAvatar(request.getAvatar().asReadOnlyByteBuffer()); + newAccount.setAvatar(request.getAvatar()); newAccount.setAccountName(request.getAccountName()); newAccount.setUsername(request.getUsername()); newAccount.setCreationTimestamp(creationTimestamp); @@ -151,7 +145,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void newProfileInsert(CassandraBatchOperations batchOps, CompletePendingAccountCreationRequest request, - PendingAccount pendingAccount, Long creationTimestamp) { + PendingAccount pendingAccount, Long creationTimestamp) { Profile newProfile = new Profile(); newProfile.setProfileId(pendingAccount.getProfileId()); Set authenticationProvidersSet = new HashSet(); @@ -163,7 +157,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void newProfileByAuthenticationProviderInsert(CassandraBatchOperations batchOps, - PendingAccount pendingAccount) { + PendingAccount pendingAccount) { ProfileByAuthenticationProvider newProfileByAuthenticationProvider = new ProfileByAuthenticationProvider(); newProfileByAuthenticationProvider.setAuthenticationProvider(pendingAccount.getAuthenticationProvider()); newProfileByAuthenticationProvider @@ -293,7 +287,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio * @return true or false according to the result of removing the account's creation provider */ private boolean removeCreationProvider(CassandraBatchOperations batchOperations, Account existingAccount, - Profile existingProfile) { + Profile existingProfile) { // update authentication providers of the profile by removing the one of the deleted account (if not // already manually removed by the user) Long timeUpdated = Instant.now().toEpochMilli(); @@ -320,9 +314,9 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void updateAccountData(CassandraBatchOperations batchOps, UpdateAccountRequest request, - Account existingAccount, Long lastUpdateTimestamp) { + Account existingAccount, Long lastUpdateTimestamp) { Account updatedAccount = existingAccount; - updatedAccount.setAvatar(request.getAvatar().asReadOnlyByteBuffer()); + updatedAccount.setAvatar(request.getAvatar()); updatedAccount.setAccountMark(request.getAccountMark()); updatedAccount.setAccountName(request.getAccountName()); updatedAccount.setFirstName(request.getFirstName()); @@ -340,7 +334,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void updateProfileData(CassandraBatchOperations batchOps, UpdateProfileRequest request, - Profile existingProfile, Long lastUpdateTimestamp) { + Profile existingProfile, Long lastUpdateTimestamp) { Profile updatedProfile = existingProfile; updatedProfile.setPasscode(request.getPasscode()); if (!request.getDefaultAccountId().trim().isEmpty()) { @@ -353,7 +347,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void updateAuthProvidersInProfileWhenDeletingAccount(CassandraBatchOperations batchOps, - Profile existingProfile, Set authProvidersToUpdate, Long lastUpdateTimestamp) { + Profile existingProfile, Set authProvidersToUpdate, Long lastUpdateTimestamp) { Profile updatedProfile = existingProfile; if (authProvidersToUpdate != null) { updatedProfile.setAuthenticationProviders(authProvidersToUpdate); @@ -388,14 +382,14 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void deleteAuthenticationProvidersFromProfile(CassandraBatchOperations batchOps, UUID profileId, - Set authenticationProvidersSetToDelete) { + Set authenticationProvidersSetToDelete) { for (AuthenticationProvider authProvider : authenticationProvidersSetToDelete) { deleteProfileByAuthenticationProvider(batchOps, profileId, authProvider); } } private void deleteProfileByAuthenticationProvider(CassandraBatchOperations batchOps, UUID profileId, - AuthenticationProvider authProvider) { + AuthenticationProvider authProvider) { ProfileByAuthenticationProvider profileByAuthenticationProviderToDelete = new ProfileByAuthenticationProvider(); profileByAuthenticationProviderToDelete.setAuthenticationProvider(authProvider.getValue()); profileByAuthenticationProviderToDelete.setAuthenticationProviderType(authProvider.getType()); @@ -480,7 +474,7 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } private void deleteProfileAccountsWhenDeletingProfile(UUID profileId, CassandraBatchOperations batchOperations, - List existingAccountsForProfile) { + List existingAccountsForProfile) { for (AccountByProfileId accountByProfileId : existingAccountsForProfile) { Account existingAccount = accountRepository.findByAccountId(accountByProfileId.getAccountId()); deleteAccountData(batchOperations, existingAccount); @@ -654,4 +648,12 @@ public class AccountRepositoryAdditionalImpl implements AccountRepositoryAdditio } return false; } + + public PendingAccount savePendingAccount(PendingAccount pendingAccount) { + String cql = "INSERT INTO pendingAccount (accountId, profileId, authenticationProvider, authenticationProviderType, creationTimestamp)" + + " VALUES (" + pendingAccount.getAccountId() + ", " + pendingAccount.getProfileId() + ", '" + pendingAccount.getAuthenticationProvider() + "', '" + pendingAccount.getAuthenticationProviderType() + "'," + pendingAccount.getCreationTimestamp() + ") " + + "USING TTL "+COMPLETE_PENDING_ACCOUNT_TIMEOUT_IN_MINUTES *60 +";"; + cassandraTemplate.getCqlOperations().execute(cql); + return pendingAccount; + } } diff --git a/src/main/java/biz/nynja/account/repositories/PendingAccountRepository.java b/src/main/java/biz/nynja/account/repositories/PendingAccountRepository.java index 4d3c6f1eec8766ea9cef3ffbe029d9eb2970eb3e..f7d2c3c2b297bd93dbf9002196e080e2d5985cc4 100644 --- a/src/main/java/biz/nynja/account/repositories/PendingAccountRepository.java +++ b/src/main/java/biz/nynja/account/repositories/PendingAccountRepository.java @@ -16,4 +16,7 @@ public interface PendingAccountRepository extends CassandraRepository S save(S s); } diff --git a/src/main/java/biz/nynja/account/services/AccountServiceImpl.java b/src/main/java/biz/nynja/account/services/AccountServiceImpl.java index 77058b72fd2547ba345f16fc1442ecc60233d249..b9fdf4aa5d8a7afca9e494565b0b8eb53e570664 100644 --- a/src/main/java/biz/nynja/account/services/AccountServiceImpl.java +++ b/src/main/java/biz/nynja/account/services/AccountServiceImpl.java @@ -3,10 +3,8 @@ */ package biz.nynja.account.services; -import java.time.Instant; import java.util.Optional; import java.util.UUID; -import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.lognet.springboot.grpc.GRpcService; @@ -14,26 +12,57 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import biz.nynja.account.components.Validator; -import biz.nynja.account.grpc.*; +import biz.nynja.account.grpc.AccountByAccountIdRequest; +import biz.nynja.account.grpc.AccountByAuthenticationProviderRequest; +import biz.nynja.account.grpc.AccountResponse; +import biz.nynja.account.grpc.AccountServiceGrpc; +import biz.nynja.account.grpc.AccountsByProfileIdRequest; +import biz.nynja.account.grpc.AccountsResponse; +import biz.nynja.account.grpc.AddAuthenticationProviderRequest; +import biz.nynja.account.grpc.AddContactInfoRequest; +import biz.nynja.account.grpc.AuthProviderDetails; +import biz.nynja.account.grpc.AuthenticationType; +import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; +import biz.nynja.account.grpc.ContactType; +import biz.nynja.account.grpc.CreatePendingAccountRequest; +import biz.nynja.account.grpc.CreatePendingAccountResponse; +import biz.nynja.account.grpc.DeleteAccountRequest; +import biz.nynja.account.grpc.DeleteAuthenticationProviderRequest; +import biz.nynja.account.grpc.DeleteContactInfoRequest; +import biz.nynja.account.grpc.DeleteProfileRequest; +import biz.nynja.account.grpc.EditContactInfoRequest; +import biz.nynja.account.grpc.ErrorResponse; import biz.nynja.account.grpc.ErrorResponse.Cause; +import biz.nynja.account.grpc.GetByEmailRequest; +import biz.nynja.account.grpc.GetByPhoneNumberRequest; +import biz.nynja.account.grpc.GetByQrCodeRequest; +import biz.nynja.account.grpc.GetByUsernameRequest; +import biz.nynja.account.grpc.ProfileResponse; +import biz.nynja.account.grpc.SearchResponse; +import biz.nynja.account.grpc.SearchResultDetails; +import biz.nynja.account.grpc.StatusResponse; +import biz.nynja.account.grpc.UpdateAccountRequest; +import biz.nynja.account.grpc.UpdateProfileRequest; import biz.nynja.account.models.Account; +import biz.nynja.account.models.AccountByQrCode; +import biz.nynja.account.models.AccountByUsername; +import biz.nynja.account.models.AuthenticationProvider; +import biz.nynja.account.models.ContactInfo; +import biz.nynja.account.models.Profile; +import biz.nynja.account.models.ProfileByAuthenticationProvider; import biz.nynja.account.phone.PhoneNumberNormalizer; import biz.nynja.account.phone.PhoneNumberValidator; -import biz.nynja.account.models.*; -import biz.nynja.account.repositories.AccountByAuthenticationProviderRepository; import biz.nynja.account.repositories.AccountByQrCodeRepository; import biz.nynja.account.repositories.AccountByUsernameRepository; import biz.nynja.account.repositories.AccountRepositoryAdditional; -import biz.nynja.account.repositories.PendingAccountRepository; import biz.nynja.account.repositories.ProfileByAuthenticationProviderRepository; import biz.nynja.account.repositories.ProfileRepository; -import biz.nynja.account.services.decomposition.AccountsProvider; -import biz.nynja.account.validation.ValidationError; +import biz.nynja.account.services.decomposition.AccountCreator; +import biz.nynja.account.services.decomposition.AccountProvider; import biz.nynja.account.validation.Validation; +import biz.nynja.account.validation.ValidationError; import io.grpc.stub.StreamObserver; -import java.nio.ByteBuffer; - /** * gRPC Account service implementation.
* The service extends the protobuf generated class and overrides the needed methods. It also saves/retrieves the @@ -45,47 +74,34 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class); private static final byte MIN_NUMBER_OF_AUTH_PROVIDERS_IN_PROFILE = 1; - private final PendingAccountRepository pendingAccountRepository; private final AccountRepositoryAdditional accountRepositoryAdditional; private final ProfileRepository profileRepository; private final ProfileByAuthenticationProviderRepository profileByAutheticationProviderRepository; private final AccountByQrCodeRepository accountByQrCodeRepository; - private final AccountByAuthenticationProviderRepository accountByAuthenticationProviderRepository; private final AccountByUsernameRepository accountByUsernameRepository; private final Validator validator; private final PhoneNumberValidator phoneNumberValidator; - private final AccountsProvider accountsProvider; + private final AccountProvider accountProvider; private final PhoneNumberNormalizer phoneNumberNormalizer; - - public AccountServiceImpl(PendingAccountRepository pendingAccountRepository, - AccountRepositoryAdditional accountRepositoryAdditional, - ProfileRepository profileRepository, - ProfileByAuthenticationProviderRepository profileByAutheticationProviderRepository, - AccountByQrCodeRepository accountByQrCodeRepository, - AccountByAuthenticationProviderRepository accountByAuthenticationProviderRepository, - AccountByUsernameRepository accountByUsernameRepository, - Validator validator, - PhoneNumberValidator phoneNumbervalidator, - AccountsProvider accountsProvider, - PhoneNumberNormalizer phoneNumberNormalizer) { - this.pendingAccountRepository = pendingAccountRepository; + private final AccountCreator accountCreator; + + public AccountServiceImpl(AccountRepositoryAdditional accountRepositoryAdditional, + ProfileRepository profileRepository, + ProfileByAuthenticationProviderRepository profileByAutheticationProviderRepository, + AccountByQrCodeRepository accountByQrCodeRepository, + AccountByUsernameRepository accountByUsernameRepository, Validator validator, + PhoneNumberValidator phoneNumberValidator, AccountProvider accountProvider, + PhoneNumberNormalizer phoneNumberNormalizer, AccountCreator accountCreator) { this.accountRepositoryAdditional = accountRepositoryAdditional; this.profileRepository = profileRepository; this.profileByAutheticationProviderRepository = profileByAutheticationProviderRepository; this.accountByQrCodeRepository = accountByQrCodeRepository; - this.accountByAuthenticationProviderRepository = accountByAuthenticationProviderRepository; this.accountByUsernameRepository = accountByUsernameRepository; this.validator = validator; - this.phoneNumberValidator = phoneNumbervalidator; - this.accountsProvider = accountsProvider; + this.phoneNumberValidator = phoneNumberValidator; + this.accountProvider = accountProvider; this.phoneNumberNormalizer = phoneNumberNormalizer; - } - - @Override - public void createAccount(CreateAccountRequest request, StreamObserver responseObserver) { - - // TODO: add method implementation - + this.accountCreator = accountCreator; } @Override @@ -103,8 +119,8 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas "Missing authentication provider identifier", "", Cause.MISSING_AUTH_PROVIDER_IDENTIFIER); return; } - Optional account = accountsProvider.getAccountResponseByAuthenticationProvider( - request.getAuthenticationType(), request.getAuthenticationIdentifier()); + Optional account = accountProvider.getAccountResponseByAuthenticationProvider( + request.getAuthenticationType(), request.getAuthenticationIdentifier()); if (!account.isPresent()) { logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), @@ -116,103 +132,113 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas return; } - } - - @Override - public void searchByEmail(GetByEmailRequest request, StreamObserver responseObserver) { - logger.info("Search account by e-mail: {}", request.getEmail()); - if ((request.getEmail() == null) || request.getEmail().isEmpty()) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Missing e-mail.", "", Cause.MISSING_EMAIL); - return; - } - if (!validator.isEmailValid(request.getEmail())) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Invalid e-mail!. Value : ", request.getEmail(), Cause.EMAIL_INVALID); - return; - } - - Optional account = accountsProvider.getAccountByAuthenticationProvider(AuthenticationType.EMAIL, - request.getEmail()); - - if (!account.isPresent()) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "No matching accounts found for e-mail: ", request.getEmail(), Cause.EMAIL_NOT_FOUND); - return; - } else { + } + + @Override + public void searchByEmail(GetByEmailRequest request, StreamObserver responseObserver) { + logger.info("Search account by e-mail: {}", request.getEmail()); + if ((request.getEmail() == null) || request.getEmail().isEmpty()) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Missing e-mail.", "", + Cause.MISSING_EMAIL); + return; + } + if (!validator.isEmailValid(request.getEmail())) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Invalid e-mail!. Value : ", + request.getEmail(), Cause.EMAIL_INVALID); + return; + } + + Optional account = accountProvider.getAccountByAuthenticationProvider(AuthenticationType.EMAIL, + request.getEmail()); + + if (!account.isPresent()) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), + "No matching accounts found for e-mail: ", request.getEmail(), Cause.EMAIL_NOT_FOUND); + return; + } else { SearchResultDetails searchResultDetails = buildSearchResultDetails(account.get().getAccountId().toString(), account.get().getAvatar(), account.get().getFirstName(), account.get().getLastName()); - SearchResponse response = SearchResponse.newBuilder().setSearchResultDetails(searchResultDetails).build(); - logger.debug("Found result for account by e-mail {}: \"{}\"", request.getEmail(), response); - responseObserver.onNext(response); - responseObserver.onCompleted(); - return; - } - } - - @Override - public void searchByPhoneNumber(GetByPhoneNumberRequest request, StreamObserver responseObserver) { - - logger.info("Search account by phone: {}", request.getPhoneNumber()); - if ((request.getPhoneNumber() == null) || request.getPhoneNumber().isEmpty()) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Missing phone number.", "", Cause.MISSING_PHONENUMBER); - return; - } - - if (!phoneNumberValidator.isPhoneNumberValid(request.getPhoneNumber())) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Invalid phone number. Value : ", request.getPhoneNumber(), Cause.INVALID_PHONENUMBER); - return; - } - - Optional account = accountsProvider.getAccountByAuthenticationProvider(AuthenticationType.PHONE, - request.getPhoneNumber()); - - if (!account.isPresent()) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "No matching accounts found for phone: ", request.getPhoneNumber(), Cause.PHONENUMBER_NOT_FOUND); - return; - } else { + SearchResponse response = SearchResponse.newBuilder().setSearchResultDetails(searchResultDetails).build(); + logger.debug("Found result for account by e-mail {}: \"{}\"", request.getEmail(), response); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } + } + + @Override + public void searchByPhoneNumber(GetByPhoneNumberRequest request, StreamObserver responseObserver) { + + logger.info("Search account by phone: {}", request.getPhoneNumber()); + if ((request.getPhoneNumber() == null) || request.getPhoneNumber().isEmpty()) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Missing phone number.", "", + Cause.MISSING_PHONENUMBER); + return; + } + + if (!phoneNumberValidator.isPhoneNumberValid(request.getPhoneNumber())) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), + "Invalid phone number. Value : ", request.getPhoneNumber(), Cause.INVALID_PHONENUMBER); + return; + } + + Optional account = accountProvider.getAccountByAuthenticationProvider(AuthenticationType.PHONE, + request.getPhoneNumber()); + + if (!account.isPresent()) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), + "No matching accounts found for phone: ", request.getPhoneNumber(), Cause.PHONENUMBER_NOT_FOUND); + return; + } else { SearchResultDetails searchResultDetails = buildSearchResultDetails(account.get().getAccountId().toString(), account.get().getAvatar(), account.get().getFirstName(), account.get().getLastName()); - SearchResponse response = SearchResponse.newBuilder().setSearchResultDetails(searchResultDetails).build(); - logger.debug("Found result for account by phone {}: \"{}\"", request.getPhoneNumber(), response); - responseObserver.onNext(response); - responseObserver.onCompleted(); - return; - } - } + SearchResponse response = SearchResponse.newBuilder().setSearchResultDetails(searchResultDetails).build(); + logger.debug("Found result for account by phone {}: \"{}\"", request.getPhoneNumber(), response); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } + } @Override public void getAccountByUsername(GetByUsernameRequest request, StreamObserver responseObserver) { - logger.info("Getting account by username: {}", request.getUsername()); - Validation validation = validateGetByUsernameRequest(request); - if(validation.hasErrors()) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), validation.getErrorMessage(), "", validation.getCause().get()); - return; - } - - Optional accountResonse = accountsProvider.getAccountResponseByUsername(request.getUsername()); - - if (!accountResonse.isPresent()) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Account not found", "", Cause.ACCOUNT_NOT_FOUND); - return; - } else { - responseObserver.onNext(accountResonse.get()); - responseObserver.onCompleted(); - return; - } + logger.info("Getting account by username: {}", request.getUsername()); + Validation validation = validateGetByUsernameRequest(request); + if (validation.hasErrors()) { + logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), validation.getErrorMessage(), + "", validation.getCause().get()); + return; + } + + Optional accountResonse = accountProvider.getAccountResponseByUsername(request.getUsername()); + + if (!accountResonse.isPresent()) { + logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Account not found", "", + Cause.ACCOUNT_NOT_FOUND); + return; + } else { + responseObserver.onNext(accountResonse.get()); + responseObserver.onCompleted(); + return; + } } @Override public void searchByUsername(GetByUsernameRequest request, StreamObserver responseObserver) { - logger.info("Searching account by username: {}", request.getUsername()); - Validation validation = validateGetByUsernameRequest(request); - if(validation.hasErrors()) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), validation.getErrorMessage(), "", validation.getCause().get()); - return; + logger.info("Searching account by username: {}", request.getUsername()); + Validation validation = validateGetByUsernameRequest(request); + if (validation.hasErrors()) { + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), validation.getErrorMessage(), + "", validation.getCause().get()); + return; } AccountByUsername account = accountByUsernameRepository.findByUsername(request.getUsername()); if (account == null) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "No matching accounts found for username: ", request.getUsername(), Cause.USERNAME_NOT_FOUND); + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), + "No matching accounts found for username: ", request.getUsername(), Cause.USERNAME_NOT_FOUND); return; } @@ -243,36 +269,40 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas @Override public void getAccountByQrCode(GetByQrCodeRequest request, StreamObserver responseObserver) { - logger.info("Search account by QR code: {}", request.getQrCode()); + logger.info("Search account by QR code: {}", request.getQrCode()); if ((request.getQrCode() == null) || request.getQrCode().isEmpty()) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Missing QR code.", "", Cause.MISSING_QR_CODE); + logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Missing QR code.", "", + Cause.MISSING_QR_CODE); return; } - - Optional accountResonse = accountsProvider.getAccountResponseByQrCode(request.getQrCode()); - + + Optional accountResonse = accountProvider.getAccountResponseByQrCode(request.getQrCode()); + if (!accountResonse.isPresent()) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Account not found", "", Cause.ACCOUNT_NOT_FOUND); + logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Account not found", "", + Cause.ACCOUNT_NOT_FOUND); return; } else { responseObserver.onNext(accountResonse.get()); responseObserver.onCompleted(); return; } - + } @Override public void searchByQrCode(GetByQrCodeRequest request, StreamObserver responseObserver) { logger.info("Search account by QR code: {}", request.getQrCode()); if ((request.getQrCode() == null) || request.getQrCode().isEmpty()) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Missing QR code.", "", Cause.MISSING_QR_CODE); + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "Missing QR code.", "", + Cause.MISSING_QR_CODE); return; } AccountByQrCode account = accountByQrCodeRepository.findByQrCode(request.getQrCode()); if (account == null) { - logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), "No matching accounts found for QR code! Value: ", request.getQrCode(), Cause.QR_CODE_NOT_FOUND); + logAndBuildGrpcSearchResponse(responseObserver, SearchResponse.newBuilder(), + "No matching accounts found for QR code! Value: ", request.getQrCode(), Cause.QR_CODE_NOT_FOUND); return; } @@ -287,7 +317,6 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas return; } - @Override public void getAllAccountsByProfileId(AccountsByProfileIdRequest request, StreamObserver responseObserver) { @@ -303,7 +332,7 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas request.getProfileId(), Cause.INVALID_PROFILE_ID); return; } - Optional accounts = accountsProvider.getAllAccountsByProfileId(request); + Optional accounts = accountProvider.getAllAccountsByProfileId(request); if (!accounts.isPresent()) { logAndBuildGrpcAccountsResponse(responseObserver, AccountsResponse.newBuilder(), @@ -333,7 +362,7 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas return; } - Optional account = accountsProvider.getAccountByAccountId(request); + Optional account = accountProvider.getAccountByAccountId(request); if (!account.isPresent()) { logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Account id not found: {}", @@ -352,70 +381,9 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas logger.info("Creating pending account..."); logger.debug("Creating pending account: {} ...", request); - Cause cause = validator.validateCreatePendingAccountRequest(request); - if (cause != null) { - logAndBuildGrpcPendingAccountResponse(responseObserver, CreatePendingAccountResponse.newBuilder(), "Validation failed", "", cause); - return; - } - - if (request.getAuthenticationType() == AuthenticationType.PHONE) { - // Get the normalized phone number from libphone - CreatePendingAccountRequest newRequest = CreatePendingAccountRequest.newBuilder() - .setAuthenticationType(request.getAuthenticationType()).setAuthenticationProvider( - phoneNumberValidator.getNormalizedPhoneNumber(request.getAuthenticationProvider())) - .build(); - request = newRequest; - } - - PendingAccountByAuthenticationProvider foundExistingPendingAccount = accountRepositoryAdditional - .findSameAuthenticationProviderInPendingAccount( - AuthenticationProvider.createAuthenticationProviderFromStrings( - request.getAuthenticationType().name(), request.getAuthenticationProvider())); - - PendingAccount updatedPendingAccount = new PendingAccount(); - - if (foundExistingPendingAccount != null) { - updatedPendingAccount.setAccountId(foundExistingPendingAccount.getAccountId()); - updatedPendingAccount.setProfileId(foundExistingPendingAccount.getProfileId()); - updatedPendingAccount.setAuthenticationProvider(foundExistingPendingAccount.getAuthenticationProvider()); - updatedPendingAccount - .setAuthenticationProviderType(foundExistingPendingAccount.getAuthenticationProviderType()); - updatedPendingAccount.setCreationTimestamp(Instant.now().toEpochMilli()); - - PendingAccount updatePendingAccount = pendingAccountRepository.save(updatedPendingAccount); - CreatePendingAccountResponse response = CreatePendingAccountResponse.newBuilder() - .setPendingAccountDetails(updatePendingAccount.toProto()).build(); - logger.info("Pending account created."); - responseObserver.onNext(response); - responseObserver.onCompleted(); - return; - } - - if (accountRepositoryAdditional.authenticationProviderAlreadyUsedInAccount( - AuthenticationProvider.createAuthenticationProviderFromStrings(request.getAuthenticationType().name(), - request.getAuthenticationProvider()))) { - logAndBuildGrpcPendingAccountResponse(responseObserver, CreatePendingAccountResponse.newBuilder(), - "Account already created", "", Cause.ACCOUNT_ALREADY_CREATED); - return; - } - - PendingAccount pendingAccount = PendingAccount.fromProto(request); - - pendingAccount.setAccountId(UUID.randomUUID()); - pendingAccount.setProfileId(UUID.randomUUID()); - pendingAccount.setCreationTimestamp(Instant.now().toEpochMilli()); - - PendingAccount savedPendingAccount = pendingAccountRepository.save(pendingAccount); - logger.debug("Pending account \"{}\" saved into the DB", savedPendingAccount.toString()); - CreatePendingAccountResponse response = CreatePendingAccountResponse.newBuilder() - .setPendingAccountDetails(savedPendingAccount.toProto()).build(); - logger.info("Pending account created successfully."); - logger.debug("Pending account: \"{}\" created successfully.", response); - + CreatePendingAccountResponse response = accountCreator.retrieveCreatePendingAccountResponse(request); responseObserver.onNext(response); responseObserver.onCompleted(); - - return; } @Override @@ -425,39 +393,9 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas logger.info("Complete pending account creation..."); logger.debug("Complete pending account creation...: {} ...", request); - Cause cause = validator.validateCompletePendingAccountCreationRequest(request); - if (cause != null) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), "Validation failed", "", - cause); - return; - } - - if (request.getUsername() != null && !request.getUsername().trim().isEmpty() && accountRepositoryAdditional - .foundExistingNotOwnUsername(UUID.fromString(request.getAccountId()), request.getUsername())) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), - "User name already in use: {}", request.getUsername(), Cause.USERNAME_ALREADY_USED); - return; - } - - if (request.getRolesList() == null || request.getRolesList().isEmpty()) { - request = CompletePendingAccountCreationRequest.newBuilder(request).addRoles(Role.USER).build(); - } - - Account createdAccount = accountRepositoryAdditional.completePendingAccountCreation(request); - - if (createdAccount == null) { - logAndBuildGrpcAccountResponse(responseObserver, AccountResponse.newBuilder(), - "Error creating account with useraname: {}", request.getUsername(), Cause.ERROR_CREATING_ACCOUNT); - return; - } else { - logger.debug("Account \"{}\" saved into the DB", createdAccount.toString()); - AccountResponse response = AccountResponse.newBuilder().setAccountDetails(createdAccount.toProto()).build(); - logger.debug("Account: \"{}\" created successfully.", response); - - responseObserver.onNext(response); - responseObserver.onCompleted(); - return; - } + AccountResponse response = accountCreator.retrieveCompletePendingAccountResponse(request); + responseObserver.onNext(response); + responseObserver.onCompleted(); } @Override @@ -691,9 +629,8 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas Optional> validationResult = validator .validateContactInfoRequest(request.getAccountId(), request.getContactInfo()); if (validationResult.isPresent()) { - logAndBuildGrpcStatusResponse(responseObserver, StatusResponse.newBuilder(), - "Validation failed. {}.", validationResult.get().getRight(), - validationResult.get().getLeft()); + logAndBuildGrpcStatusResponse(responseObserver, StatusResponse.newBuilder(), "Validation failed. {}.", + validationResult.get().getRight(), validationResult.get().getLeft()); return; } if (request.getContactInfo().getType() == ContactType.PHONE_CONTACT) { @@ -828,17 +765,17 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas return; } - private SearchResultDetails buildSearchResultDetails(String id, ByteBuffer avatar, String firstName, String lastName) { + private SearchResultDetails buildSearchResultDetails(String id, String avatar, String firstName, String lastName) { SearchResultDetails.Builder searchResultDetails = SearchResultDetails.newBuilder(); searchResultDetails.setFirstName(firstName).setLastName(lastName); if (avatar != null) { - searchResultDetails.setAvatar(com.google.protobuf.ByteString.copyFrom(avatar)); + searchResultDetails.setAvatar(avatar); } return searchResultDetails.build(); } - + private static void logAndBuildGrpcSearchResponse(StreamObserver responseObserver, SearchResponse.Builder newBuilder, String logMessage, String logValue, Cause cause) { @@ -862,13 +799,6 @@ public class AccountServiceImpl extends AccountServiceGrpc.AccountServiceImplBas responseObserver.onCompleted(); } - private static void logAndBuildGrpcPendingAccountResponse(StreamObserver responseObserver, - CreatePendingAccountResponse.Builder newBuilder, String logMessage, String logValue, Cause cause) { - logger.error(logMessage, logValue); - responseObserver.onNext(newBuilder.setError(ErrorResponse.newBuilder().setCause(cause)).build()); - responseObserver.onCompleted(); - } - private static void logAndBuildGrpcProfileResponse(StreamObserver responseObserver, ProfileResponse.Builder newBuilder, String logMessage, String logValue, Cause cause) { logger.error(logMessage, logValue); diff --git a/src/main/java/biz/nynja/account/services/decomposition/AccountCreator.java b/src/main/java/biz/nynja/account/services/decomposition/AccountCreator.java new file mode 100644 index 0000000000000000000000000000000000000000..70783c0ca6acdd064512843d4b1cafe60299431f --- /dev/null +++ b/src/main/java/biz/nynja/account/services/decomposition/AccountCreator.java @@ -0,0 +1,177 @@ +/** + * Copyright (C) 2018 Nynja Inc. All rights reserved. + */ +package biz.nynja.account.services.decomposition; + +import java.time.Instant; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import biz.nynja.account.components.PendingAccountValidator; +import biz.nynja.account.grpc.AccountDetails; +import biz.nynja.account.grpc.AccountResponse; +import biz.nynja.account.grpc.AuthenticationType; +import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; +import biz.nynja.account.grpc.CreatePendingAccountRequest; +import biz.nynja.account.grpc.CreatePendingAccountResponse; +import biz.nynja.account.grpc.ErrorResponse; +import biz.nynja.account.grpc.ErrorResponse.Cause; +import biz.nynja.account.grpc.Role; +import biz.nynja.account.models.Account; +import biz.nynja.account.models.AuthenticationProvider; +import biz.nynja.account.models.PendingAccount; +import biz.nynja.account.models.PendingAccountByAuthenticationProvider; +import biz.nynja.account.phone.PhoneNumberValidator; +import biz.nynja.account.repositories.AccountRepositoryAdditional; +import biz.nynja.account.repositories.PendingAccountRepository; + +@Service +public class AccountCreator { + + private static final Logger logger = LoggerFactory.getLogger(AccountCreator.class); + + private final PendingAccountRepository pendingAccountRepository; + private final AccountRepositoryAdditional accountRepositoryAdditional; + private final PendingAccountValidator pendingAccountValidator; + private final PhoneNumberValidator phoneNumberValidator; + + public AccountCreator(PendingAccountRepository pendingAccountRepository, + AccountRepositoryAdditional accountRepositoryAdditional, PendingAccountValidator pendingAccountValidator, + PhoneNumberValidator phoneNumberValidator) { + this.pendingAccountRepository = pendingAccountRepository; + this.accountRepositoryAdditional = accountRepositoryAdditional; + this.pendingAccountValidator = pendingAccountValidator; + this.phoneNumberValidator = phoneNumberValidator; + } + + /** + * Retrieves a {@link CreatePendingAccountResponse} based on {@link CreatePendingAccountRequest} + * + * @param request + * @return + */ + public CreatePendingAccountResponse retrieveCreatePendingAccountResponse(CreatePendingAccountRequest request) { + Cause cause = pendingAccountValidator.validateCreatePendingAccountRequest(request); + if (cause != null) { + return CreatePendingAccountResponse.newBuilder().setError(ErrorResponse.newBuilder().setCause(cause)) + .build(); + } + + if (request.getAuthenticationType() == AuthenticationType.PHONE) { + // Get the normalized phone number from libphone + CreatePendingAccountRequest newRequest = CreatePendingAccountRequest.newBuilder() + .setAuthenticationType(request.getAuthenticationType()).setAuthenticationProvider( + phoneNumberValidator.getNormalizedPhoneNumber(request.getAuthenticationProvider())) + .build(); + request = newRequest; + } + + CreatePendingAccountResponse response = updateAndValidatePendingAccountCreation(request); + if (response != null) { + return response; + } + + PendingAccount pendingAccount = PendingAccount.fromProto(request); + + pendingAccount.setAccountId(UUID.randomUUID()); + pendingAccount.setProfileId(UUID.randomUUID()); + pendingAccount.setCreationTimestamp(Instant.now().toEpochMilli()); + + PendingAccount savedPendingAccount = accountRepositoryAdditional.savePendingAccount(pendingAccount); + logger.debug("Pending account \"{}\" saved into the DB", savedPendingAccount); + response = CreatePendingAccountResponse.newBuilder().setPendingAccountDetails(savedPendingAccount.toProto()) + .build(); + logger.info("Pending account created successfully."); + logger.debug("Pending account: \"{}\" created successfully.", response); + return response; + } + + private CreatePendingAccountResponse updateAndValidatePendingAccountCreation(CreatePendingAccountRequest request) { + PendingAccountByAuthenticationProvider foundExistingPendingAccount = accountRepositoryAdditional + .findSameAuthenticationProviderInPendingAccount( + AuthenticationProvider.createAuthenticationProviderFromStrings( + request.getAuthenticationType().name(), request.getAuthenticationProvider())); + + PendingAccount updatedPendingAccount = new PendingAccount(); + + if (foundExistingPendingAccount != null) { + updatedPendingAccount.setAccountId(foundExistingPendingAccount.getAccountId()); + updatedPendingAccount.setProfileId(foundExistingPendingAccount.getProfileId()); + updatedPendingAccount.setAuthenticationProvider(foundExistingPendingAccount.getAuthenticationProvider()); + updatedPendingAccount + .setAuthenticationProviderType(foundExistingPendingAccount.getAuthenticationProviderType()); + updatedPendingAccount.setCreationTimestamp(Instant.now().toEpochMilli()); + + PendingAccount updatePendingAccount = accountRepositoryAdditional.savePendingAccount(updatedPendingAccount); + return CreatePendingAccountResponse.newBuilder().setPendingAccountDetails(updatePendingAccount.toProto()) + .build(); + } + + if (accountRepositoryAdditional.authenticationProviderAlreadyUsedInAccount( + AuthenticationProvider.createAuthenticationProviderFromStrings(request.getAuthenticationType().name(), + request.getAuthenticationProvider()))) { + return logAndBuildGrpcPendingAccountResponse(CreatePendingAccountResponse.newBuilder(), + "Account already created", "", Cause.ACCOUNT_ALREADY_CREATED); + } + return null; + } + + /** + * Retrieves a {@link AccountResponse} based on a {@link CompletePendingAccountCreationRequest} + * + * @param request + * @return + */ + public AccountResponse retrieveCompletePendingAccountResponse(CompletePendingAccountCreationRequest request) { + AccountResponse response = validateCompletePendingAccountCreationRequest(request); + if (response != null) { + return response; + } + + if (request.getRolesList() == null || request.getRolesList().isEmpty()) { + request = CompletePendingAccountCreationRequest.newBuilder(request).addRoles(Role.USER).build(); + } + + Account createdAccount = accountRepositoryAdditional.completePendingAccountCreation(request); + + if (createdAccount == null) { + return logAndBuildGrpcAccountResponse(AccountResponse.newBuilder(), + "Error creating account with useraname: {}", request.getUsername(), Cause.ERROR_CREATING_ACCOUNT); + } else { + logger.debug("Account \"{}\" saved into the DB", createdAccount); + AccountDetails details = createdAccount.toProto(); + logger.debug("Account: \"{}\" created successfully.", response); + return AccountResponse.newBuilder().setAccountDetails(details).build(); + } + } + + private AccountResponse validateCompletePendingAccountCreationRequest( + CompletePendingAccountCreationRequest request) { + Cause cause = pendingAccountValidator.validateCompletePendingAccountCreationRequest(request); + if (cause != null) { + return logAndBuildGrpcAccountResponse(AccountResponse.newBuilder(), "Validation failed", "", cause); + } + + if (request.getUsername() != null && !request.getUsername().trim().isEmpty() && accountRepositoryAdditional + .foundExistingNotOwnUsername(UUID.fromString(request.getAccountId()), request.getUsername())) { + return logAndBuildGrpcAccountResponse(AccountResponse.newBuilder(), "User name already in use: {}", + request.getUsername(), Cause.USERNAME_ALREADY_USED); + } + return null; + } + + private static CreatePendingAccountResponse logAndBuildGrpcPendingAccountResponse( + CreatePendingAccountResponse.Builder newBuilder, String logMessage, String logValue, Cause cause) { + logger.error(logMessage, logValue); + return newBuilder.setError(ErrorResponse.newBuilder().setCause(cause)).build(); + } + + private static AccountResponse logAndBuildGrpcAccountResponse(AccountResponse.Builder newBuilder, String logMessage, + String logValue, Cause cause) { + logger.error(logMessage, logValue); + return newBuilder.setError(ErrorResponse.newBuilder().setCause(cause)).build(); + } +} diff --git a/src/main/java/biz/nynja/account/services/decomposition/AccountsProvider.java b/src/main/java/biz/nynja/account/services/decomposition/AccountProvider.java similarity index 63% rename from src/main/java/biz/nynja/account/services/decomposition/AccountsProvider.java rename to src/main/java/biz/nynja/account/services/decomposition/AccountProvider.java index 66c1c67a250ce39d1312022b3590b0e8b268eb2c..1126e4a710bde49afd2915dea9109345da6fe631 100644 --- a/src/main/java/biz/nynja/account/services/decomposition/AccountsProvider.java +++ b/src/main/java/biz/nynja/account/services/decomposition/AccountProvider.java @@ -1,8 +1,26 @@ +/** + * Copyright (C) 2018 Nynja Inc. All rights reserved. + */ package biz.nynja.account.services.decomposition; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + import biz.nynja.account.components.AccountServiceHelper; -import biz.nynja.account.components.Validator; -import biz.nynja.account.grpc.*; +import biz.nynja.account.grpc.AccountByAccountIdRequest; +import biz.nynja.account.grpc.AccountByAuthenticationProviderRequest; +import biz.nynja.account.grpc.AccountDetails; +import biz.nynja.account.grpc.AccountResponse; +import biz.nynja.account.grpc.AccountsByProfileIdRequest; +import biz.nynja.account.grpc.AccountsList; +import biz.nynja.account.grpc.AccountsResponse; +import biz.nynja.account.grpc.AuthenticationType; import biz.nynja.account.models.Account; import biz.nynja.account.models.AccountByProfileId; import biz.nynja.account.models.AccountByQrCode; @@ -13,17 +31,9 @@ import biz.nynja.account.repositories.AccountByQrCodeRepository; import biz.nynja.account.repositories.AccountByUsernameRepository; import biz.nynja.account.repositories.AccountRepository; import biz.nynja.account.services.AccountServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; @Service -public class AccountsProvider { +public class AccountProvider { private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class); @@ -34,12 +44,11 @@ public class AccountsProvider { private final PhoneNumberValidator validator; private final AccountServiceHelper accountServiceHelper; - public AccountsProvider(AccountRepository accountRepository, - AccountByProfileIdRepository accountByProfileIdRepository, - AccountByUsernameRepository accountByUsernameRepository, - AccountByQrCodeRepository accountByQrCodeRepository, - PhoneNumberValidator validator, - AccountServiceHelper accountServiceHelper) { + public AccountProvider(AccountRepository accountRepository, + AccountByProfileIdRepository accountByProfileIdRepository, + AccountByUsernameRepository accountByUsernameRepository, + AccountByQrCodeRepository accountByQrCodeRepository, PhoneNumberValidator validator, + AccountServiceHelper accountServiceHelper) { this.accountRepository = accountRepository; this.accountByProfileIdRepository = accountByProfileIdRepository; this.validator = validator; @@ -48,51 +57,53 @@ public class AccountsProvider { this.accountByQrCodeRepository = accountByQrCodeRepository; } - public Optional getAccountByAuthenticationProvider(AuthenticationType type, String authenticationIdentifier) { + public Optional getAccountByAuthenticationProvider(AuthenticationType type, + String authenticationIdentifier) { if (type == AuthenticationType.PHONE) { - authenticationIdentifier = validator.getNormalizedPhoneNumber(authenticationIdentifier); + authenticationIdentifier = validator.getNormalizedPhoneNumber(authenticationIdentifier); } - Account account = accountServiceHelper.getAccountByAuthenticationProviderHelper( - authenticationIdentifier, type.toString()); + Account account = accountServiceHelper.getAccountByAuthenticationProviderHelper(authenticationIdentifier, + type.toString()); if (account == null) { - logger.debug("No matching accounts found for authetntication provider {}: {}", - type, authenticationIdentifier); + logger.debug("No matching accounts found for authetntication provider {}: {}", type, + authenticationIdentifier); return Optional.empty(); } - + return Optional.of(account); } - - public Optional getAccountResponseByUsername(String username){ - AccountByUsername account = accountByUsernameRepository.findByUsername(username); - if(account == null) { - return Optional.empty(); - } - AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.toProto()).build(); - logger.debug("Found result for account by username {}:", username, response); - return Optional.of(response); + + public Optional getAccountResponseByUsername(String username) { + AccountByUsername account = accountByUsernameRepository.findByUsername(username); + if (account == null) { + return Optional.empty(); + } + AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.toProto()).build(); + logger.debug("Found result for account by username {}:", username, response); + return Optional.of(response); } - - public Optional getAccountResponseByQrCode(String qrCode){ - AccountByQrCode account = accountByQrCodeRepository.findByQrCode(qrCode); - if(account == null) { - return Optional.empty(); - } - AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.toProto()).build(); + + public Optional getAccountResponseByQrCode(String qrCode) { + AccountByQrCode account = accountByQrCodeRepository.findByQrCode(qrCode); + if (account == null) { + return Optional.empty(); + } + AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.toProto()).build(); logger.debug("Found result for account by username {}:", qrCode, response); return Optional.of(response); - } - - public Optional getAccountResponseByAuthenticationProvider(AuthenticationType type, String authenticationIdentifier) { - Optional account = getAccountByAuthenticationProvider(type, authenticationIdentifier); - if(!account.isPresent()) { - return Optional.empty(); - } - + } + + public Optional getAccountResponseByAuthenticationProvider(AuthenticationType type, + String authenticationIdentifier) { + Optional account = getAccountByAuthenticationProvider(type, authenticationIdentifier); + if (!account.isPresent()) { + return Optional.empty(); + } + AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.get().toProto()).build(); - logger.debug("Found result for account by authentication provider {}: {}: \"{}\"", - type, authenticationIdentifier, response); + logger.debug("Found result for account by authentication provider {}: {}: \"{}\"", type, + authenticationIdentifier, response); return Optional.of(response); } @@ -102,7 +113,8 @@ public class AccountsProvider { if (listAccountsByProfileId.size() == 0) { return Optional.empty(); } - List responseList = listAccountsByProfileId.stream().map(AccountByProfileId::toProto).collect(Collectors.toList()); + List responseList = listAccountsByProfileId.stream().map(AccountByProfileId::toProto) + .collect(Collectors.toList()); AccountsResponse response = AccountsResponse.newBuilder() .setAccountsResponse(AccountsList.newBuilder().addAllAccountDetails(responseList)).build(); logger.debug("Returned response: \"{}\".", response); @@ -120,9 +132,11 @@ public class AccountsProvider { return Optional.of(response); } - private AccountByAuthenticationProviderRequest normalizedPhoneNumber(AccountByAuthenticationProviderRequest request) { + private AccountByAuthenticationProviderRequest normalizedPhoneNumber( + AccountByAuthenticationProviderRequest request) { return AccountByAuthenticationProviderRequest.newBuilder() .setAuthenticationType(request.getAuthenticationType()) - .setAuthenticationIdentifier(validator.getNormalizedPhoneNumber(request.getAuthenticationIdentifier())).build(); + .setAuthenticationIdentifier(validator.getNormalizedPhoneNumber(request.getAuthenticationIdentifier())) + .build(); } } diff --git a/src/test/java/biz/nynja/account/components/ValidatorTests.java b/src/test/java/biz/nynja/account/components/ValidatorTests.java index 932b69e2fcc9d18c9f77ee9abc1fd01c00fe7f1e..e5bc6654112bbfa3643df667551d14a7d45ae4ff 100644 --- a/src/test/java/biz/nynja/account/components/ValidatorTests.java +++ b/src/test/java/biz/nynja/account/components/ValidatorTests.java @@ -6,7 +6,6 @@ package biz.nynja.account.components; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -18,7 +17,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import biz.nynja.account.grpc.AuthProviderDetails; import biz.nynja.account.grpc.AuthenticationType; import biz.nynja.account.grpc.CompletePendingAccountCreationRequest; import biz.nynja.account.grpc.CreatePendingAccountRequest; @@ -32,16 +30,20 @@ import biz.nynja.account.utils.Util; */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = { Validator.class, PhoneNumberValidator.class }) +@ContextConfiguration(classes = { Validator.class, PendingAccountValidator.class, PhoneNumberValidator.class }) public class ValidatorTests { @Autowired - @Qualifier("validator") + @Qualifier("validator") private Validator validator; + @Autowired + @Qualifier("pendingAccountValidator") + private PendingAccountValidator pendingAccountValidator; + @MockBean private AccountRepositoryAdditional accountRepositoryAdditional; - + @Test public void validUsernameTest() { @@ -208,7 +210,7 @@ public class ValidatorTests { CompletePendingAccountCreationRequest request = CompletePendingAccountCreationRequest.newBuilder() .setAccountId(Util.ACCOUNT_ID.toString()).setFirstName(Util.FIRST_NAME).setLastName(Util.LAST_NAME) .setUsername(Util.USERNAME).build(); - assertNull(validator.validateCompletePendingAccountCreationRequest(request)); + assertNull(pendingAccountValidator.validateCompletePendingAccountCreationRequest(request)); } @Test @@ -216,14 +218,16 @@ public class ValidatorTests { CompletePendingAccountCreationRequest request = CompletePendingAccountCreationRequest.newBuilder() .setAccountId(Util.ACCOUNT_ID.toString()).setFirstName(Util.FIRST_NAME).setLastName(Util.LAST_NAME) .setUsername("@alabala").build(); - assertEquals(validator.validateCompletePendingAccountCreationRequest(request), Cause.USERNAME_INVALID); + assertEquals(Cause.USERNAME_INVALID, + pendingAccountValidator.validateCompletePendingAccountCreationRequest(request)); } @Test public void validateCompletePendingAccountCreationRequestMissingAccountIdTest() { CompletePendingAccountCreationRequest request = CompletePendingAccountCreationRequest.newBuilder() .setFirstName(Util.FIRST_NAME).setLastName(Util.LAST_NAME).setUsername(Util.USERNAME).build(); - assertEquals(validator.validateCompletePendingAccountCreationRequest(request), Cause.MISSING_ACCOUNT_ID); + assertEquals(Cause.MISSING_ACCOUNT_ID, + pendingAccountValidator.validateCompletePendingAccountCreationRequest(request)); } @Test @@ -231,7 +235,7 @@ public class ValidatorTests { CreatePendingAccountRequest request = CreatePendingAccountRequest.newBuilder() .setAuthenticationType(AuthenticationType.EMAIL) .setAuthenticationProvider("valid.E-mail1@domain-sub.test.com").build(); - assertNull("should be null", validator.validateCreatePendingAccountRequest(request)); + assertNull("should be null", pendingAccountValidator.validateCreatePendingAccountRequest(request)); } @Test @@ -239,7 +243,7 @@ public class ValidatorTests { CreatePendingAccountRequest request = CreatePendingAccountRequest.newBuilder() .setAuthenticationType(AuthenticationType.EMAIL) .setAuthenticationProvider("invalid.E-mail1.@domain_test.com1").build(); - assertEquals(validator.validateCreatePendingAccountRequest(request), Cause.EMAIL_INVALID); + assertEquals(Cause.EMAIL_INVALID, pendingAccountValidator.validateCreatePendingAccountRequest(request)); } } diff --git a/src/test/java/biz/nynja/account/services/AccountServiceTests.java b/src/test/java/biz/nynja/account/services/AccountServiceTests.java index 7da87396bdf5a5034cf558dc56dc8e3b4eaf58f5..c3048e668765585bed47f76db790ef0ea35f6087 100644 --- a/src/test/java/biz/nynja/account/services/AccountServiceTests.java +++ b/src/test/java/biz/nynja/account/services/AccountServiceTests.java @@ -56,9 +56,13 @@ import biz.nynja.account.grpc.DeleteContactInfoRequest; import biz.nynja.account.grpc.DeleteProfileRequest; import biz.nynja.account.grpc.EditContactInfoRequest; import biz.nynja.account.grpc.ErrorResponse.Cause; +import biz.nynja.account.grpc.GetByEmailRequest; +import biz.nynja.account.grpc.GetByPhoneNumberRequest; +import biz.nynja.account.grpc.GetByQrCodeRequest; +import biz.nynja.account.grpc.GetByUsernameRequest; import biz.nynja.account.grpc.ProfileResponse; import biz.nynja.account.grpc.Role; -import biz.nynja.account.grpc.GetByUsernameRequest; +import biz.nynja.account.grpc.SearchResponse; import biz.nynja.account.grpc.StatusResponse; import biz.nynja.account.grpc.UpdateAccountRequest; import biz.nynja.account.grpc.UpdateProfileRequest; @@ -82,13 +86,9 @@ import biz.nynja.account.repositories.AccountRepositoryAdditional; import biz.nynja.account.repositories.PendingAccountRepository; import biz.nynja.account.repositories.ProfileByAuthenticationProviderRepository; import biz.nynja.account.repositories.ProfileRepository; -import biz.nynja.account.services.decomposition.AccountsProvider; +import biz.nynja.account.services.decomposition.AccountProvider; import biz.nynja.account.utils.GrpcServerTestBase; import biz.nynja.account.utils.Util; -import biz.nynja.account.grpc.GetByQrCodeRequest; -import biz.nynja.account.grpc.GetByEmailRequest; -import biz.nynja.account.grpc.GetByPhoneNumberRequest; -import biz.nynja.account.grpc.SearchResponse; /** * AccountService unit tests. @@ -207,9 +207,9 @@ public class AccountServiceTests extends GrpcServerTestBase { @MockBean private AccountByUsernameRepository accountByUsernameRepository; - + @MockBean - private AccountsProvider accountsProvider; + private AccountProvider accountProvider; @Test public void testGetAccountByAccountId() throws ExecutionException, InterruptedException { @@ -217,9 +217,9 @@ public class AccountServiceTests extends GrpcServerTestBase { .setAccountId(Util.ACCOUNT_ID.toString()).build(); Account account = savedAccount; - AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.toProto()).build(); + AccountResponse response = AccountResponse.newBuilder().setAccountDetails(account.toProto()).build(); Optional accountResponse = Optional.of(response); - given(accountsProvider.getAccountByAccountId(request)).willReturn(accountResponse); + given(accountProvider.getAccountByAccountId(request)).willReturn(accountResponse); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -272,14 +272,14 @@ public class AccountServiceTests extends GrpcServerTestBase { List accountByProfileId = new ArrayList<>(); accountByProfileId.add(savedAccountByProfileId); - - List responseList = accountByProfileId.stream().map(AccountByProfileId::toProto).collect(Collectors.toList()); + + List responseList = accountByProfileId.stream().map(AccountByProfileId::toProto) + .collect(Collectors.toList()); AccountsResponse aResponse = AccountsResponse.newBuilder() .setAccountsResponse(AccountsList.newBuilder().addAllAccountDetails(responseList)).build(); Optional response = Optional.of(aResponse); - given(accountsProvider.getAllAccountsByProfileId(request)) - .willReturn(response); + given(accountProvider.getAllAccountsByProfileId(request)).willReturn(response); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -330,10 +330,10 @@ public class AccountServiceTests extends GrpcServerTestBase { .setAuthenticationIdentifier(Util.PHONE_PROVIDER).setAuthenticationType(AuthenticationType.PHONE) .build(); - AccountResponse response = AccountResponse.newBuilder().setAccountDetails(accountByPhone.toProto()).build(); + AccountResponse response = AccountResponse.newBuilder().setAccountDetails(accountByPhone.toProto()).build(); Optional accountResponse = Optional.of(response); - - given(accountsProvider.getAccountResponseByAuthenticationProvider(AuthenticationType.PHONE, + + given(accountProvider.getAccountResponseByAuthenticationProvider(AuthenticationType.PHONE, Util.PHONE_PROVIDER)).willReturn(accountResponse); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc @@ -461,7 +461,7 @@ public class AccountServiceTests extends GrpcServerTestBase { AuthenticationProvider.createAuthenticationProviderFromStrings(request.getAuthenticationType().name(), request.getAuthenticationProvider()))) .willReturn(existingPendingAccountByAuthenticationProvider); - given(pendingAccountRepository.save(Mockito.any(PendingAccount.class))).willReturn(existingPendingAccount); + given(accountRepositoryAdditional.savePendingAccount(Mockito.any(PendingAccount.class))).willReturn(existingPendingAccount); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); final CreatePendingAccountResponse reply = accountServiceBlockingStub.createPendingAccount(request); @@ -500,7 +500,7 @@ public class AccountServiceTests extends GrpcServerTestBase { public void testCreatePendingAccountOK() { final CreatePendingAccountRequest request = CreatePendingAccountRequest.newBuilder() .setAuthenticationType(AuthenticationType.EMAIL).setAuthenticationProvider(Util.EMAIL).build(); - given(pendingAccountRepository.save(Mockito.any(PendingAccount.class))).willReturn(pendingAccount); + given(accountRepositoryAdditional.savePendingAccount(Mockito.any(PendingAccount.class))).willReturn(pendingAccount); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); final CreatePendingAccountResponse reply = accountServiceBlockingStub.createPendingAccount(request); @@ -514,7 +514,7 @@ public class AccountServiceTests extends GrpcServerTestBase { final CreatePendingAccountRequest request = CreatePendingAccountRequest.newBuilder() .setAuthenticationType(AuthenticationType.EMAIL) .setAuthenticationProvider("invalid.E-mail1.@domain_test.com1").build(); - given(pendingAccountRepository.save(Mockito.any(PendingAccount.class))).willReturn(pendingAccount); + given(accountRepositoryAdditional.savePendingAccount(Mockito.any(PendingAccount.class))).willReturn(pendingAccount); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); final CreatePendingAccountResponse reply = accountServiceBlockingStub.createPendingAccount(request); @@ -527,7 +527,7 @@ public class AccountServiceTests extends GrpcServerTestBase { public void testCreatePendingAccountInvalidPhone() { final CreatePendingAccountRequest request = CreatePendingAccountRequest.newBuilder() .setAuthenticationType(AuthenticationType.PHONE).setAuthenticationProvider("BG:084365:5555").build(); - given(pendingAccountRepository.save(Mockito.any(PendingAccount.class))).willReturn(pendingAccount); + given(accountRepositoryAdditional.savePendingAccount(Mockito.any(PendingAccount.class))).willReturn(pendingAccount); final AccountServiceGrpc.AccountServiceBlockingStub accountServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); final CreatePendingAccountResponse reply = accountServiceBlockingStub.createPendingAccount(request); @@ -1467,8 +1467,7 @@ public class AccountServiceTests extends GrpcServerTestBase { } public void testSearchByUsername() throws ExecutionException, InterruptedException { - final GetByUsernameRequest request = GetByUsernameRequest.newBuilder() - .setUsername(Util.S_USERNAME).build(); + final GetByUsernameRequest request = GetByUsernameRequest.newBuilder().setUsername(Util.S_USERNAME).build(); AccountByUsername response = savedResponse; @@ -1486,8 +1485,7 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByUsernameNotFound() throws ExecutionException, InterruptedException { - final GetByUsernameRequest request = GetByUsernameRequest.newBuilder() - .setUsername(Util.S_USERNAME).build(); + final GetByUsernameRequest request = GetByUsernameRequest.newBuilder().setUsername(Util.S_USERNAME).build(); AccountByUsername response = null; @@ -1519,8 +1517,8 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByUsernameInvalid() { - final GetByUsernameRequest request = GetByUsernameRequest.newBuilder() - .setUsername(Util.S_INVALID_USERNAME).build(); + final GetByUsernameRequest request = GetByUsernameRequest.newBuilder().setUsername(Util.S_INVALID_USERNAME) + .build(); final AccountServiceGrpc.AccountServiceBlockingStub searchServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -1534,12 +1532,13 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByPhoneNumber() throws ExecutionException, InterruptedException { - final GetByPhoneNumberRequest request = GetByPhoneNumberRequest.newBuilder() - .setPhoneNumber(Util.S_PHONE_NUMBER).build(); + final GetByPhoneNumberRequest request = GetByPhoneNumberRequest.newBuilder().setPhoneNumber(Util.S_PHONE_NUMBER) + .build(); Optional response = Optional.of(savedAccount); - - given(accountsProvider.getAccountByAuthenticationProvider(AuthenticationType.PHONE, request.getPhoneNumber())).willReturn(response); + + given(accountProvider.getAccountByAuthenticationProvider(AuthenticationType.PHONE, request.getPhoneNumber())) + .willReturn(response); final AccountServiceGrpc.AccountServiceBlockingStub searchServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -1553,12 +1552,13 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByPhoneNumberNotFound() throws ExecutionException, InterruptedException { - final GetByPhoneNumberRequest request = GetByPhoneNumberRequest.newBuilder() - .setPhoneNumber(Util.S_PHONE_NUMBER).build(); + final GetByPhoneNumberRequest request = GetByPhoneNumberRequest.newBuilder().setPhoneNumber(Util.S_PHONE_NUMBER) + .build(); List response = new LinkedList<>(); - given(accountByAuthenticationProviderRepository.findAllByAuthenticationProvider(request.getPhoneNumber())).willReturn(response); + given(accountByAuthenticationProviderRepository.findAllByAuthenticationProvider(request.getPhoneNumber())) + .willReturn(response); final AccountServiceGrpc.AccountServiceBlockingStub searchServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -1601,12 +1601,12 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByEmail() throws ExecutionException, InterruptedException { - final GetByEmailRequest request = GetByEmailRequest.newBuilder() - .setEmail(Util.S_EMAIL).build(); + final GetByEmailRequest request = GetByEmailRequest.newBuilder().setEmail(Util.S_EMAIL).build(); Optional response = Optional.of(savedAccount); - - given(accountsProvider.getAccountByAuthenticationProvider(AuthenticationType.EMAIL, request.getEmail())).willReturn(response); + + given(accountProvider.getAccountByAuthenticationProvider(AuthenticationType.EMAIL, request.getEmail())) + .willReturn(response); final AccountServiceGrpc.AccountServiceBlockingStub searchServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -1620,12 +1620,12 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByEmailNotFound() throws ExecutionException, InterruptedException { - final GetByEmailRequest request = GetByEmailRequest.newBuilder() - .setEmail(Util.S_EMAIL).build(); + final GetByEmailRequest request = GetByEmailRequest.newBuilder().setEmail(Util.S_EMAIL).build(); List response = new LinkedList<>(); - given(accountByAuthenticationProviderRepository.findAllByAuthenticationProvider(request.getEmail())).willReturn(response); + given(accountByAuthenticationProviderRepository.findAllByAuthenticationProvider(request.getEmail())) + .willReturn(response); final AccountServiceGrpc.AccountServiceBlockingStub searchServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -1653,8 +1653,7 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByEmailInvalid() { - final GetByEmailRequest request = GetByEmailRequest.newBuilder() - .setEmail(Util.S_INVALID_EMAIL).build(); + final GetByEmailRequest request = GetByEmailRequest.newBuilder().setEmail(Util.S_INVALID_EMAIL).build(); final AccountServiceGrpc.AccountServiceBlockingStub searchServiceBlockingStub = AccountServiceGrpc .newBlockingStub(Optional.ofNullable(channel).orElse(inProcChannel)); @@ -1668,8 +1667,7 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByQrCode() throws ExecutionException, InterruptedException { - final GetByQrCodeRequest request = GetByQrCodeRequest.newBuilder() - .setQrCode(Util.S_QR_CODE).build(); + final GetByQrCodeRequest request = GetByQrCodeRequest.newBuilder().setQrCode(Util.S_QR_CODE).build(); AccountByQrCode response = savedResponseQrCode; @@ -1687,8 +1685,7 @@ public class AccountServiceTests extends GrpcServerTestBase { @Test public void testSearchByQrCodeNotFound() throws ExecutionException, InterruptedException { - final GetByQrCodeRequest request = GetByQrCodeRequest.newBuilder() - .setQrCode(Util.S_QR_CODE).build(); + final GetByQrCodeRequest request = GetByQrCodeRequest.newBuilder().setQrCode(Util.S_QR_CODE).build(); AccountByQrCode response = null; diff --git a/src/test/java/biz/nynja/account/utils/Util.java b/src/test/java/biz/nynja/account/utils/Util.java index 11d213e1f912972c499dd77bcd81f2d58b997bbf..a55aa71b9545d420ff3c1c64518aad925ef90d53 100644 --- a/src/test/java/biz/nynja/account/utils/Util.java +++ b/src/test/java/biz/nynja/account/utils/Util.java @@ -44,7 +44,7 @@ public class Util { public static final String UPDATED_ACCOUNT_MARK = "PRIVATE"; public static final String AUTHENTICATION_PROVIDER = "Provider"; public static final String AUTHENTICATION_PROVIDER_TYPE = "ProviderType"; - public static final ByteBuffer AVATAR = ByteBuffer.allocate(42); + public static final String AVATAR = "avatar"; public static final String ACCOUNT_NAME = "AccountName"; public static final String ACCOUNT_STATUS = "active"; public static final long CREATION_TIMESTAMP = 45; @@ -283,7 +283,7 @@ public class Util { public AccountByUsername savedResponse() { AccountByUsername response = new AccountByUsername(); response.setAccountId(Util.ACCOUNT_ID); - response.setAvatar(ByteBuffer.wrap(S_AVATAR_STRING.getBytes())); + response.setAvatar(S_AVATAR_STRING); response.setFirstName(Util.S_FIRST_NAME); response.setLastName(Util.S_LAST_NAME); return response; @@ -293,7 +293,7 @@ public class Util { public AccountByAuthenticationProvider savedResponseProvider() { AccountByAuthenticationProvider response = new AccountByAuthenticationProvider(); response.setAccountId(Util.ACCOUNT_ID); - response.setAvatar(ByteBuffer.wrap(S_AVATAR_STRING.getBytes())); + response.setAvatar(S_AVATAR_STRING); response.setFirstName(Util.S_FIRST_NAME); response.setLastName(Util.S_LAST_NAME); return response; @@ -303,7 +303,7 @@ public class Util { public AccountByQrCode savedResponseQrCode() { AccountByQrCode response = new AccountByQrCode(); response.setAccountId(Util.ACCOUNT_ID); - response.setAvatar(ByteBuffer.wrap(S_AVATAR_STRING.getBytes())); + response.setAvatar(S_AVATAR_STRING); response.setFirstName(Util.S_FIRST_NAME); response.setLastName(Util.S_LAST_NAME); response.setQrCode(Util.S_QR_CODE);