public void ShouldCreateSMSCode()
        {
            var mockLogger     = new Mock <ILogger <NotificationSettingsService> >();
            var mockJobClient  = new Mock <IBackgroundJobClient>();
            var mockNSDelegate = new Mock <INotificationSettingsDelegate>();

            INotificationSettingsService service = new NotificationSettingsService(
                mockLogger.Object,
                mockJobClient.Object,
                mockNSDelegate.Object);

            NotificationSettingsRequest nsr = new NotificationSettingsRequest()
            {
                EmailEnabled = true,
                EmailAddress = "*****@*****.**",
                SMSEnabled   = true,
                SMSNumber    = "2505555555",
                SubjectHdid  = "hdid",
                SMSVerified  = false,
            };

            Assert.True(nsr.SMSVerificationCode == null);
            service.QueueNotificationSettings(nsr);

            mockJobClient.Verify(x => x.Create(
                                     It.Is <Job>(job => job.Method.Name == "PushNotificationSettings" && job.Args[0] is string),
                                     It.IsAny <EnqueuedState>()));

            Assert.True(nsr.SMSVerificationCode != null);
        }
Exemplo n.º 2
0
        public object Post(NotificationSettingsRequest request)
        {
            if (!request.AccountId.HasValue)
            {
                if (!SessionAs <AuthUserSession>().HasPermission(RoleName.Admin))
                {
                    return(new HttpError(HttpStatusCode.Unauthorized, "You do not have permission to modify company settings"));
                }

                _commandBus.Send(new AddOrUpdateNotificationSettings
                {
                    CompanyId            = AppConstants.CompanyId,
                    NotificationSettings = request.NotificationSettings
                });
            }
            else
            {
                _commandBus.Send(new AddOrUpdateNotificationSettings
                {
                    AccountId            = request.AccountId.Value,
                    CompanyId            = AppConstants.CompanyId,
                    NotificationSettings = request.NotificationSettings
                });
            }

            return(new HttpResult(HttpStatusCode.OK, "OK"));
        }
Exemplo n.º 3
0
        /// <inheritdoc />
        public bool UpdateUserSMS(string hdid, string sms)
        {
            this.logger.LogTrace($"Removing user sms number ${hdid}");
            sms = this.SanitizeSMS(sms);
            UserProfile userProfile = this.profileDelegate.GetUserProfile(hdid).Payload;

            userProfile.SMSNumber = null;
            this.profileDelegate.Update(userProfile);

            // Update the notification settings
            NotificationSettingsRequest queuedNotification = this.notificationSettingsService.QueueNotificationSettings(new NotificationSettingsRequest(userProfile, userProfile.Email, sms));

            bool isDeleted = string.IsNullOrEmpty(sms);
            MessagingVerification?lastSMSVerification = this.messageVerificationDelegate.GetLastForUser(hdid, MessagingVerificationType.SMS);

            if (lastSMSVerification != null)
            {
                this.logger.LogInformation($"Expiring old sms validation for user ${hdid}");
                this.messageVerificationDelegate.Expire(lastSMSVerification, isDeleted);
            }

            if (!isDeleted)
            {
                this.logger.LogInformation($"Sending new sms verification for user ${hdid}");
                this.AddVerificationSMS(hdid, sms, queuedNotification.SMSVerificationCode);
            }

            this.logger.LogDebug($"Finished updating user sms");
            return(true);
        }
        public void ShouldSend()
        {
            NotificationSettingsRequest nsRequest = new NotificationSettingsRequest()
            {
                EmailEnabled        = true,
                EmailAddress        = "*****@*****.**",
                SMSEnabled          = false,
                SMSNumber           = "2505555555",
                SubjectHdid         = "hdid",
                SMSVerificationCode = "123456",
                SMSVerified         = false,
            };
            string bearerToken = "bearer token";

            NotificationSettingsResponse nsResponse = new NotificationSettingsResponse(nsRequest);
            RequestResult <NotificationSettingsResponse> expectedResult = new RequestResult <NotificationSettingsResponse>()
            {
                ResourcePayload = nsResponse,
                ResultStatus    = Common.Constants.ResultType.Success,
            };
            var mockLogger     = new Mock <ILogger <NotificationSettingsService> >();
            var mockJobClient  = new Mock <IBackgroundJobClient>();
            var mockNSDelegate = new Mock <INotificationSettingsDelegate>();

            mockNSDelegate.Setup(s => s.SetNotificationSettings(nsRequest, bearerToken)).Returns(Task.FromResult(expectedResult));
            INotificationSettingsService service = new NotificationSettingsService(
                mockLogger.Object,
                mockJobClient.Object,
                mockNSDelegate.Object);
            RequestResult <NotificationSettingsResponse> actualResult = Task.Run(async() => await
                                                                                 service.SendNotificationSettings(nsRequest, bearerToken)).Result;

            Assert.True(actualResult.IsDeepEqual(expectedResult));
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        public bool UpdateUserSMS(string hdid, string sms, Uri hostUri, string bearerToken)
        {
            this.logger.LogTrace($"Removing user sms number ${hdid}");
            UserProfile userProfile = this.profileDelegate.GetUserProfile(hdid).Payload;

            userProfile.SMSNumber = null;
            this.profileDelegate.Update(userProfile);
            MessagingVerification?smsInvite = this.RetrieveLastInvite(hdid);

            // Update the notification settings
            NotificationSettingsRequest notificationRequest = this.UpdateNotificationSettings(userProfile, userProfile.Email, sms);

            if (smsInvite != null)
            {
                this.logger.LogInformation($"Expiring old sms validation for user ${hdid}");
                smsInvite.ExpireDate = DateTime.UtcNow;
                smsInvite.Deleted    = string.IsNullOrEmpty(sms);
                this.messageVerificationDelegate.Update(smsInvite);
            }

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

            this.logger.LogDebug($"Finished updating user sms");
            return(true);
        }
Exemplo n.º 6
0
        private void UpdateNotificationSettings(UserProfile userProfile)
        {
            // Update the notification settings
            NotificationSettingsRequest request = new NotificationSettingsRequest(userProfile, userProfile.Email, userProfile.SMSNumber);

            this.notificationSettingsService.QueueNotificationSettings(request);
        }
        private NotificationSettingsRequest UpdateNotificationSettings(UserProfile userProfile, string?smsNumber)
        {
            // Update the notification settings
            NotificationSettingsRequest request = new NotificationSettingsRequest(userProfile, userProfile.Email, smsNumber);

            this.notificationSettingsService.QueueNotificationSettings(request);
            return(request);
        }
        public void ValidateSetNotificationSettings201()
        {
            RequestResult <NotificationSettingsResponse> expected = new RequestResult <NotificationSettingsResponse>()
            {
                ResultStatus    = Common.Constants.ResultType.Success,
                ResourcePayload = new NotificationSettingsResponse()
                {
                    SMSEnabled = true,
                    SMSNumber  = "5551231234",
                    SMSScope   = new List <NotificationTarget>
                    {
                        NotificationTarget.Covid19,
                    },
                    EmailEnabled = true,
                    EmailAddress = "*****@*****.**",
                    EmailScope   = new List <NotificationTarget>
                    {
                        NotificationTarget.Covid19,
                    },
                },
                TotalResultCount = 1,
            };
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                IgnoreNullValues     = true,
                WriteIndented        = true,
            };
            NotificationSettingsRequest request = new NotificationSettingsRequest(expected.ResourcePayload);

            request.SMSVerificationCode = "1234";
            string json        = JsonSerializer.Serialize(request, options);
            var    handlerMock = new Mock <HttpMessageHandler>();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Created,
                Content    = new StringContent(json),
            })
            .Verifiable();
            using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            Mock <IHttpClientService> mockHttpClientService = new Mock <IHttpClientService>();

            mockHttpClientService.Setup(s => s.CreateDefaultHttpClient()).Returns(() => new HttpClient(handlerMock.Object));
            INotificationSettingsDelegate nsDelegate = new RestNotificationSettingsDelegate(loggerFactory.CreateLogger <RestNotificationSettingsDelegate>(), mockHttpClientService.Object, this.configuration);
            RequestResult <NotificationSettingsResponse> actualResult = Task.Run(async() => await nsDelegate.SetNotificationSettings(request, string.Empty)).Result;

            Assert.True(actualResult.IsDeepEqual(expected));
        }
        private static NotificationSettingsRequest ValidateVerificationCode(NotificationSettingsRequest notificationSettings)
        {
            if (notificationSettings.SMSEnabled && string.IsNullOrEmpty(notificationSettings.SMSVerificationCode))
            {
                // Create the SMS validation code if the SMS is not verified and the caller didn't set it.
                Random generator = new Random();
                notificationSettings.SMSVerificationCode = generator.Next(0, 999999).ToString("D6", CultureInfo.InvariantCulture);
            }

            return(notificationSettings);
        }
Exemplo n.º 10
0
        public object Get(NotificationSettingsRequest request)
        {
            if (request.AccountId.HasValue)
            {
                // if account notification settings have not been created yet, send back the default company values
                var accountSettings = _configDao.GetNotificationSettings(request.AccountId.Value);
                return(accountSettings ?? _configDao.GetNotificationSettings());
            }

            return(_configDao.GetNotificationSettings());
        }
Exemplo n.º 11
0
        public async Task UpdateNotificationSettings(NotificationSettings notificationSettings)
        {
            // Update cached user settings
            UserCache.Set(UserNotificationSettingsCacheKey, notificationSettings);

            var request = new NotificationSettingsRequest
            {
                AccountId            = CurrentAccount.Id,
                NotificationSettings = notificationSettings
            };

            await UseServiceClientAsync <IAccountServiceClient>(client => client.UpdateNotificationSettings(request));
        }
        public void ValidateSetNotificationSettings400()
        {
            string errMsg = "Mocked Error";
            RequestResult <NotificationSettingsResponse> expected = new RequestResult <NotificationSettingsResponse>()
            {
                ResultStatus = Common.Constants.ResultType.Error,
                ResultError  = new RequestResultError()
                {
                    ResultMessage = $"Bad Request, HTTP Error BadRequest\nDetails:\n{errMsg}", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.PHSA)
                },
            };
            NotificationSettingsRequest notificationSettings = new NotificationSettingsRequest()
            {
                SMSEnabled = true,
                SMSNumber  = "5551231234",
                SMSScope   = new List <NotificationTarget>
                {
                    NotificationTarget.Covid19,
                },
                EmailEnabled = true,
                EmailAddress = "*****@*****.**",
                EmailScope   = new List <NotificationTarget>
                {
                    NotificationTarget.Covid19,
                },
            };
            var handlerMock = new Mock <HttpMessageHandler>();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content    = new StringContent(errMsg),
            })
            .Verifiable();
            using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            Mock <IHttpClientService> mockHttpClientService = new Mock <IHttpClientService>();

            mockHttpClientService.Setup(s => s.CreateDefaultHttpClient()).Returns(() => new HttpClient(handlerMock.Object));
            INotificationSettingsDelegate nsDelegate = new RestNotificationSettingsDelegate(loggerFactory.CreateLogger <RestNotificationSettingsDelegate>(), mockHttpClientService.Object, this.configuration);
            RequestResult <NotificationSettingsResponse> actualResult = Task.Run(async() => await nsDelegate.SetNotificationSettings(notificationSettings, string.Empty)).Result;

            Assert.True(actualResult.IsDeepEqual(expected));
        }
        /// <inheritdoc />
        public void QueueNotificationSettings(NotificationSettingsRequest notificationSettings)
        {
            this.logger.LogTrace($"Queueing Notification Settings push to PHSA...");
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                IgnoreNullValues     = true,
                WriteIndented        = true,
            };
            string json = JsonSerializer.Serialize(ValidateVerificationCode(notificationSettings), options);

            this.jobClient.Enqueue <INotificationSettingsJob>(j => j.PushNotificationSettings(json));
            this.logger.LogDebug($"Finished queueing Notification Settings push.");
        }
Exemplo n.º 14
0
        public void ValidateSetNotificationSettings403()
        {
            RequestResult <NotificationSettingsRequest> expected = new RequestResult <NotificationSettingsRequest>()
            {
                ResultStatus  = Common.Constants.ResultType.Error,
                ResultMessage = "DID Claim is missing or can not resolve PHN, HTTP Error Forbidden",
            };
            NotificationSettingsRequest notificationSettings = new NotificationSettingsRequest()
            {
                SMSEnabled = true,
                SMSNumber  = "5551231234",
                SMSScope   = new List <NotificationTarget>
                {
                    NotificationTarget.Covid19,
                },
                EmailEnabled = true,
                EmailAddress = "*****@*****.**",
                EmailScope   = new List <NotificationTarget>
                {
                    NotificationTarget.Covid19,
                },
            };
            var handlerMock = new Mock <HttpMessageHandler>();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Forbidden,
                Content    = new StringContent(string.Empty),
            })
            .Verifiable();
            using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            Mock <IHttpClientService> mockHttpClientService = new Mock <IHttpClientService>();

            mockHttpClientService.Setup(s => s.CreateDefaultHttpClient()).Returns(() => new HttpClient(handlerMock.Object));
            INotificationSettingsDelegate nsDelegate = new RestNotificationSettingsDelegate(loggerFactory.CreateLogger <RestNotificationSettingsDelegate>(), mockHttpClientService.Object, this.configuration);
            RequestResult <NotificationSettingsResponse> actualResult = Task.Run(async() => await nsDelegate.SetNotificationSettings(notificationSettings, string.Empty)).Result;

            Assert.True(actualResult.IsDeepEqual(expected));
        }
Exemplo n.º 15
0
        public async Task SaveNotificationSettings(string email, NotificationSettingsRequest request)
        {
            using (var userRepository = new Repository <User>(_provider)) {
                var user = userRepository.Get(x => x.Email == email).Single();
                var notificationSettingsRep = new Repository <NotificationSettings>(userRepository);
                var notificationSettings    = notificationSettingsRep.Get(x => x.User == user).Single();
                notificationSettings.InviteSend       = request.InviteSend;
                notificationSettings.ProfileAdd       = request.ProfileAdd;
                notificationSettings.ProfileRemove    = request.ProfileRemove;
                notificationSettings.DocumentReceived = request.DocumentReceived;
                notificationSettings.DocumentRejected = request.DocumentRejected;
                notificationSettings.DocumentRetired  = request.DocumentRetired;
                notificationSettings.DocumentSend     = request.DocumentSend;
                notificationSettings.DocumentSign     = request.DocumentSign;
                await notificationSettingsRep.UpdateAsync(notificationSettings);

                await notificationSettingsRep.CommitAsync();
            }
        }
Exemplo n.º 16
0
        /// <inheritdoc />
        public NotificationSettingsRequest QueueNotificationSettings(NotificationSettingsRequest notificationSettings)
        {
            this.logger.LogTrace($"Queueing Notification Settings push to PHSA...");
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                IgnoreNullValues     = true,
                WriteIndented        = true,
            };
            string json = JsonSerializer.Serialize(ValidateSMSVerificationCode(notificationSettings), options);

            this.jobClient.Enqueue <INotificationSettingsJob>(j => j.PushNotificationSettings(json));

            // Retrieve and update each delegate notification setting
            DBResult <IEnumerable <ResourceDelegate> > dbResult = this.resourceDelegateDelegate.Get(notificationSettings.SubjectHdid, 0, 500);

            foreach (ResourceDelegate resourceDelegate in dbResult.Payload)
            {
                this.logger.LogDebug($"Queueing Dependent Notification Settings.");
                NotificationSettingsRequest dependentNotificationSettings = new ()
                {
                    SubjectHdid  = resourceDelegate.ProfileHdid,
                    EmailAddress = notificationSettings.EmailAddress,
                    EmailEnabled = notificationSettings.EmailEnabled,
                    EmailScope   = notificationSettings.EmailScope,
                };

                // Only send dependents sms number if it has been verified
                if (notificationSettings.SMSVerified)
                {
                    dependentNotificationSettings.SMSNumber   = notificationSettings.SMSNumber;
                    dependentNotificationSettings.SMSEnabled  = notificationSettings.SMSEnabled;
                    dependentNotificationSettings.SMSScope    = notificationSettings.SMSScope;
                    dependentNotificationSettings.SMSVerified = notificationSettings.SMSVerified;
                }

                string delegateJson = JsonSerializer.Serialize(dependentNotificationSettings, options);
                this.jobClient.Enqueue <INotificationSettingsJob>(j => j.PushNotificationSettings(delegateJson));
            }

            this.logger.LogDebug($"Finished queueing Notification Settings push.");
            return(notificationSettings);
        }
        public void ShouldQueue()
        {
            NotificationSettingsRequest nsr = new NotificationSettingsRequest()
            {
                EmailEnabled        = true,
                EmailAddress        = "*****@*****.**",
                SMSEnabled          = true,
                SMSNumber           = "2505555555",
                SubjectHdid         = "hdid",
                SMSVerificationCode = "123456",
                SMSVerified         = false,
            };

            var mockLogger     = new Mock <ILogger <NotificationSettingsService> >();
            var mockJobClient  = new Mock <IBackgroundJobClient>();
            var mockNSDelegate = new Mock <INotificationSettingsDelegate>();
            var mockResourceDelegateDelegate = new Mock <IResourceDelegateDelegate>();
            var dbResult = new Database.Wrapper.DBResult <IEnumerable <ResourceDelegate> >();

            dbResult.Payload = new List <ResourceDelegate>();
            mockResourceDelegateDelegate.Setup(s => s.Get(nsr.SubjectHdid, 0, 500)).Returns(dbResult);
            INotificationSettingsService service = new NotificationSettingsService(
                mockLogger.Object,
                mockJobClient.Object,
                mockNSDelegate.Object,
                mockResourceDelegateDelegate.Object);

            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                IgnoreNullValues     = true,
                WriteIndented        = true,
            };

            string expectedJobParm = JsonSerializer.Serialize(nsr, options);

            service.QueueNotificationSettings(nsr);

            mockJobClient.Verify(x => x.Create(
                                     It.Is <Job>(job => job.Method.Name == "PushNotificationSettings" && (string)job.Args[0] == expectedJobParm),
                                     It.IsAny <EnqueuedState>()));
        }
        public void ShouldCreateSMSCode()
        {
            NotificationSettingsRequest nsr = new NotificationSettingsRequest()
            {
                EmailEnabled = true,
                EmailAddress = "*****@*****.**",
                SMSEnabled   = true,
                SMSNumber    = "2505555555",
                SubjectHdid  = "hdid",
                SMSVerified  = true,
            };

            var mockLogger     = new Mock <ILogger <NotificationSettingsService> >();
            var mockJobClient  = new Mock <IBackgroundJobClient>();
            var mockNSDelegate = new Mock <INotificationSettingsDelegate>();
            var mockResourceDelegateDelegate = new Mock <IResourceDelegateDelegate>();
            var dbResult = new Database.Wrapper.DBResult <IEnumerable <ResourceDelegate> >();

            dbResult.Payload = new List <ResourceDelegate>()
            {
                new ResourceDelegate()
                {
                    ProfileHdid = hdid
                },
            };
            mockResourceDelegateDelegate.Setup(s => s.Get(nsr.SubjectHdid, 0, 500)).Returns(dbResult);

            INotificationSettingsService service = new NotificationSettingsService(
                mockLogger.Object,
                mockJobClient.Object,
                mockNSDelegate.Object,
                mockResourceDelegateDelegate.Object);

            Assert.True(nsr.SMSVerificationCode == null);
            service.QueueNotificationSettings(nsr);

            mockJobClient.Verify(x => x.Create(
                                     It.Is <Job>(job => job.Method.Name == "PushNotificationSettings" && job.Args[0] is string),
                                     It.IsAny <EnqueuedState>()));

            Assert.True(nsr.SMSVerificationCode != null);
        }
Exemplo n.º 19
0
        private NotificationSettingsRequest UpdateNotificationSettings(string dependentHdid, string delegateHdid, bool isDelete = false)
        {
            DBResult <UserProfile> dbResult            = this.userProfileDelegate.GetUserProfile(delegateHdid);
            UserProfile            delegateUserProfile = dbResult.Payload;

            // Update the notification settings
            NotificationSettingsRequest request = new NotificationSettingsRequest(delegateUserProfile, delegateUserProfile.Email, delegateUserProfile.SMSNumber);

            request.SubjectHdid = dependentHdid;
            if (isDelete)
            {
                request.EmailAddress = null;
                request.EmailEnabled = false;
                request.SMSNumber    = null;
                request.SMSEnabled   = false;
                request.SMSVerified  = false;
            }

            this.notificationSettingsService.QueueNotificationSettings(request);
            return(request);
        }
        /// <summary>
        /// Runs the task that needs to be done for the IOneTimeTask.
        /// </summary>
        public void Run()
        {
            this.logger.LogInformation($"Performing Task {this.GetType().Name}");
            IEnumerable <UserProfile> users = this.dbContext.UserProfile.Where(q => !string.IsNullOrEmpty(q.Email)).ToList();

            this.logger.LogInformation($"Queueing NotificationSettings for {users.Count()} users");
            foreach (UserProfile user in users)
            {
                NotificationSettingsRequest nsr = new NotificationSettingsRequest()
                {
                    SubjectHdid  = user.HdId,
                    EmailAddress = user.Email,
                    EmailEnabled = true,
                };

                // Queue each push to PHSA in the Job Scheduler
                this.notificationSettingsService.QueueNotificationSettings(nsr);
            }

            this.logger.LogInformation($"Task {this.GetType().Name} has completed");
        }
Exemplo n.º 21
0
        public void PushNotificationSettings(string notificationSettingsJSON)
        {
            this.logger.LogDebug($"Queueing Notification Settings push to PHSA...");
            if (this.jobEnabled)
            {
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    IgnoreNullValues     = true,
                    WriteIndented        = true,
                };

                NotificationSettingsRequest notificationSettings = JsonSerializer.Deserialize <NotificationSettingsRequest>(notificationSettingsJSON, options);
                string?accessToken = this.authDelegate.AuthenticateAsUser().AccessToken;

                if (string.IsNullOrEmpty(accessToken))
                {
                    this.logger.LogError($"Authenticated as User System access token is null or emtpy, Error:\n{accessToken}");
                    throw new FormatException($"Authenticated as User System access token is null or emtpy, Error:\n{accessToken}");
                }
                else
                {
                    RequestResult <NotificationSettingsResponse> retVal = Task.Run(async() => await
                                                                                   this.notificationSettingsDelegate.SetNotificationSettings(notificationSettings, accessToken).ConfigureAwait(true)).Result;
                    if (retVal.ResultStatus != HealthGateway.Common.Constants.ResultType.Success)
                    {
                        this.logger.LogError($"Unable to send Notification Settings to PHSA, Error:\n{retVal.ResultError?.ResultMessage}");
                        throw new FormatException($"Unable to send Notification Settings to PHSA, Error:\n{retVal.ResultError?.ResultMessage}");
                    }
                }
            }
            else
            {
                this.logger.LogInformation("Job has been disabled by configuration");
            }

            this.logger.LogDebug($"Finished queueing Notification Settings push.");
        }
Exemplo n.º 22
0
        /// <inheritdoc/>
        public async Task <RequestResult <NotificationSettingsResponse> > SetNotificationSettings(NotificationSettingsRequest notificationSettings, string bearerToken)
        {
            RequestResult <NotificationSettingsResponse> retVal = new RequestResult <NotificationSettingsResponse>()
            {
                ResultStatus = Common.Constants.ResultType.Error,
            };
            Stopwatch timer = new Stopwatch();

            timer.Start();
            this.logger.LogDebug($"Sending Notification Settings to PHSA...");
            this.logger.LogTrace($"Bearer token: {bearerToken}");
            using HttpClient client = this.httpClientService.CreateDefaultHttpClient();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", bearerToken);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json));
            client.DefaultRequestHeaders.Add(SubjectResourceHeader, notificationSettings.SubjectHdid);
            try
            {
                Uri endpoint = new Uri(this.nsConfig.Endpoint);
                var options  = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    IgnoreNullValues     = true,
                    WriteIndented        = true,
                };
                string json = JsonSerializer.Serialize(notificationSettings, options);
                using HttpContent content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
                this.logger.LogTrace($"Http content: {json}");
                HttpResponseMessage response = await client.PutAsync(endpoint, content).ConfigureAwait(true);

                string payload = await response.Content.ReadAsStringAsync().ConfigureAwait(true);

                switch (response.StatusCode)
                {
                case HttpStatusCode.Created:
                case HttpStatusCode.OK:
                    NotificationSettingsResponse?nsResponse = JsonSerializer.Deserialize <NotificationSettingsResponse>(payload, options);
                    retVal.ResultStatus     = Common.Constants.ResultType.Success;
                    retVal.TotalResultCount = 1;
                    retVal.ResourcePayload  = nsResponse;
                    break;

                case HttpStatusCode.UnprocessableEntity:
                    retVal.ResultStatus = Constants.ResultType.ActionRequired;
                    this.logger.LogInformation($"PHSA has indicated that the SMS number is invalid: {notificationSettings.SMSNumber}");
                    retVal.ResultError = new RequestResultError()
                    {
                        ResultMessage = $"PHSA has indicated that the SMS number is invalid: {notificationSettings.SMSNumber}", ErrorCode = ErrorTranslator.ServiceError(ErrorType.SMSInvalid, ServiceType.PHSA)
                    };
                    break;

                case HttpStatusCode.BadRequest:
                    this.logger.LogError($"Error Details: {payload}");
                    retVal.ResultError = new RequestResultError()
                    {
                        ResultMessage = $"Bad Request, HTTP Error {response.StatusCode}\nDetails:\n{payload}", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.PHSA)
                    };
                    break;

                case HttpStatusCode.Forbidden:
                    this.logger.LogError($"Error Details: {payload}");
                    retVal.ResultError = new RequestResultError()
                    {
                        ResultMessage = $"DID Claim is missing or can not resolve PHN, HTTP Error {response.StatusCode}", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.PHSA)
                    };
                    break;

                default:
                    retVal.ResultError = new RequestResultError()
                    {
                        ResultMessage = $"Unable to connect to Notification Settings Endpoint, HTTP Error {response.StatusCode}", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.PHSA)
                    };
                    this.logger.LogError($"Unable to connect to endpoint {endpoint}, HTTP Error {response.StatusCode}\n{payload}");
                    break;
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                retVal.ResultError = new RequestResultError()
                {
                    ResultMessage = $"Exception getting Notification Settings: {e}", ErrorCode = ErrorTranslator.ServiceError(ErrorType.CommunicationExternal, ServiceType.PHSA)
                };
                this.logger.LogError($"Unexpected exception in GetNotificationSettings {e}");
            }

            timer.Stop();
            this.logger.LogDebug($"Finished getting Notification Settings, Time Elapsed: {timer.Elapsed}");
            return(retVal);
        }
        /// <inheritdoc />
        public async Task <RequestResult <NotificationSettingsResponse> > SendNotificationSettings(NotificationSettingsRequest notificationSettings, string bearerToken)
        {
            this.logger.LogTrace($"Queueing Notification Settings push to PHSA...");
            RequestResult <NotificationSettingsResponse> retVal = await this.notificationSettingsDelegate.
                                                                  SetNotificationSettings(ValidateVerificationCode(notificationSettings), bearerToken).ConfigureAwait(true);

            this.logger.LogDebug($"Finished queueing Notification Settings push.");
            return(retVal);
        }
Exemplo n.º 24
0
 public async Task UpdateNotificationSettings(NotificationSettingsRequest notificationSettingsRequest)
 {
     string req = string.Format("/settings/notifications/{0}", notificationSettingsRequest.AccountId);
     await Client.PostAsync <string>(req, notificationSettingsRequest, logger : Logger);
 }
Exemplo n.º 25
0
        /// <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);
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Post([FromBody] NotificationSettingsRequest request)
        {
            await settingsManager.SaveNotificationSettings(User.Identity.Name, request);

            return(Json(ApiResponse.Success(true)));
        }
Exemplo n.º 27
0
 public SetNotificationSettings(CallContext callContext, NotificationSettingsRequest settings) : base(callContext)
 {
     this.settings = settings;
 }