public async Task CreatesUserSessionInDbSuccessfully()
        {
            // Arrange
            var dfcUserSession = CreateDfcUserSession();
            var questionSet    = CreateQuestionSet();
            var ms             = new MemoryStream();

            using var sw = new StreamWriter(ms);

            sw.Write(JsonConvert.SerializeObject(dfcUserSession));
            sw.Flush();
            ms.Position = 0;

            A.CallTo(() => httpRequest.Body).Returns(ms);
            A.CallTo(() => questionSetRepository.GetCurrentQuestionSet(A <string> .Ignored)).Returns(questionSet);
            A.CallTo(() => userSessionRepository.GetByIdAsync(A <string> .Ignored, A <string> .Ignored)).Returns((UserSession)null);
            A.CallTo(() => sessionClient.ValidateUserSession(A <DfcUserSession> .Ignored)).Returns(true);

            // Act
            var result = await functionApp.CreateNewSkillsAssessment(httpRequest).ConfigureAwait(false);

            // Assert
            var statusCodeResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal((int)HttpStatusCode.Created, statusCodeResult.StatusCode);
            A.CallTo(() => userSessionRepository.CreateUserSession(A <UserSession> .Ignored)).MustHaveHappenedOnceExactly();
        }
コード例 #2
0
        /// <summary>
        /// Авторизация пользователя, и сохранение данных о нем в куки
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private bool authenticate(UserViewModel user)
        {
            var userProfile = new UserProfileSessionData(userRepository.GetUser(user.email, user.pwd));

            UserStorage.Set(userProfile);

            userSessionRepository.CreateUserSession(new Domain.Core.UserSession
            {
                SessionID = Session.SessionID,
                UserID    = userProfile.ID,
                Start     = DateTime.Now,
                IP        = Request.UserHostAddress
            });
            try
            {
                userSessionRepository.Save();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Ошибка при создании UserSession");
                return(false);
            }
            return(true);
            // return new Authenticate { IsAuthenticated = true, UserName = userProfile.Name ?? userProfile.Login };
        }
        private async Task CreateUserSession(QuestionSet currentQuestionSetInfo, DfcUserSession dfcUserSession, string partitionKey = null)
        {
            var userSession = new UserSession
            {
                UserSessionId   = dfcUserSession.SessionId,
                Salt            = dfcUserSession.Salt,
                StartedDt       = dfcUserSession.CreatedDate,
                LanguageCode    = "en",
                PartitionKey    = !string.IsNullOrWhiteSpace(partitionKey) ? partitionKey : dfcUserSession.PartitionKey,
                AssessmentState = new AssessmentState(currentQuestionSetInfo.QuestionSetVersion, currentQuestionSetInfo.MaxQuestions),
                AssessmentType  = currentQuestionSetInfo.AssessmentType.ToLowerInvariant(),
            };

            await userSessionRepository.CreateUserSession(userSession).ConfigureAwait(false);
        }
        public async Task ReturnsCreatedDfcUserSession()
        {
            // Arrange
            var dfcSession = new DfcUserSession
            {
                PartitionKey = "partitionKey",
                CreatedDate  = DateTime.UtcNow,
                SessionId    = "sessionId",
                Salt         = "ncs",
            };

            A.CallTo(() => sessionClient.NewSession()).Returns(dfcSession);

            var questionSet = new QuestionSet
            {
                QuestionSetVersion = "qsVersion",
                AssessmentType     = "short",
                MaxQuestions       = 5,
                PartitionKey       = "partitionKey",
                Description        = "short description",
                IsCurrent          = true,
                LastUpdated        = DateTimeOffset.UtcNow,
                QuestionSetKey     = "qsKey",
                Title   = "qstitle",
                Version = 1,
            };

            A.CallTo(() => questionSetRepository.GetCurrentQuestionSet(A <string> .Ignored)).Returns(questionSet);

            // Act
            var result = await functionApp.CreateNewShortAssessment(httpRequest).ConfigureAwait(false);

            var okObjectResult     = Assert.IsType <OkObjectResult>(result);
            var deserialisedResult = JsonConvert.DeserializeObject <DfcUserSession>(okObjectResult.Value.ToString());

            // Assert
            deserialisedResult.Should().BeEquivalentTo(dfcSession);
            A.CallTo(() => userSessionRepository.CreateUserSession(A <UserSession> .Ignored)).MustHaveHappenedOnceExactly();
        }
コード例 #5
0
        public async Task GetSessionReturnsDfcUserSession()
        {
            // Arrange
            var sessionId   = $"sessionId{Guid.NewGuid()}";
            var startedDate = DateTime.UtcNow;

            var userSession = CreateUserSession(sessionId, startedDate);
            await userSessionRepository.CreateUserSession(userSession).ConfigureAwait(false);

            var expectedDfcUserSession = CreateDfcUserSession(sessionId, startedDate);
            var client = new RestClient(apiBaseUrl);
            var req    = new RestRequest($"assessment/session/{sessionId}", Method.GET);

            // Act
            var response = client.Execute(req);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var deserialisedResult = JsonConvert.DeserializeObject <DfcUserSession>(response.Content);

            deserialisedResult.Should().BeEquivalentTo(expectedDfcUserSession);
        }
コード例 #6
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "assessment")] HttpRequest req,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionSetRepository questionSetRepository,
            [Inject] IOptions <AppSettings> appSettings)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogWarning("Unable to locate 'DssCorrelationId' in request header");
                    correlationId = Guid.NewGuid().ToString();
                }

                log.LogInformation($"CorrelationId: {correlationId} - Creating a new assessment");

                // Get the assessmentType and questionSetTitle values from the query string
                var queryDictionary = System.Web.HttpUtility.ParseQueryString(req.QueryString.ToString());
                var assessmentType  = queryDictionary.Get("assessmentType");
                if (string.IsNullOrEmpty(assessmentType))
                {
                    log.LogInformation($"CorrelationId: {correlationId} - Missing assessmentType {assessmentType}");
                    return(httpResponseMessageHelper.BadRequest());
                }

                // Get the current question set version for this assesssment type and title (supplied by CMS - configured in appsettings)
                var currentQuestionSetInfo = await questionSetRepository.GetCurrentQuestionSet(assessmentType);

                if (currentQuestionSetInfo == null)
                {
                    log.LogInformation($"CorrelationId: {correlationId} - Unable to load latest question set {assessmentType}");
                    return(httpResponseMessageHelper.NoContent());
                }


                // Create a new user session
                string salt         = appSettings.Value.SessionSalt;
                string sessionId    = SessionIdHelper.GenerateSessionId(salt);
                string partitionKey = PartitionKeyGenerator.UserSession(sessionId);

                var userSession = new UserSession()
                {
                    UserSessionId   = sessionId,
                    Salt            = salt,
                    StartedDt       = DateTime.Now,
                    LanguageCode    = "en",
                    PartitionKey    = partitionKey,
                    AssessmentState = new AssessmentState(currentQuestionSetInfo.QuestionSetVersion, currentQuestionSetInfo.MaxQuestions),
                    AssessmentType  = currentQuestionSetInfo.AssessmentType.ToLower()
                };
                await userSessionRepository.CreateUserSession(userSession);

                log.LogInformation($"CorrelationId: {correlationId} - Finished creating new assessment {userSession.UserSessionId}");

                var result = new FilterSessionResponse()
                {
                    SessionId = userSession.PrimaryKey
                };
                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }