private async Task <Tuple <RequestResult <UserProfileModel>, UserProfileModel> > ExecuteInsertUserProfile(Database.Constants.DBStatusCode dbResultStatus, string registrationStatus, MessagingVerification messagingVerification = null)
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true,
                Email = "*****@*****.**"
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.InsertUserProfile(It.Is <UserProfile>(x => x.HdId == userProfile.HdId))).Returns(new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = DBStatusCode.Created
            });

            Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>();

            configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration()
            {
                WebClient = new WebClientConfiguration()
                {
                    RegistrationStatus = registrationStatus
                }
            });

            Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>();

            cryptoDelegateMock.Setup(s => s.GenerateKey()).Returns("abc");

            Mock <INotificationSettingsService> notificationServiceMock = new Mock <INotificationSettingsService>();

            notificationServiceMock.Setup(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()));

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                new Mock <IPatientService>().Object,
                new Mock <IUserEmailService>().Object,
                new Mock <IUserSMSService>().Object,
                configServiceMock.Object,
                new Mock <IEmailQueueService>().Object,
                notificationServiceMock.Object,
                profileDelegateMock.Object,
                new Mock <IUserPreferenceDelegate>().Object,
                new Mock <ILegalAgreementDelegate>().Object,
                new Mock <IMessagingVerificationDelegate>().Object,
                cryptoDelegateMock.Object,
                new Mock <IHttpContextAccessor>().Object);

            RequestResult <UserProfileModel> actualResult = await service.CreateUserProfile(new CreateUserRequest()
            {
                Profile = userProfile
            }, DateTime.Today);

            return(new Tuple <RequestResult <UserProfileModel>, UserProfileModel>(actualResult, expected));
        }
示例#2
0
        /// <inheritdoc />
        public RequestResult <UserProfileModel> GetUserProfile(string hdid, DateTime jwtAuthTime)
        {
            this.logger.LogTrace($"Getting user profile... {hdid}");
            DBResult <UserProfile> retVal = this.userProfileDelegate.GetUserProfile(hdid);

            this.logger.LogDebug($"Finished getting user profile. {JsonSerializer.Serialize(retVal)}");

            if (retVal.Status == DBStatusCode.NotFound)
            {
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = ResultType.Success,
                    ResourcePayload = new UserProfileModel(),
                });
            }

            DateTime previousLastLogin = retVal.Payload.LastLoginDateTime;

            if (DateTime.Compare(previousLastLogin, jwtAuthTime) != 0)
            {
                this.logger.LogTrace($"Updating user last login... {hdid}");
                retVal.Payload.LastLoginDateTime = jwtAuthTime;
                DBResult <UserProfile> updateResult = this.userProfileDelegate.Update(retVal.Payload);
                this.logger.LogDebug($"Finished updating user last login. {JsonSerializer.Serialize(updateResult)}");
            }

            RequestResult <TermsOfServiceModel> termsOfServiceResult = this.GetActiveTermsOfService();

            UserProfileModel userProfile = UserProfileModel.CreateFromDbModel(retVal.Payload);

            userProfile.HasTermsOfServiceUpdated = termsOfServiceResult.ResourcePayload?.EffectiveDate > previousLastLogin;

            if (!userProfile.IsEmailVerified)
            {
                this.logger.LogTrace($"Retrieving last email invite... {hdid}");
                MessagingVerification?emailInvite = this.messageVerificationDelegate.GetLastForUser(hdid, MessagingVerificationType.Email);
                this.logger.LogDebug($"Finished retrieving email: {JsonSerializer.Serialize(emailInvite)}");
                userProfile.Email = emailInvite?.Email?.To;
            }

            if (!userProfile.IsSMSNumberVerified)
            {
                this.logger.LogTrace($"Retrieving last email invite... {hdid}");
                MessagingVerification?smsInvite = this.messageVerificationDelegate.GetLastForUser(hdid, MessagingVerificationType.SMS);
                this.logger.LogDebug($"Finished retrieving email: {JsonSerializer.Serialize(smsInvite)}");
                userProfile.SMSNumber = smsInvite?.SMSNumber;
            }

            return(new RequestResult <UserProfileModel>()
            {
                ResultStatus = retVal.Status != DBStatusCode.Error ? ResultType.Success : ResultType.Error,
                ResultError = retVal.Status != DBStatusCode.Error ? null : new RequestResultError()
                {
                    ResultMessage = retVal.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                },
                ResourcePayload = userProfile,
            });
        }
        private Tuple <RequestResult <UserProfileModel>, UserProfileModel> ExecuteRecoverUserProfile(UserProfile userProfile, Database.Constants.DBStatusCode dbResultStatus = Database.Constants.DBStatusCode.Read)
        {
            DBResult <UserProfile> userProfileDBResult = new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = dbResultStatus
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.GetUserProfile(hdid)).Returns(userProfileDBResult);
            profileDelegateMock.Setup(s => s.Update(userProfile, true)).Returns(userProfileDBResult);

            Mock <IEmailQueueService> emailQueueServiceMock = new Mock <IEmailQueueService>();

            emailQueueServiceMock
            .Setup(s => s.QueueNewEmail(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), false));

            IHeaderDictionary headerDictionary = new HeaderDictionary();

            headerDictionary.Add("referer", "http://localhost/");
            Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary);
            Mock <HttpContext> httpContextMock = new Mock <HttpContext>();

            httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object);
            Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object);

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                new Mock <IPatientService>().Object,
                new Mock <IUserEmailService>().Object,
                new Mock <IUserSMSService>().Object,
                new Mock <IConfigurationService>().Object,
                emailQueueServiceMock.Object,
                new Mock <INotificationSettingsService>().Object,
                profileDelegateMock.Object,
                new Mock <IUserPreferenceDelegate>().Object,
                new Mock <ILegalAgreementDelegate>().Object,
                new Mock <IMessagingVerificationDelegate>().Object,
                new Mock <ICryptoDelegate>().Object,
                httpContextAccessorMock.Object);

            RequestResult <UserProfileModel> actualResult = service.RecoverUserProfile(hdid);

            return(new Tuple <RequestResult <UserProfileModel>, UserProfileModel>(actualResult, expected));
        }
        private static RequestResult <UserProfileModel> GetUserProfileExpectedRequestResultMock(ResultType resultType)
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true
            };

            return(new RequestResult <UserProfileModel>
            {
                ResourcePayload = UserProfileModel.CreateFromDbModel(userProfile),
                ResultStatus = Common.Constants.ResultType.Success
            });
        }
示例#5
0
        /// <inheritdoc />
        public RequestResult <UserProfileModel> GetUserProfile(string hdid, DateTime?lastLogin = null)
        {
            this.logger.LogTrace($"Getting user profile... {hdid}");
            DBResult <UserProfile> retVal = this.userProfileDelegate.GetUserProfile(hdid);

            this.logger.LogDebug($"Finished getting user profile. {JsonSerializer.Serialize(retVal)}");

            if (retVal.Status == DBStatusCode.NotFound)
            {
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = retVal.Status != DBStatusCode.Error ? ResultType.Success : ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = retVal.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                    },
                    ResourcePayload = null,
                });
            }

            DateTime?previousLastLogin = retVal.Payload.LastLoginDateTime;

            if (lastLogin.HasValue)
            {
                this.logger.LogTrace($"Updating user last login... {hdid}");
                retVal.Payload.LastLoginDateTime = lastLogin;
                DBResult <UserProfile> updateResult = this.userProfileDelegate.Update(retVal.Payload);
                this.logger.LogDebug($"Finished updating user last login. {JsonSerializer.Serialize(updateResult)}");
            }

            RequestResult <TermsOfServiceModel> termsOfServiceResult = this.GetActiveTermsOfService();

            UserProfileModel userProfile = UserProfileModel.CreateFromDbModel(retVal.Payload);

            userProfile.HasTermsOfServiceUpdated =
                previousLastLogin.HasValue &&
                termsOfServiceResult.ResourcePayload?.EffectiveDate > previousLastLogin.Value;

            return(new RequestResult <UserProfileModel>()
            {
                ResultStatus = retVal.Status != DBStatusCode.Error ? ResultType.Success : ResultType.Error,
                ResultError = retVal.Status != DBStatusCode.Error ? null : new RequestResultError()
                {
                    ResultMessage = retVal.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                },
                ResourcePayload = userProfile,
            });
        }
        public void ShouldGetUserProfile()
        {
            // Setup
            string hdid   = "1234567890123456789012345678901234567890123456789012";
            string token  = "Fake Access Token";
            string userId = "1001";

            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true
            };

            RequestResult <UserProfileModel> expected = new RequestResult <UserProfileModel>
            {
                ResourcePayload = UserProfileModel.CreateFromDbModel(userProfile),
                ResultStatus    = Common.Constants.ResultType.Success
            };

            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);

            Mock <IUserProfileService> userProfileServiceMock = new Mock <IUserProfileService>();

            userProfileServiceMock.Setup(s => s.GetUserProfile(hdid, It.IsAny <DateTime>())).Returns(expected);
            userProfileServiceMock.Setup(s => s.GetActiveTermsOfService()).Returns(new RequestResult <TermsOfServiceModel>());
            userProfileServiceMock.Setup(s => s.GetUserPreferences(hdid)).Returns(new RequestResult <Dictionary <string, string> >()
            {
                ResourcePayload = new Dictionary <string, string>()
                {
                }
            });

            Mock <IUserEmailService> emailServiceMock = new Mock <IUserEmailService>();
            Mock <IUserSMSService>   smsServiceMock   = new Mock <IUserSMSService>();

            UserProfileController service = new UserProfileController(
                new Mock <ILogger <UserProfileController> >().Object,
                userProfileServiceMock.Object,
                httpContextAccessorMock.Object,
                emailServiceMock.Object,
                smsServiceMock.Object
                );
            IActionResult actualResult = service.GetUserProfile(hdid);

            Assert.IsType <JsonResult>(actualResult);
            Assert.True(((JsonResult)actualResult).Value.IsDeepEqual(expected));
        }
示例#7
0
        public RequestResult <UserProfileModel> RecoverUserProfile(string hdid)
        {
            this.logger.LogTrace($"Recovering user profile... {hdid}");

            DBResult <UserProfile> retrieveResult = this.userProfileDelegate.GetUserProfile(hdid);

            if (retrieveResult.Status == DBStatusCode.Read)
            {
                UserProfile profile = retrieveResult.Payload;
                if (profile.ClosedDateTime == null)
                {
                    this.logger.LogTrace("Finished. Profile already is active, recover not needed.");
                    return(new RequestResult <UserProfileModel>()
                    {
                        ResourcePayload = UserProfileModel.CreateFromDbModel(profile),
                        ResultStatus = ResultType.Success,
                    });
                }

                // Remove values set for deletion
                profile.ClosedDateTime       = null;
                profile.IdentityManagementId = null;
                DBResult <UserProfile> updateResult = this.userProfileDelegate.Update(profile);
                if (!string.IsNullOrWhiteSpace(profile.Email))
                {
                    this.QueueEmail(profile.Email, EmailTemplateName.AccountRecoveredTemplate);
                }

                this.logger.LogDebug($"Finished recovering user profile. {JsonSerializer.Serialize(updateResult)}");
                return(new RequestResult <UserProfileModel>()
                {
                    ResourcePayload = UserProfileModel.CreateFromDbModel(updateResult.Payload),
                    ResultStatus = ResultType.Success,
                });
            }
            else
            {
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = retrieveResult.Message, ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database)
                    },
                });
            }
        }
        public async Task ShouldCreateUserProfile()
        {
            string hdid   = "1234567890123456789012345678901234567890123456789012";
            string token  = "Fake Access Token";
            string userId = "1001";

            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true
            };

            CreateUserRequest createUserRequest = new CreateUserRequest
            {
                Profile = userProfile
            };

            RequestResult <UserProfileModel> expected = new RequestResult <UserProfileModel>
            {
                ResourcePayload = UserProfileModel.CreateFromDbModel(userProfile),
                ResultStatus    = Common.Constants.ResultType.Success
            };

            Mock <IHttpContextAccessor> httpContextAccessorMock = CreateValidHttpContext(token, userId, hdid);

            Mock <IUserProfileService> userProfileServiceMock = new Mock <IUserProfileService>();

            userProfileServiceMock.Setup(s => s.CreateUserProfile(createUserRequest, It.IsAny <DateTime>())).ReturnsAsync(expected);
            Mock <IUserEmailService> emailServiceMock = new Mock <IUserEmailService>();
            Mock <IUserSMSService>   smsServiceMock   = new Mock <IUserSMSService>();

            UserProfileController service = new UserProfileController(
                new Mock <ILogger <UserProfileController> >().Object,
                userProfileServiceMock.Object,
                httpContextAccessorMock.Object,
                emailServiceMock.Object,
                smsServiceMock.Object
                );
            IActionResult actualResult = await service.CreateUserProfile(hdid, createUserRequest);

            Assert.IsType <JsonResult>(actualResult);
            Assert.True(((JsonResult)actualResult).Value.IsDeepEqual(expected));
        }
        public RequestResult <UserProfileModel> RecoverUserProfile(string hdid, string hostUrl)
        {
            this.logger.LogTrace($"Recovering user profile... {hdid}");

            string registrationStatus = this.configurationService.GetConfiguration().WebClient.RegistrationStatus;

            RequestResult <UserProfileModel> requestResult = new RequestResult <UserProfileModel>();

            DBResult <UserProfile> retrieveResult = this.userProfileDelegate.GetUserProfile(hdid);

            if (retrieveResult.Status == DBStatusCode.Read)
            {
                UserProfile profile = retrieveResult.Payload;
                if (profile.ClosedDateTime == null)
                {
                    this.logger.LogTrace("Finished. Profile already is active, recover not needed.");
                    requestResult.ResourcePayload = UserProfileModel.CreateFromDbModel(profile);
                    requestResult.ResultStatus    = ResultType.Success;
                    return(requestResult);
                }

                // Remove values set for deletion
                profile.ClosedDateTime       = null;
                profile.IdentityManagementId = null;
                DBResult <UserProfile> updateResult = this.userProfileDelegate.Update(profile);
                if (!string.IsNullOrWhiteSpace(profile.Email))
                {
                    Dictionary <string, string> keyValues = new Dictionary <string, string>();
                    keyValues.Add(HostTemplateVariable, hostUrl);
                    this.emailQueueService.QueueNewEmail(profile.Email, EmailTemplateName.AccountRecoveredTemplate, keyValues);
                }

                requestResult.ResourcePayload = UserProfileModel.CreateFromDbModel(updateResult.Payload);
                requestResult.ResultStatus    = ResultType.Success;
                this.logger.LogDebug($"Finished recovering user profile. {JsonSerializer.Serialize(updateResult)}");
            }

            return(requestResult);
        }
        /// <inheritdoc />
        public async Task <RequestResult <UserProfileModel> > CreateUserProfile(CreateUserRequest createProfileRequest, Uri hostUri, string bearerToken)
        {
            this.logger.LogTrace($"Creating user profile... {JsonSerializer.Serialize(createProfileRequest)}");

            string registrationStatus = this.configurationService.GetConfiguration().WebClient.RegistrationStatus;

            RequestResult <UserProfileModel> requestResult = new RequestResult <UserProfileModel>();

            if (registrationStatus == RegistrationStatus.Closed)
            {
                requestResult.ResultStatus = ResultType.Error;
                requestResult.ResultError  = new RequestResultError()
                {
                    ResultMessage = "Registration is closed", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState)
                };
                this.logger.LogWarning($"Registration is closed. {JsonSerializer.Serialize(createProfileRequest)}");
                return(requestResult);
            }

            string hdid = createProfileRequest.Profile.HdId;
            MessagingVerification?emailInvite = null;

            if (registrationStatus == RegistrationStatus.InviteOnly)
            {
                if (!Guid.TryParse(createProfileRequest.InviteCode, out Guid inviteKey))
                {
                    requestResult.ResultStatus = ResultType.Error;
                    requestResult.ResultError  = new RequestResultError()
                    {
                        ResultMessage = "Invalid email invite", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState)
                    };
                    this.logger.LogWarning($"Invalid email invite code. {JsonSerializer.Serialize(createProfileRequest)}");
                    return(requestResult);
                }

                emailInvite = this.emailInviteDelegate.GetByInviteKey(inviteKey);
                bool hdidIsValid = string.IsNullOrEmpty(emailInvite?.HdId) || (emailInvite?.HdId == createProfileRequest.Profile.HdId);

                // Fails if...
                // Email invite not found or
                // Email invite was already validated or
                // Email's recipient is not found
                // Email invite must have a blank/null HDID or be the same as the one in the request
                // Email address doesn't match the invite
                if (emailInvite == null || (emailInvite.Email == null || emailInvite.Email.To == null ||
                                            emailInvite.Validated || !hdidIsValid ||
                                            !emailInvite.Email.To.Equals(createProfileRequest.Profile.Email, StringComparison.OrdinalIgnoreCase)))
                {
                    requestResult.ResultStatus = ResultType.Error;
                    requestResult.ResultError  = new RequestResultError()
                    {
                        ResultMessage = "Invalid email invite", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState)
                    };
                    this.logger.LogWarning($"Invalid email invite. {JsonSerializer.Serialize(createProfileRequest)}");
                    return(requestResult);
                }
            }

            PrimitiveRequestResult <bool> isMimimunAgeResult = await this.ValidateMinimumAge(hdid).ConfigureAwait(true);

            if (isMimimunAgeResult.ResultStatus != ResultType.Success)
            {
                requestResult.ResultStatus = isMimimunAgeResult.ResultStatus;
                requestResult.ResultError  = isMimimunAgeResult.ResultError;
                return(requestResult);
            }
            else if (!isMimimunAgeResult.ResourcePayload)
            {
                requestResult.ResultStatus = ResultType.Error;
                requestResult.ResultError  = new RequestResultError()
                {
                    ResultMessage = "Patient under minimum age", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState)
                };
                this.logger.LogWarning($"Patient under minimum age. {JsonSerializer.Serialize(createProfileRequest)}");
                return(requestResult);
            }

            string?     requestedSMSNumber = createProfileRequest.Profile.SMSNumber;
            string?     requestedEmail     = createProfileRequest.Profile.Email;
            UserProfile newProfile         = createProfileRequest.Profile;

            newProfile.Email         = string.Empty;
            newProfile.SMSNumber     = null;
            newProfile.CreatedBy     = hdid;
            newProfile.UpdatedBy     = hdid;
            newProfile.EncryptionKey = this.cryptoDelegate.GenerateKey();

            DBResult <UserProfile> insertResult = this.userProfileDelegate.InsertUserProfile(newProfile);

            if (insertResult.Status == DBStatusCode.Created)
            {
                // Update the notification settings
                NotificationSettingsRequest notificationRequest = this.UpdateNotificationSettings(newProfile, requestedSMSNumber);

                if (emailInvite != null)
                {
                    // Validates the invite email
                    emailInvite.Validated = true;
                    emailInvite.HdId      = hdid;
                    this.emailInviteDelegate.Update(emailInvite);
                }

                if (!string.IsNullOrWhiteSpace(requestedEmail))
                {
                    this.emailQueueService.QueueNewInviteEmail(hdid, requestedEmail, hostUri);
                }

                if (!string.IsNullOrWhiteSpace(requestedSMSNumber))
                {
                    this.logger.LogInformation($"Sending sms invite for user ${hdid}");
                    MessagingVerification messagingVerification = new MessagingVerification();
                    messagingVerification.HdId              = hdid;
                    messagingVerification.SMSNumber         = requestedSMSNumber;
                    messagingVerification.SMSValidationCode = notificationRequest.SMSVerificationCode;
                    messagingVerification.VerificationType  = MessagingVerificationType.SMS;
                    messagingVerification.ExpireDate        = DateTime.MaxValue;
                    this.messageVerificationDelegate.Insert(messagingVerification);
                }

                requestResult.ResourcePayload = UserProfileModel.CreateFromDbModel(insertResult.Payload);
                requestResult.ResultStatus    = ResultType.Success;
            }

            this.logger.LogDebug($"Finished creating user profile. {JsonSerializer.Serialize(insertResult)}");
            return(requestResult);
        }
        // TODO: Remove helper methods
        private Tuple <RequestResult <UserProfileModel>, UserProfileModel> ExecuteGetUserProfile(Database.Constants.DBStatusCode dbResultStatus, DateTime lastLoginDateTime)
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true,
                LastLoginDateTime      = lastLoginDateTime,
            };

            DBResult <UserProfile> userProfileDBResult = new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = dbResultStatus
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            expected.HasTermsOfServiceUpdated = true;

            LegalAgreement termsOfService = new LegalAgreement()
            {
                Id            = Guid.NewGuid(),
                LegalText     = "",
                EffectiveDate = DateTime.Now
            };

            Mock <IEmailQueueService>   emailer             = new Mock <IEmailQueueService>();
            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.GetUserProfile(hdid)).Returns(userProfileDBResult);
            profileDelegateMock.Setup(s => s.Update(userProfile, true)).Returns(userProfileDBResult);

            UserPreference dbUserPreference = new UserPreference
            {
                HdId       = hdid,
                Preference = "TutorialPopover",
                Value      = true.ToString(),
            };
            List <UserPreference> userPreferences = new List <UserPreference>();

            userPreferences.Add(dbUserPreference);
            DBResult <IEnumerable <UserPreference> > readResult = new DBResult <IEnumerable <UserPreference> >
            {
                Payload = userPreferences,
                Status  = DBStatusCode.Read
            };
            Mock <IUserPreferenceDelegate> preferenceDelegateMock = new Mock <IUserPreferenceDelegate>();

            preferenceDelegateMock.Setup(s => s.GetUserPreferences(hdid)).Returns(readResult);

            Mock <IMessagingVerificationDelegate> emailInviteDelegateMock = new Mock <IMessagingVerificationDelegate>();

            emailInviteDelegateMock.Setup(s => s.GetLastByInviteKey(It.IsAny <Guid>())).Returns(new MessagingVerification());

            Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>();

            configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration());

            Mock <ILegalAgreementDelegate> legalAgreementDelegateMock = new Mock <ILegalAgreementDelegate>();

            legalAgreementDelegateMock
            .Setup(s => s.GetActiveByAgreementType(LegalAgreementType.TermsofService))
            .Returns(new DBResult <LegalAgreement>()
            {
                Payload = termsOfService
            });

            Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>();
            Mock <INotificationSettingsService>   notificationServiceMock         = new Mock <INotificationSettingsService>();
            Mock <IMessagingVerificationDelegate> messageVerificationDelegateMock = new Mock <IMessagingVerificationDelegate>();

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                new Mock <IPatientService>().Object,
                new Mock <IUserEmailService>().Object,
                new Mock <IUserSMSService>().Object,
                configServiceMock.Object,
                new Mock <IEmailQueueService>().Object,
                notificationServiceMock.Object,
                profileDelegateMock.Object,
                preferenceDelegateMock.Object,
                legalAgreementDelegateMock.Object,
                messageVerificationDelegateMock.Object,
                cryptoDelegateMock.Object,
                new Mock <IHttpContextAccessor>().Object
                );

            RequestResult <UserProfileModel> actualResult = service.GetUserProfile(hdid, DateTime.Now);

            return(new Tuple <RequestResult <UserProfileModel>, UserProfileModel>(actualResult, expected));
        }
        public async void ShouldQueueNotificationUpdate()
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = "1234567890123456789012345678901234567890123456789012",
                AcceptedTermsOfService = true,
                Email = string.Empty
            };

            DBResult <UserProfile> insertResult = new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = DBStatusCode.Created
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            Mock <IEmailQueueService>   emailer             = new Mock <IEmailQueueService>();
            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.InsertUserProfile(It.Is <UserProfile>(x => x.HdId == userProfile.HdId))).Returns(insertResult);
            Mock <IUserPreferenceDelegate> preferenceDelegateMock = new Mock <IUserPreferenceDelegate>();

            Mock <IEmailDelegate> emailDelegateMock = new Mock <IEmailDelegate>();
            Mock <IMessagingVerificationDelegate> emailInviteDelegateMock = new Mock <IMessagingVerificationDelegate>();

            emailInviteDelegateMock.Setup(s => s.GetLastByInviteKey(It.IsAny <Guid>())).Returns(new MessagingVerification());

            Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>();

            configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration()
            {
                WebClient = new WebClientConfiguration()
                {
                    RegistrationStatus = RegistrationStatus.Open
                }
            });

            Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>();

            cryptoDelegateMock.Setup(s => s.GenerateKey()).Returns("abc");

            Mock <INotificationSettingsService> notificationServiceMock = new Mock <INotificationSettingsService>();

            notificationServiceMock.Setup(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()));

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                new Mock <IPatientService>().Object,
                new Mock <IUserEmailService>().Object,
                new Mock <IUserSMSService>().Object,
                configServiceMock.Object,
                new Mock <IEmailQueueService>().Object,
                notificationServiceMock.Object,
                profileDelegateMock.Object,
                preferenceDelegateMock.Object,
                new Mock <ILegalAgreementDelegate>().Object,
                new Mock <IMessagingVerificationDelegate>().Object,
                cryptoDelegateMock.Object,
                new Mock <IHttpContextAccessor>().Object);

            // Execute
            RequestResult <UserProfileModel> actualResult = await service.CreateUserProfile(new CreateUserRequest()
            {
                Profile = userProfile
            }, DateTime.Today);

            // Verify
            notificationServiceMock.Verify(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()), Times.Once());
            Assert.Equal(ResultType.Success, actualResult.ResultStatus);
            Assert.Equal(expected.HdId, actualResult.ResourcePayload.HdId);
            Assert.Equal(expected.AcceptedTermsOfService, actualResult.ResourcePayload.AcceptedTermsOfService);
            Assert.Equal(expected.Email, actualResult.ResourcePayload.Email);
        }
示例#13
0
        /// <inheritdoc />
        public async Task <RequestResult <UserProfileModel> > CreateUserProfile(CreateUserRequest createProfileRequest, DateTime jwtAuthTime)
        {
            this.logger.LogTrace($"Creating user profile... {JsonSerializer.Serialize(createProfileRequest)}");

            string registrationStatus = this.configurationService.GetConfiguration().WebClient.RegistrationStatus;

            if (registrationStatus == RegistrationStatus.Closed)
            {
                this.logger.LogWarning($"Registration is closed. {JsonSerializer.Serialize(createProfileRequest)}");
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = "Registration is closed",
                        ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState),
                    },
                });
            }

            // Validate registration age
            string hdid = createProfileRequest.Profile.HdId;
            PrimitiveRequestResult <bool> isMimimunAgeResult = await this.ValidateMinimumAge(hdid).ConfigureAwait(true);

            if (isMimimunAgeResult.ResultStatus != ResultType.Success)
            {
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = isMimimunAgeResult.ResultStatus,
                    ResultError = isMimimunAgeResult.ResultError,
                });
            }
            else if (!isMimimunAgeResult.ResourcePayload)
            {
                this.logger.LogWarning($"Patient under minimum age. {JsonSerializer.Serialize(createProfileRequest)}");
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = "Patient under minimum age",
                        ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState),
                    },
                });
            }

            // Create profile
            UserProfile newProfile = new ()
            {
                HdId = hdid,
                IdentityManagementId   = createProfileRequest.Profile.IdentityManagementId,
                AcceptedTermsOfService = createProfileRequest.Profile.AcceptedTermsOfService,
                Email             = string.Empty,
                SMSNumber         = null,
                CreatedBy         = hdid,
                UpdatedBy         = hdid,
                LastLoginDateTime = jwtAuthTime,
                EncryptionKey     = this.cryptoDelegate.GenerateKey(),
            };
            DBResult <UserProfile> insertResult = this.userProfileDelegate.InsertUserProfile(newProfile);

            if (insertResult.Status == DBStatusCode.Created)
            {
                UserProfile createdProfile     = insertResult.Payload;
                string?     requestedSMSNumber = createProfileRequest.Profile.SMSNumber;
                string?     requestedEmail     = createProfileRequest.Profile.Email;

                // Add email verification
                if (!string.IsNullOrWhiteSpace(requestedEmail))
                {
                    this.userEmailService.CreateUserEmail(hdid, requestedEmail);
                }

                // Add SMS verification
                if (!string.IsNullOrWhiteSpace(requestedSMSNumber))
                {
                    this.userSMSService.CreateUserSMS(hdid, requestedSMSNumber);
                }

                this.notificationSettingsService.QueueNotificationSettings(new NotificationSettingsRequest(createdProfile, requestedEmail, requestedSMSNumber));

                this.logger.LogDebug($"Finished creating user profile. {JsonSerializer.Serialize(insertResult)}");
                return(new RequestResult <UserProfileModel>()
                {
                    ResourcePayload = UserProfileModel.CreateFromDbModel(insertResult.Payload),
                    ResultStatus = ResultType.Success,
                });
            }
            else
            {
                this.logger.LogError($"Error creating user profile. {JsonSerializer.Serialize(insertResult)}");
                return(new RequestResult <UserProfileModel>()
                {
                    ResultStatus = ResultType.Error,
                    ResultError = new RequestResultError()
                    {
                        ResultMessage = insertResult.Message,
                        ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationInternal, ServiceType.Database),
                    },
                });
            }
        }
        public void ShouldGetUserProfile()
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = hdid,
                AcceptedTermsOfService = true,
            };

            DBResult <UserProfile> userProfileDBResult = new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = DBStatusCode.Read
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            LegalAgreement termsOfService = new LegalAgreement()
            {
                Id            = Guid.NewGuid(),
                LegalText     = "",
                EffectiveDate = DateTime.Now
            };

            Mock <IEmailQueueService>   emailer             = new Mock <IEmailQueueService>();
            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.GetUserProfile(hdid)).Returns(userProfileDBResult);
            profileDelegateMock.Setup(s => s.Update(userProfile, true)).Returns(userProfileDBResult);

            UserPreference dbUserPreference = new UserPreference
            {
                HdId       = hdid,
                Preference = "TutorialPopover",
                Value      = true.ToString(),
            };
            List <UserPreference> userPreferences = new List <UserPreference>();

            userPreferences.Add(dbUserPreference);
            DBResult <IEnumerable <UserPreference> > readResult = new DBResult <IEnumerable <UserPreference> >
            {
                Payload = userPreferences,
                Status  = DBStatusCode.Read
            };
            Mock <IUserPreferenceDelegate> preferenceDelegateMock = new Mock <IUserPreferenceDelegate>();

            preferenceDelegateMock.Setup(s => s.GetUserPreferences(hdid)).Returns(readResult);

            Mock <IEmailDelegate> emailDelegateMock = new Mock <IEmailDelegate>();
            Mock <IMessagingVerificationDelegate> emailInviteDelegateMock = new Mock <IMessagingVerificationDelegate>();

            emailInviteDelegateMock.Setup(s => s.GetByInviteKey(It.IsAny <Guid>())).Returns(new MessagingVerification());

            Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>();

            configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration());

            Mock <ILegalAgreementDelegate> legalAgreementDelegateMock = new Mock <ILegalAgreementDelegate>();

            legalAgreementDelegateMock
            .Setup(s => s.GetActiveByAgreementType(AgreementType.TermsofService))
            .Returns(new DBResult <LegalAgreement>()
            {
                Payload = termsOfService
            });

            Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>();
            Mock <INotificationSettingsService>   notificationServiceMock         = new Mock <INotificationSettingsService>();
            Mock <IMessagingVerificationDelegate> messageVerificationDelegateMock = new Mock <IMessagingVerificationDelegate>();

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                profileDelegateMock.Object,
                preferenceDelegateMock.Object,
                emailDelegateMock.Object,
                emailInviteDelegateMock.Object,
                configServiceMock.Object,
                emailer.Object,
                legalAgreementDelegateMock.Object,
                cryptoDelegateMock.Object,
                notificationServiceMock.Object,
                messageVerificationDelegateMock.Object);

            RequestResult <UserProfileModel> actualResult = service.GetUserProfile(hdid);

            Assert.Equal(ResultType.Success, actualResult.ResultStatus);
            Assert.True(actualResult.ResourcePayload.IsDeepEqual(expected));
        }
        public void ShouldQueueNotificationUpdate()
        {
            UserProfile userProfile = new UserProfile
            {
                HdId = "1234567890123456789012345678901234567890123456789012",
                AcceptedTermsOfService = true,
                Email = string.Empty
            };

            DBResult <UserProfile> insertResult = new DBResult <UserProfile>
            {
                Payload = userProfile,
                Status  = DBStatusCode.Created
            };

            UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile);

            Mock <IEmailQueueService>   emailer             = new Mock <IEmailQueueService>();
            Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>();

            profileDelegateMock.Setup(s => s.InsertUserProfile(userProfile)).Returns(insertResult);
            Mock <IUserPreferenceDelegate> preferenceDelegateMock = new Mock <IUserPreferenceDelegate>();

            Mock <IEmailDelegate> emailDelegateMock = new Mock <IEmailDelegate>();
            Mock <IMessagingVerificationDelegate> emailInviteDelegateMock = new Mock <IMessagingVerificationDelegate>();

            emailInviteDelegateMock.Setup(s => s.GetByInviteKey(It.IsAny <Guid>())).Returns(new MessagingVerification());

            Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>();

            configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration()
            {
                WebClient = new WebClientConfiguration()
                {
                    RegistrationStatus = RegistrationStatus.Open
                }
            });

            Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>();

            cryptoDelegateMock.Setup(s => s.GenerateKey()).Returns("abc");

            Mock <INotificationSettingsService> notificationServiceMock = new Mock <INotificationSettingsService>();

            notificationServiceMock.Setup(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()));

            Mock <IMessagingVerificationDelegate> messageVerificationDelegateMock = new Mock <IMessagingVerificationDelegate>();

            IUserProfileService service = new UserProfileService(
                new Mock <ILogger <UserProfileService> >().Object,
                profileDelegateMock.Object,
                preferenceDelegateMock.Object,
                emailDelegateMock.Object,
                emailInviteDelegateMock.Object,
                configServiceMock.Object,
                emailer.Object,
                new Mock <ILegalAgreementDelegate>().Object,
                cryptoDelegateMock.Object,
                notificationServiceMock.Object,
                messageVerificationDelegateMock.Object);

            RequestResult <UserProfileModel> actualResult = service.CreateUserProfile(new CreateUserRequest()
            {
                Profile = userProfile
            }, new Uri("http://localhost/"), "bearer_token");

            notificationServiceMock.Verify(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()), Times.Once());
            Assert.Equal(ResultType.Success, actualResult.ResultStatus);
            Assert.True(actualResult.ResourcePayload.IsDeepEqual(expected));
        }