Example #1
0
        public async Task <IActionResult> GetEvacueeReport(string?taskNumber, string?fileId, string?evacuatedFrom, string?evacuatedTo)
        {
            var userRole            = Enum.Parse <MemberRole>(currentUserRole);
            var includePersonalInfo = userRole == MemberRole.Tier3 || userRole == MemberRole.Tier4;
            var result = await messagingClient.Send(new EvacueeReportQuery { TaskNumber = taskNumber, FileId = fileId, EvacuatedFrom = evacuatedFrom, EvacuatedTo = evacuatedTo, IncludePersonalInfo = includePersonalInfo });

            return(new FileContentResult(result.Content, result.ContentType));
        }
Example #2
0
        public async Task <ActionResult <VerifySecurityQuestionsResponse> > VerifySecurityQuestions(string registrantId, VerifySecurityQuestionsRequest request)
        {
            VerifySecurityQuestionsQuery verifySecurityQuestionsQuery = new VerifySecurityQuestionsQuery {
                RegistrantId = registrantId, Answers = mapper.Map <IEnumerable <ESS.Shared.Contracts.Submissions.SecurityQuestion> >(request.Answers)
            };
            var response = await messagingClient.Send(verifySecurityQuestionsQuery);

            return(Ok(mapper.Map <VerifySecurityQuestionsResponse>(response)));
        }
Example #3
0
        public async Task <IEnumerable <EvacuationFile> > GetFiles(string byRegistrantUserId, EvacuationFileStatus[] byStatus)
        {
            var files = (await messagingClient.Send(new EvacuationFilesQuery
            {
                PrimaryRegistrantUserId = byRegistrantUserId,
                IncludeFilesInStatuses = byStatus
            })).Items;

            return(files);
        }
        public async Task <ActionResult <Profile> > DeleteProfile()
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (!env.IsProduction())
            {
                await messagingClient.Send(new DeleteRegistrantCommand { UserId = userId });
            }
            return(Ok(userId));
        }
        public async Task <ActionResult <IEnumerable <CommunityCode> > > GetCommunities([FromQuery] string stateProvinceId, [FromQuery] string countryId, [FromQuery] CommunityType[] types)
        {
            var items = (await client.Send(new CommunitiesQuery()
            {
                CountryCode = countryId,
                StateProvinceCode = stateProvinceId,
                Types = types.Select(t => (EMBC.ESS.Shared.Contracts.Metadata.CommunityType)t)
            })).Items;

            return(Ok(mapper.Map <IEnumerable <CommunityCode> >(items)));
        }
Example #6
0
        public async Task <ActionResult <string> > Upsert(Profile profile)
        {
            profile.Id = currentUserId;
            var mappedProfile = mapper.Map <RegistrantProfile>(profile);

            //BCSC profiles are authenticated and verified
            mappedProfile.AuthenticatedUser = true;
            mappedProfile.VerifiedUser      = true;
            var profileId = await messagingClient.Send(new SaveRegistrantCommand { Profile = mappedProfile });

            return(Ok(profileId));
        }
Example #7
0
        public async Task <ActionResult <ESSTask> > GetTask(string taskId)
        {
            var reply = await messagingClient.Send(new TasksSearchQuery { TaskId = taskId });

            var task = reply.Items.SingleOrDefault();

            if (task == null)
            {
                return(NotFound(taskId));
            }
            return(Ok(mapper.Map <ESSTask>(task)));
        }
        public async Task <ActionResult <RegistrantProfile> > GetRegistrantProfile(string registrantId)
        {
            var registrant = (await messagingClient.Send(new RegistrantsSearchQuery
            {
                Id = registrantId
            })).Items.FirstOrDefault();

            if (registrant == null || registrant.RegistrantProfile == null)
            {
                return(NotFound());
            }

            return(Ok(mapper.Map <RegistrantProfile>(registrant.RegistrantProfile)));
        }
        public async Task <SearchResults> Search(string firstName, string lastName, string dateOfBirth, Controllers.MemberRole userRole)
        {
            var registrants = (await messagingClient.Send(new RegistrantsSearchQuery
            {
                FirstName = firstName,
                LastName = lastName,
                DateOfBirth = dateOfBirth,
                IncludeCases = true
            })).Items;

            var files = (await messagingClient.Send(new EvacuationFilesSearchQuery
            {
                FirstName = firstName,
                LastName = lastName,
                DateOfBirth = dateOfBirth,
                IncludeHouseholdMembers = true
            })).Items;

            //check for restricted files
            var anyRestriction = registrants.SelectMany(r => r.Files).Any(f => f.RestrictedAccess) ||
                                 files.Any(f => f.RestrictedAccess);

            if (userRole == Controllers.MemberRole.Tier1 && anyRestriction)
            {
                return(new SearchResults
                {
                    Files = Array.Empty <EvacuationFile>(),
                    Registrants = Array.Empty <RegistrantWithFiles>()
                });
            }

            //filter files by role
            var statusFilter = userRole == Controllers.MemberRole.Tier1
                ? tier1FileStatuses
                : tier2andAboveFileStatuses;

            files       = files.Where(f => statusFilter.Contains(f.Status));
            registrants = registrants.Select(r => new RegistrantWithFiles
            {
                RegistrantProfile = r.RegistrantProfile,
                Files             = r.Files.Where(f => statusFilter.Contains(f.Status))
            });

            return(new SearchResults
            {
                Registrants = mapper.Map <IEnumerable <RegistrantWithFiles> >(registrants),
                Files = mapper.Map <IEnumerable <EvacuationFile> >(files)
            });
        }
Example #10
0
        public RegistrationsTests()
        {
            mapper = new MapperConfiguration(cfg =>
            {
                cfg.AddMaps(typeof(EMBC.Responders.API.Configuration));
            }).CreateMapper();

            messagingClient = A.Fake <IMessagingClient>();

            //Handle RegistrantsQuery
            A.CallTo(() => messagingClient.Send(A <RegistrantsQuery> .That.IsNotNull()))
            .ReturnsLazily(o =>
            {
                var query = o.GetArgument <RegistrantsQuery>(0);
                IEnumerable <KeyValuePair <string, RegistrantProfile> > ret = stagedRegistrantsDictionary.Where(a => true);

                if (!string.IsNullOrEmpty(query.Id))
                {
                    ret = ret.Where(r => r.Value.Id == query.Id);
                }
                if (!string.IsNullOrEmpty(query.UserId))
                {
                    ret = ret.Where(r => r.Value.UserId == query.UserId);
                }

                return(Task.FromResult(new RegistrantsQueryResponse
                {
                    Items = ret.Select(r => r.Value)
                }));
            });
        }
        public async Task <ActionResult <IEnumerable <SupplierListItem> > > GetSuppliers(string?legalName, string?gstNumber)
        {
            var query = new SuppliersQuery();

            if (!string.IsNullOrEmpty(legalName) && !string.IsNullOrEmpty(gstNumber))
            {
                query.LegalName = legalName;
                query.GSTNumber = gstNumber;
            }
            else
            {
                query.TeamId = teamId;
            }
            var suppliers = (await messagingClient.Send(query)).Items;

            return(Ok(mapper.Map <IEnumerable <SupplierListItem> >(suppliers, opt => opt.Items["UserTeamId"] = teamId)));
        }
Example #12
0
        public async Task <SearchResults> SearchEvacuations(string firstName, string lastName, string dateOfBirth, MemberRole userRole)
        {
            var searchResults = await messagingClient.Send(new ESS.Shared.Contracts.Submissions.EvacueeSearchQuery
            {
                FirstName               = firstName,
                LastName                = lastName,
                DateOfBirth             = dateOfBirth,
                IncludeRestrictedAccess = userRole != MemberRole.Tier1,
                InStatuses              = (userRole == MemberRole.Tier1 ? tier1FileStatuses : tier2andAboveFileStatuses)
                                          .Select(s => Enum.Parse <ESS.Shared.Contracts.Submissions.EvacuationFileStatus>(s.ToString(), true)).ToArray()
            });

            return(new SearchResults
            {
                Registrants = mapper.Map <IEnumerable <RegistrantProfileSearchResult> >(searchResults.Profiles),
                Files = mapper.Map <IEnumerable <EvacuationFileSearchResult> >(searchResults.EvacuationFiles)
            });
        }
Example #13
0
        public async Task GetRegistrantProfileById()
        {
            var registrantId = "123-abc";
            var registrant   = (await messagingClient.Send(new RegistrantsQuery
            {
                Id = registrantId
            })).Items.FirstOrDefault();

            registrant.Id.ShouldBe(registrantId);
        }
Example #14
0
        public async Task <ActionResult <IEnumerable <AssignedCommunity> > > GetAssignedCommunities([FromQuery] bool forAllTeams = false)
        {
            var query = new TeamsQuery();

            if (!forAllTeams)
            {
                query.TeamId = teamId;
            }

            var teams = (await messagingClient.Send(query)).Teams;

            var communities = teams.SelectMany(t => t.AssignedCommunities.Select(c => new { CommunityCode = c.Code, DateAssigned = c.DateAssigned, Team = t }));

            return(Ok(communities.Select(c => new AssignedCommunity
            {
                TeamId = c.Team.Id,
                TeamName = c.Team.Name,
                CommunityCode = c.CommunityCode,
                DateAssigned = c.DateAssigned
            })));
        }
Example #15
0
        public async Task <TeamMember> GetTeamMember(ClaimsPrincipal sourcePrincipal = null)
        {
            if (sourcePrincipal == null)
            {
                sourcePrincipal = currentPrincipal;
            }
            var member = (await messagingClient.Send(new TeamMembersQuery {
                UserName = getCurrentUserName(sourcePrincipal), IncludeActiveUsersOnly = true
            })).TeamMembers.SingleOrDefault();

            return(member);
        }
        public async Task <ActionResult <Configuration> > GetConfiguration()
        {
            var outageInfo = await cache.GetOrSet(
                "outageinfo",
                async() => (await client.Send(new OutageQuery {
                PortalType = PortalType.Registrants
            })).OutageInfo,
                TimeSpan.FromMinutes(5));

            var oidcConfig = configuration.GetSection("auth:oidc");
            var config     = new Configuration
            {
                Oidc = new OidcOptions
                {
                    ClientId = oidcConfig["clientId"],
                    Issuer   = oidcConfig["issuer"],
                    Scope    = oidcConfig.GetValue("scope", "openid offline_access registrants-portal-api"),
                    Idp      = oidcConfig.GetValue("idp", "bcsc")
                },
                OutageInfo  = mapper.Map <OutageInformation>(outageInfo),
                TimeoutInfo = new TimeoutConfiguration
                {
                    SessionTimeoutInMinutes = configuration.GetValue <int>("timeout:minutes", 20),
                    WarningMessageDuration  = configuration.GetValue <int>("timeout:warningDuration", 1)
                }
            };

            return(Ok(await Task.FromResult(config)));
        }
        public async Task <ActionResult <Configuration> > GetConfiguration()
        {
            var outageInfo = await cache.GetOrSet(
                "outageinfo",
                async() => (await client.Send(new OutageQuery {
                PortalType = PortalType.Registrants
            })).OutageInfo,
                TimeSpan.FromSeconds(30));

            var oidcConfig = configuration.GetSection("auth:oidc");
            var config     = new Configuration
            {
                Oidc = new OidcOptions
                {
                    ClientId = oidcConfig["clientId"],
                    Issuer   = oidcConfig["issuer"],
                    Scope    = oidcConfig.GetValue("scope", "openid offline_access registrants-portal-api"),
                    Idp      = oidcConfig.GetValue("idp", "bcsc")
                },
                OutageInfo  = mapper.Map <OutageInformation>(outageInfo),
                TimeoutInfo = new TimeoutConfiguration
                {
                    SessionTimeoutInMinutes = configuration.GetValue <int>("timeout:minutes", 20),
                    WarningMessageDuration  = configuration.GetValue <int>("timeout:warningDuration", 1)
                },
                Captcha = new CaptchaConfiguration
                {
                    Url             = configuration.GetValue <string>("captcha:url"),
                    AutomationValue = environment.IsProduction() ? null : configuration.GetValue <string>("captcha:automation")?.Substring(0, 6).ToSha256() //captcha is limited to 6 characters
                }
            };

            return(Ok(await Task.FromResult(config)));
        }
Example #18
0
        public async Task <ActionResult <Configuration> > GetConfiguration()
        {
            var outageInfo = await cache.GetOrSet(
                "outageInfo",
                async() => (await client.Send(new OutageQuery {
                PortalType = PortalType.Responders
            })).OutageInfo,
                TimeSpan.FromSeconds(30));

            var config = new Configuration
            {
                Oidc = new OidcConfiguration
                {
                    ClientId = configuration.GetValue <string>("oidc:clientId"),
                    Issuer   = configuration.GetValue <string>("oidc:issuer"),
                    PostLogoutRedirectUrl = $"{configuration.GetValue<string>("oidc:bceidLogoutUrl")}?retnow=1&returl={this.HttpContext.Request.Host}"
                },
                OutageInfo  = mapper.Map <OutageInformation>(outageInfo),
                TimeoutInfo = new TimeoutConfiguration
                {
                    SessionTimeoutInMinutes = configuration.GetValue <int>("timeout:minutes", 20),
                    WarningMessageDuration  = configuration.GetValue <int>("timeout:warningDuration", 1)
                }
            };

            return(Ok(await Task.FromResult(config)));
        }
        public async Task <ActionResult <RegistrationResult> > Create(AnonymousRegistration registration)
        {
            if (registration == null)
            {
                return(BadRequest());
            }

            var profile = mapper.Map <RegistrantProfile>(registration.RegistrationDetails);

            profile.AuthenticatedUser = false;
            profile.VerifiedUser      = false;
            var file = mapper.Map <ESS.Shared.Contracts.Submissions.EvacuationFile>(registration);
            var id   = await messagingClient.Send(new SubmitAnonymousEvacuationFileCommand
            {
                File             = file,
                SubmitterProfile = profile
            });

            return(Ok(new RegistrationResult {
                ReferenceNumber = id
            }));
        }
        public async Task <ActionResult <UserProfile> > GetCurrentUserProfile()
        {
            var userName     = User.FindFirstValue(ClaimTypes.Upn).Split('@')[0];
            var userId       = User.FindFirstValue(ClaimTypes.Sid);
            var sourceSystem = User.FindFirstValue("identity_source");

            // Get the current user
            var currentMember = await userService.GetTeamMember();

            if (currentMember == null)
            {
                logger.LogError("Login failure userName {0}, user ID {1}, sourceSystem: {2}: {3}", userName, userId, sourceSystem, $"User {userName} not found");
                return(Unauthorized());
            }
            if (currentMember.ExternalUserId != null && currentMember.ExternalUserId != userId)
            {
                throw new Exception($"User {userName} has external id {currentMember.ExternalUserId} but trying to log in with user id {userId}");
            }
            if (currentMember.ExternalUserId == null && currentMember.LastSuccessfulLogin.HasValue)
            {
                throw new Exception($"User {userName} has no external id but somehow logged in already");
            }

            if (!currentMember.LastSuccessfulLogin.HasValue || string.IsNullOrEmpty(currentMember.ExternalUserId))
            {
                currentMember.ExternalUserId = userId;
            }

            currentMember.LastSuccessfulLogin = DateTime.UtcNow;

            // Update current user
            await messagingClient.Send(new SaveTeamMemberCommand
            {
                Member = mapper.Map <ESS.Shared.Contracts.Team.TeamMember>(currentMember)
            });

            return(Ok(mapper.Map <UserProfile>(currentMember)));
        }
Example #21
0
        public async Task <bool> ProcessInvite(string inviteId, string loggedInUserId)
        {
            try
            {
                await messagingClient.Send(new ProcessRegistrantInviteCommand { InviteId = inviteId, LoggedInUserId = loggedInUserId });

                return(true);
            }
            catch (BusinessLogicException e)
            {
                logger.LogError(e, "Invite {0} for user {1}: {2} error", inviteId, loggedInUserId, e.Message);
                return(false);
            }
        }
        public async Task <SearchResults> Search(string firstName, string lastName, string dateOfBirth, MemberRole userRole)
        {
            var registrants = (await messagingClient.Send(new RegistrantsSearchQuery
            {
                FirstName = firstName,
                LastName = lastName,
                DateOfBirth = dateOfBirth
            })).Items;

            var files = (await messagingClient.Send(new EvacuationFilesSearchQuery
            {
                FirstName = firstName,
                LastName = lastName,
                DateOfBirth = dateOfBirth
            })).Items;

            //TODO: check if any result has restrictions

            return(new SearchResults
            {
                Registrants = mapper.Map <IEnumerable <RegistrantProfileSearchResult> >(registrants),
                Files = mapper.Map <IEnumerable <EvacuationFileSearchResult> >(files)
            });
        }
Example #23
0
        public RegistrationsTests()
        {
            mapper = new MapperConfiguration(cfg =>
            {
                cfg.AddMaps(typeof(Startup));
            }).CreateMapper();

            messagingClient = A.Fake <IMessagingClient>();

            //Handle RegistrantsSearchQuery
            A.CallTo(() => messagingClient.Send(A <RegistrantsSearchQuery> .That.IsNotNull()))
            .ReturnsLazily(o =>
            {
                var query = o.GetArgument <RegistrantsSearchQuery>(0);
                IEnumerable <KeyValuePair <string, RegistrantWithFiles> > ret = stagedRegistrantsWithFiles.Where(a => true);

                if (!string.IsNullOrEmpty(query.Id))
                {
                    ret = ret.Where(r => r.Value.RegistrantProfile.Id == query.Id);
                }
                if (!string.IsNullOrEmpty(query.UserId))
                {
                    ret = ret.Where(r => r.Value.RegistrantProfile.UserId == query.UserId);
                }
                if (!string.IsNullOrEmpty(query.FirstName))
                {
                    ret = ret.Where(r => r.Value.RegistrantProfile.FirstName.Equals(query.FirstName, StringComparison.OrdinalIgnoreCase));
                }
                if (!string.IsNullOrEmpty(query.LastName))
                {
                    ret = ret.Where(r => r.Value.RegistrantProfile.LastName.Equals(query.LastName, StringComparison.OrdinalIgnoreCase));
                }
                if (!string.IsNullOrEmpty(query.DateOfBirth))
                {
                    ret = ret.Where(r => r.Value.RegistrantProfile.DateOfBirth.Equals(query.DateOfBirth, StringComparison.OrdinalIgnoreCase));
                }

                return(Task.FromResult(new RegistrantsSearchQueryResult
                {
                    Items = ret.Select(r => r.Value)
                }));
            });
        }
Example #24
0
        public async Task <TeamMember> GetTeamMember(ClaimsPrincipal sourcePrincipal = null)
        {
            if (sourcePrincipal == null)
            {
                sourcePrincipal = currentPrincipal;
            }
            var member = (await messagingClient.Send(new TeamMembersQuery {
                UserName = getCurrentUserName(sourcePrincipal), IncludeActiveUsersOnly = true
            })).TeamMembers.SingleOrDefault();

            if (!IsPrincipalValid(sourcePrincipal, member))
            {
                //replace the cached principal when not valid
                var cacheKey = generateCacheKeyName(getCurrentUserName(sourcePrincipal));
                await cache.RemoveAsync(cacheKey);

                await cache.SetAsync(cacheKey, member);
            }
            return(member);
        }
        public async Task <SearchResults> SearchEvacuations(string firstName, string lastName, string dateOfBirth, string externalReferenceId, MemberRole userRole)
        {
            var allowedStatues = (!string.IsNullOrEmpty(externalReferenceId) || userRole != MemberRole.Tier1 ? tier2andAboveFileStatuses : tier1FileStatuses)
                                 .Select(s => Enum.Parse <EMBC.ESS.Shared.Contracts.Events.EvacuationFileStatus>(s.ToString(), true)).ToArray();
            var searchResults = await messagingClient.Send(new EMBC.ESS.Shared.Contracts.Events.EvacueeSearchQuery
            {
                FirstName               = firstName,
                LastName                = lastName,
                DateOfBirth             = dateOfBirth,
                IncludeRestrictedAccess = userRole != MemberRole.Tier1,
                InStatuses              = allowedStatues
            });

            return(new SearchResults
            {
                Registrants = mapper.Map <IEnumerable <RegistrantProfileSearchResult> >(searchResults.Profiles),
                Files = mapper.Map <IEnumerable <EvacuationFileSearchResult> >(searchResults.EvacuationFiles)
            });
        }
Example #26
0
        public async Task <ActionResult <IEnumerable <TeamMember> > > GetTeamMembers()
        {
            var response = await client.Send(new TeamMembersQuery { TeamId = teamId, IncludeActiveUsersOnly = false });

            return(Ok(mapper.Map <IEnumerable <TeamMember> >(response.TeamMembers)));
        }
Example #27
0
        private async Task <TeamMember> GetTeamMember(string userName)
        {
            var reply = await messagingClient.Send(new TeamMembersQuery { UserName = userName, IncludeActiveUsersOnly = true });

            return(reply.TeamMembers.SingleOrDefault());
        }
Example #28
0
        public async Task <ActionResult <IEnumerable <Team> > > GetTeams()
        {
            var response = await client.Send(new TeamsQuery { });

            return(Ok(mapper.Map <IEnumerable <Team> >(response.Teams)));
        }