Exemple #1
0
 public HostController(SessionStorageService sessionStorageService, SpotifyService spotify, QuestionService questionService, GameService gameService)
 {
     sessionService       = sessionStorageService;
     this.spotify         = spotify;
     this.questionService = questionService;
     this.gameService     = gameService;
 }
        protected async override Task OnInitializedAsync()
        {
            NotificationValues = await SessionStorageService.GetItemAsync <NotificationNames>(Id);

            DefaultSelectedNotificationType    = "Select Notification Type";
            DefaultSelectedNotificationChannel = "Select Notification Channel";
            if (!string.IsNullOrEmpty(Id))
            {
                var id = int.Parse(Id);
                if (id > 0)
                {
                    notificationTemplateCrtVM = await NotificationTemplateService.FetchByIdAsync(id);

                    NotificationId = notificationTemplateCrtVM.Id;

                    DefaultSelectedNotificationType       = NotificationValues.NotificationTypeName == null
                        ? DefaultSelectedNotificationType = "Select Notification Type" : NotificationValues.NotificationTypeName;

                    DefaultSelectedNotificationChannel       = NotificationValues.NotificationChannelName == null
                        ? DefaultSelectedNotificationChannel = "Select Notification Channel" : NotificationValues.NotificationChannelName;
                }

                notificationTypeVMs = await NotificationTypeService.FetchAllAsync();

                notificationChannelVMs = await NotificationChannelService.FetchAllAsync();
            }
        }
Exemple #3
0
        /// <summary>
        /// Creates or retrieves a session for the user
        /// </summary>
        /// <param name="customId">A custom session ID. This will take precedence over an existing session.</param>
        /// <returns>A Tuple that contains the session object and a boolean indicating whether the session was newly created</returns>
        private async Task <Tuple <UserSession, bool> > CreateOrRetrieveSessionAsync(Guid?customId = null)
        {
            UserSession ret        = null;
            var         newSession = true; // Whether the session is new
            // Check if a stored session is available
            var storedSessData        = Request.Session[SessionStorageService.SessionUserCookieStorageKey] as string;
            var sessionStorageService = new SessionStorageService(ServerContext);

            if (storedSessData != null && customId == null)
            {
                // [Attempt to] Find matching session
                ret = await sessionStorageService.GetSessionFromIdentifierAsync(storedSessData);

                // If return is not null, session was already available, don't create new session, reuse
                newSession &= ret == null;
            }
            if (storedSessData == null || ret == null || customId != null)
            {
                // Register and attempt to save session
                var session = new UserSession(customId ?? Guid.NewGuid())
                {
                    UserAgent = Request.Headers.UserAgent,
                    StartTime = DateTime.Now
                };
                // Register session in database
                await sessionStorageService.SaveSessionAsync(session);

                // Store session data
                Request.Session[SessionStorageService.SessionUserCookieStorageKey] = session.SessionId;
                ret        = session;
                newSession = true;
            }
            return(new Tuple <UserSession, bool>(ret, newSession));
        }
Exemple #4
0
        public void Then_The_Object_Is_Deleted_From_Session(
            [Frozen] Mock <IHttpContextAccessor> mockAccessor,
            SessionStorageService <TestModel> sessionStore)
        {
            sessionStore.Delete();

            mockAccessor.Verify(x => x.HttpContext.Session.Remove(nameof(TestModel)), Times.Once);
        }
Exemple #5
0
        /// <summary>
        /// Acccess the session storage to log the user in.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task <bool> LoginAsync(string username, string password)
        {
            var user = await UserRepository.GetByKeyAsync(username);

            if (user == null || !string.Equals(password, user.Password))
            {
                return(false);
            }

            await SessionStorageService.SetItemAsync(Constants.User, user.Username);

            return(true);
        }
Exemple #6
0
        public void Then_Null_Is_Returned_If_The_Object_Does_Not_Exist_In_Session(
            [Frozen] Mock <IHttpContextAccessor> mockAccessor,
            [Frozen] Mock <ISession> mockSession,
            SessionStorageService <TestModel> sessionStore)
        {
            byte[] bytes = null;
            mockSession.Setup(x => x.TryGetValue(nameof(TestModel), out bytes)).Returns(false);
            mockAccessor.Setup(x => x.HttpContext.Session).Returns(mockSession.Object);

            var actual = sessionStore.Get();

            Assert.IsNull(actual);
        }
Exemple #7
0
        public void Then_The_Object_Is_Serialized_And_Saved_To_The_Session(
            TestModel testModel,
            [Frozen] Mock <ISession> mockSession,
            [Frozen] Mock <IHttpContextAccessor> mockAccessor,
            SessionStorageService <TestModel> sessionStore)
        {
            var expectedModel = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(testModel));

            mockAccessor.Setup(x => x.HttpContext.Session).Returns(mockSession.Object);

            sessionStore.Store(testModel);

            mockSession.Verify(x => x.Set(nameof(TestModel), expectedModel), Times.Once);
        }
Exemple #8
0
        public void Then_The_Object_Is_Returned_From_Session_If_It_Exists(
            TestModel testModel,
            [Frozen] Mock <ISession> mockSession,
            [Frozen] Mock <IHttpContextAccessor> mockAccessor,
            SessionStorageService <TestModel> sessionStore)
        {
            var value = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(testModel));

            mockSession.Setup(x => x.TryGetValue(nameof(TestModel), out value)).Returns(true);
            mockAccessor.Setup(x => x.HttpContext.Session).Returns(mockSession.Object);

            var actual = sessionStore.Get();

            actual.Should().BeEquivalentTo(testModel);
        }
 protected void EditNotificationType(string notifictionValues)
 {
     if (!string.IsNullOrEmpty(notifictionValues))
     {
         var    parts = notifictionValues.Split("_");
         var    Id    = parts[0];
         string notificationTypeName    = parts[1];
         string notificationChannelName = parts[2];
         string notificationTypeId      = parts[3];
         string notificationChannelId   = parts[4];
         SessionStorageService.SetItemAsync(Id, new NotificationNames(notificationTypeName,
                                                                      notificationChannelName,
                                                                      notificationTypeId,
                                                                      notificationChannelId));
         NavigationManager.NavigateTo($"/createnotificationtemplate/{Id}");
     }
 }
Exemple #10
0
        public DataQueryModule(INAServerContext serverContext) : base("/qr")
        {
            ServerContext = serverContext;
            var accessValidator = new StatelessClientValidator <NAAccessKey, NAApiAccessScope>();

            this.RequiresAllClaims(new[] { accessValidator.GetAccessClaim(NAApiAccessScope.Query) },
                                   accessValidator.GetAccessClaim(NAApiAccessScope.Admin));

            // Query Log Requests
            // Limit is the max number of log requests to return. Default 100
            Get("/log/{limit:int}", async args =>
            {
                var itemLimit         = args.limit as int? ?? 100;
                var dataLoggerService = new DataLoggerService(ServerContext);
                var data = await dataLoggerService.QueryRequestsAsync(itemLimit);
                return(Response.AsJsonNet(data));
            });

            // Query SessionData
            // Id is the ID of the session to find
            Get("/sessdata/{id}", async args =>
            {
                var sessionStorageService = new SessionStorageService(ServerContext);
                var data = await sessionStorageService.GetSessionFromIdentifierAsync((string)args.id);
                return(Response.AsJsonNet(data));
            });

            // Query Tagged Requests
            // Tag is the tag to filter by
            // Limit is the max number of log requests to return
            Get("/tagged/{tags}/{limit:int}", async args =>
            {
                var itemLimit         = args.limit as int? ?? 100;
                var filterTags        = (args.tags != null) ? ((string)args.tags).Split(',') : null;
                var dataLoggerService = new DataLoggerService(ServerContext);
                var data = await dataLoggerService.QueryTaggedRequestsAsync(itemLimit, filterTags);
                return(Response.AsJsonNet(data));
            });
        }
Exemple #11
0
        /// <summary>
        /// Returns of the user is logged in.
        /// </summary>
        /// <returns></returns>
        public async Task <bool> IsLoggedIn()
        {
            try
            {
                var user = await SessionStorageService.GetItemAsync <string>(Constants.User);

                return(!string.IsNullOrWhiteSpace(user));
            }
            // We catch exceptions individually
            // this gives better control if we later
            // need to handle each situation differnt
            // and is concidered best practice.
            catch (NullReferenceException e)
            {
                Logger.LogException(e);
            }
            catch (Exception e)
            {
                Logger.LogException(e);
            }

            return(false);
        }
Exemple #12
0
 public PlayerController(SessionStorageService sessionStorageService, QuestionService questionService, GameService gameService)
 {
     sessionService       = sessionStorageService;
     this.questionService = questionService;
     this.gameService     = gameService;
 }