コード例 #1
0
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context,
                                                   ResourceExecutionDelegate next)
        {
            var httpContext = context.HttpContext;

            try
            {
                var userId   = _userContextProvider.GetId(httpContext.User, ClaimType.UserId);
                var activeId = httpContext.Session.GetInt32(SessionKey.ActiveUserId);
                if (userId != activeId)
                {
                    httpContext.Session.SetInt32(SessionKey.ActiveUserId, userId);
                    var user = await _userService.GetDetails(userId);

                    var questionnaireId = await _questionnaireService
                                          .GetRequiredQuestionnaire(user.Id, user.Age);

                    if (questionnaireId.HasValue)
                    {
                        httpContext.Session.SetInt32(SessionKey.PendingQuestionnaire,
                                                     questionnaireId.Value);
                    }
                    else
                    {
                        httpContext.Session.Remove(SessionKey.PendingQuestionnaire);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogTrace($"Attempted Mission Control access while not logged in: {ex.Message}");
            }

            if (httpContext.User.HasClaim(ClaimType.Permission, nameof(Permission.ReadAllMail)))
            {
                try
                {
                    httpContext.Items[ItemKey.UnreadCount]
                        = await _mailService.GetAdminUnreadCountAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError("Error getting admin mail unread count: {Message}", ex.Message);
                }
            }

            if (httpContext.User.HasClaim(ClaimType.Permission,
                                          nameof(Permission.ViewPerformerDetails)))
            {
                var settings = await _performerSchedulingService.GetSettingsAsync();

                var schedulingStage = _performerSchedulingService
                                      .GetSchedulingStage(settings);
                if (schedulingStage != PsSchedulingStage.Unavailable)
                {
                    httpContext.Items.Add(ItemKey.ShowPerformerScheduling, true);
                }
            }
            await next();
        }
コード例 #2
0
        public async Task <IActionResult> Index()
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();

            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);

            if (schedulingStage == PsSchedulingStage.Unavailable)
            {
                ShowAlertDanger("Performer scheduling is not set up.");
                return(RedirectToAction(nameof(HomeController.Index), "Home"));
            }

            var systemId = GetId(ClaimType.SystemId);

            var viewModel = new ScheduleOverviewViewModel
            {
                Settings        = settings,
                SchedulingStage = schedulingStage,
                AgeGroups       = await _performerSchedulingService.GetAgeGroupsAsync(),
                CanSchedule     = UserHasPermission(Permission.SchedulePerformers)
            };

            if (schedulingStage >= PsSchedulingStage.SchedulingOpen)
            {
                var system = await _performerSchedulingService
                             .GetSystemWithoutExcludedBranchesAsync(systemId);

                viewModel.SystemName = system.Name;

                var branches = system.Branches;
                foreach (var branch in branches)
                {
                    branch.Selections = await _performerSchedulingService
                                        .GetSelectionsByBranchIdAsync(branch.Id);
                }

                viewModel.Branches = branches;
            }

            if (schedulingStage >= PsSchedulingStage.SchedulePosted)
            {
                var branches = await _performerSchedulingService
                               .GetNonExcludedSystemBranchesAsync(systemId, true);

                viewModel.BranchList = new SelectList(branches, "Id", "Name");
            }

            return(View(viewModel));
        }
コード例 #3
0
        public async Task <IActionResult> Index()
        {
            if (!AuthUser.Identity.IsAuthenticated)
            {
                return(RedirectToSignIn());
            }

            if (!UserHasPermission(Permission.AccessPerformerRegistration))
            {
                // not authorized for Performer registration, redirect to authorization code

                return(RedirectToAction(nameof(AuthorizationCode)));
            }

            var settings = await _performerSchedulingService.GetSettingsAsync();

            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);

            if (schedulingStage == PsSchedulingStage.Unavailable)
            {
                return(RedirectToAction(nameof(Controllers.HomeController.Index), "Home",
                                        new { Area = string.Empty }));
            }

            var hasPermission = UserHasPermission(Permission.AccessPerformerRegistration);

            var userId    = GetId(ClaimType.UserId);
            var performer = await _performerSchedulingService.GetPerformerByUserIdAsync(userId,
                                                                                        includeBranches : true);

            if (hasPermission &&
                (performer != null || schedulingStage == PsSchedulingStage.RegistrationOpen))
            {
                return(RedirectToAction(nameof(Dashboard)));
            }

            var viewModel = new IndexViewModel
            {
                HasPermission   = hasPermission,
                Settings        = settings,
                SchedulingStage = schedulingStage
            };

            return(View(viewModel));
        }
コード例 #4
0
        public async Task <IActionResult> Index()
        {
            PageTitle = HttpContext.Items[ItemKey.SiteName].ToString();
            var site = await GetCurrentSiteAsync();

            if (AuthUser.Identity.IsAuthenticated)
            {
                if (TempData.ContainsKey(TempDataKey.UserJoined))
                {
                    if (UserHasPermission(Permission.AccessMissionControl))
                    {
                        if (GetSiteStage() == SiteStage.BeforeRegistration ||
                            GetSiteStage() == SiteStage.AccessClosed)
                        {
                            return(RedirectToAction(nameof(MissionControl.HomeController.Index),
                                                    HomeController.Name,
                                                    new { Area = nameof(MissionControl) }));
                        }
                    }
                    else if (UserHasPermission(Permission.AccessPerformerRegistration))
                    {
                        var dates = await _performerSchedulingService.GetSettingsAsync();

                        var schedulingStage
                            = _performerSchedulingService.GetSchedulingStage(dates);

                        if (schedulingStage != PsSchedulingStage.Unavailable)
                        {
                            TempData.Remove(TempDataKey.UserJoined);
                            return(RedirectToAction(
                                       nameof(PerformerRegistration.HomeController.Index),
                                       Name,
                                       new { Area = nameof(PerformerRegistration) }));
                        }
                    }
                }

                User user;
                // signed-in users can view the dashboard
                try
                {
                    user = await _userService.GetDetails(GetActiveUserId());
                }
                catch (GraException gex)
                {
                    // this likely means the currently authenticated user isn't valid anymore
                    _logger.LogError(gex,
                                     "Problem displaying index for user {GetActiveUserId}: {Message}",
                                     GetActiveUserId(),
                                     gex.Message);
                    return(RedirectToAction(nameof(SignOut)));
                }

                await _vendorCodeService.PopulateVendorCodeStatusAsync(user);

                var userLogs = await _userService.GetPaginatedUserHistoryAsync(user.Id,
                                                                               new UserLogFilter(take : BadgesToDisplay)
                {
                    HasBadge = true
                });

                foreach (var userLog in userLogs.Data)
                {
                    userLog.BadgeFilename
                        = _pathResolver.ResolveContentPath(userLog.BadgeFilename);
                }

                var pointTranslation = await _activityService.GetUserPointTranslationAsync();

                var viewModel = new DashboardViewModel
                {
                    User        = user,
                    SingleEvent = pointTranslation.IsSingleEvent,
                    ActivityDescriptionPlural = pointTranslation.ActivityDescriptionPlural,
                    UserLogs = userLogs.Data,
                    DisableSecretCode
                                    = await GetSiteSettingBoolAsync(SiteSettingKey.SecretCode.Disable),
                    UpcomingStreams = await _eventService
                                      .GetUpcomingStreamListAsync()
                };

                try
                {
                    viewModel.SiteStage = (SiteStage)HttpContext.Items[ItemKey.SiteStage];
                }
                catch (Exception)
                {
                    viewModel.SiteStage = SiteStage.Unknown;
                }

                var program = await _siteService.GetProgramByIdAsync(user.ProgramId);

                if (program.DailyLiteracyTipId.HasValue)
                {
                    var day = _siteLookupService.GetSiteDay(site);
                    if (day.HasValue)
                    {
                        var image = await _dailyLiteracyTipService.GetImageByDayAsync(
                            program.DailyLiteracyTipId.Value, day.Value);

                        if (image != null)
                        {
                            var imagePath = Path.Combine($"site{site.Id}",
                                                         "dailyimages",
                                                         $"dailyliteracytip{program.DailyLiteracyTipId}",
                                                         $"{image.Name}{image.Extension}");

                            if (System.IO.File.Exists(_pathResolver
                                                      .ResolveContentFilePath(imagePath)))
                            {
                                var dailyLiteracyTip = await _dailyLiteracyTipService
                                                       .GetByIdAsync(program.DailyLiteracyTipId.Value);

                                viewModel.DailyImageLarge   = dailyLiteracyTip.IsLarge;
                                viewModel.DailyImageMessage = dailyLiteracyTip.Message;
                                viewModel.DailyImagePath
                                    = _pathResolver.ResolveContentPath(imagePath);
                            }
                        }
                    }
                }

                if (TempData.ContainsKey(TempDataKey.UserJoined))
                {
                    TempData.Remove(TempDataKey.UserJoined);
                    viewModel.FirstTimeParticipant = user.IsFirstTime;
                    viewModel.ProgramName          = program.Name;
                    viewModel.UserJoined           = true;
                }

                var userAvatar = await _avatarService.GetUserAvatarAsync();

                if (userAvatar?.Count > 0)
                {
                    var avatarElements = userAvatar;
                    foreach (var element in avatarElements)
                    {
                        element.Filename = _pathResolver.ResolveContentPath(element.Filename);
                    }
                    viewModel.AvatarElements = avatarElements;
                }

                var dashboardPage = await _dashboardContentService.GetCurrentContentAsync();

                if (dashboardPage != null && !string.IsNullOrWhiteSpace(dashboardPage.Content))
                {
                    viewModel.DashboardPageContent = CommonMark.CommonMarkConverter
                                                     .Convert(dashboardPage.Content);
                }

                viewModel.Carousel = await _carouselService.GetCurrentForDashboardAsync();

                if (TempData.ContainsKey(ModelData))
                {
                    var model = Newtonsoft.Json.JsonConvert
                                .DeserializeObject <DashboardViewModel>((string)TempData[ModelData]);
                    viewModel.ActivityAmount = model.ActivityAmount;
                    viewModel.Title          = model.Title;
                    viewModel.Author         = model.Author;
                }
                if (TempData.ContainsKey(ActivityErrorMessage))
                {
                    ModelState.AddModelError("ActivityAmount",
                                             _sharedLocalizer[(string)TempData[ActivityErrorMessage]]);
                    viewModel.ActivityAmount = null;
                }
                if (TempData.ContainsKey(TitleErrorMessage))
                {
                    ModelState.AddModelError(DisplayNames.Title,
                                             _sharedLocalizer[(string)TempData[TitleErrorMessage]]);
                }
                if (TempData.ContainsKey(AuthorErrorMessage))
                {
                    ModelState.AddModelError(DisplayNames.Author,
                                             _sharedLocalizer[(string)TempData[AuthorErrorMessage]]);
                }
                if (TempData.ContainsKey(SecretCodeMessage))
                {
                    viewModel.SecretCodeMessage
                        = _sharedLocalizer[(string)TempData[SecretCodeMessage]];
                }

                if (user.DailyPersonalGoal.HasValue)
                {
                    var programDays = (int)Math.Ceiling((
                                                            site.ProgramEnds.Value - site.ProgramStarts.Value).TotalDays);
                    viewModel.TotalProgramGoal = programDays * user.DailyPersonalGoal.Value;
                    viewModel.ActivityEarned   = await _activityService.GetActivityEarnedAsync();
                }
                else
                {
                    viewModel.TotalProgramGoal = program.AchieverPointAmount;
                    viewModel.ActivityEarned   = user.PointsEarned;
                    viewModel.ProgressMessage
                        = _sharedLocalizer[Annotations.Info.Goal, program.AchieverPointAmount];
                }
                viewModel.PercentComplete = Math.Min(
                    (int)(viewModel.ActivityEarned * 100 / viewModel.TotalProgramGoal), 100);

                var userVendorCode = await _vendorCodeService.GetUserVendorCodeAsync(user.Id);

                if (userVendorCode?.CanBeDonated == true && userVendorCode.IsDonated == null &&
                    (!userVendorCode.ExpirationDate.HasValue ||
                     userVendorCode.ExpirationDate.Value > _dateTimeProvider.Now))
                {
                    viewModel.HasPendingVendorCodeQuestion = true;
                    viewModel.VendorCodeExpiration         = userVendorCode.ExpirationDate;
                }

                return(View(ViewTemplates.Dashboard, viewModel));
            }
            else
            {
                return(await ShowLandingPageAsync(site, GetSiteStage()));
            }
        }
コード例 #5
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context,
                                                 ActionExecutionDelegate next)
        {
            var httpContext = context.HttpContext;

            if (httpContext.User.Identity.IsAuthenticated)
            {
                // Check if the user Id matches the active user id
                if (httpContext.Session.GetInt32(SessionKey.ActiveUserId)
                    == _userContextProvider.GetId(httpContext.User, ClaimType.UserId))
                {
                    // Check if user can access mission control
                    if (httpContext.User.HasClaim(ClaimType.Permission,
                                                  nameof(Permission.AccessMissionControl)))
                    {
                        httpContext.Items.Add(ItemKey.ShowMissionControl, true);
                    }

                    // Check if user can access performer registration
                    if (httpContext.User.HasClaim(ClaimType.Permission,
                                                  nameof(Permission.AccessPerformerRegistration)))
                    {
                        var settings = await _performerSchedulingService.GetSettingsAsync();

                        var schedulingStage = _performerSchedulingService
                                              .GetSchedulingStage(settings);
                        if (schedulingStage != PsSchedulingStage.Unavailable)
                        {
                            httpContext.Items.Add(ItemKey.ShowPerformerRegistration, true);
                        }
                    }
                }

                var pendingQuestionnaire = httpContext
                                           .Session
                                           .GetInt32(SessionKey.PendingQuestionnaire);

                if (pendingQuestionnaire.HasValue)
                {
                    var controllerActionDescriptor
                        = context.ActionDescriptor as ControllerActionDescriptor;
                    if (!controllerActionDescriptor.ControllerTypeInfo
                        .IsDefined(typeof(Attributes.PreventQuestionnaireRedirect)) &&
                        !controllerActionDescriptor.MethodInfo
                        .IsDefined(typeof(Attributes.PreventQuestionnaireRedirect)))
                    {
                        var controller = (Base.Controller)context.Controller;
                        context.Result = controller.RedirectToAction("Index",
                                                                     "Questionnaire",
                                                                     new { id = pendingQuestionnaire });
                        return;
                    }
                }
                try
                {
                    httpContext.Items[ItemKey.UnreadCount]
                        = await _mailService.GetUserUnreadCountAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error getting user unread mail count: {Message}", ex.Message);
                }

                var tempData = _tempDataFactory.GetTempData(httpContext);

                if (tempData.ContainsKey(TempDataKey.UserSignedIn))
                {
                    tempData.Remove(TempDataKey.UserSignedIn);
                    httpContext.Items[ItemKey.SignedIn] = true;
                }
            }
            await next();
        }