public async Task <IHttpActionResult> CreateAttemptAsync(GoalAttemptData attempt)
        {
            _log.LogDebug($"Request: {JsonConvert.SerializeObject(attempt)}");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            Goal goal = await _goalStore.GetGoalAsync(attempt.GoalId);

            if (goal == null || goal.UserId != user.Id)
            {
                _log.LogDebug($"Goal not found with id {attempt.GoalId} for user {user.Id}.");
                return(NotFound());
            }

            GoalAttempt newAttempt = await _attemptStore.CreateAttemptAsync(attempt.GoalId);

            _log.LogInfo($"Created goal-attempt for user {user.Id} : {newAttempt}");

            return(StatusCode(HttpStatusCode.Created));
        }
Example #2
0
        public async Task <IHttpActionResult> GetGoalsAsync()
        {
            _log.LogDebug("Request received.");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            var usersGoals = await _goalStore.GetGoalsAsync(user.Id);

            var goalDatas = new List <GoalData>();

            usersGoals.ForEach(g => goalDatas.Add(Mapper.Map <GoalData>(g)));

            goalDatas.Sort((g1, g2) => string.Compare(g1.Name, g2.Name));

            string serializeData = JsonConvert.SerializeObject(goalDatas);

            _log.LogDebug($"Returning goals {serializeData}.");

            return(Ok(serializeData));
        }
Example #3
0
        public async Task <IHttpActionResult> CreateGoalAsync(GoalData goalData)
        {
            _log.LogDebug($"Request: {JsonConvert.SerializeObject(goalData)}");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            Goal goal = await _goalStore.CreateGoalAsync(
                user.Id,
                goalData.Name,
                goalData.PeriodInHours,
                goalData.FrequencyWithinPeriod,
                goalData.StartDate);

            _log.LogDebug($"Goal created: {goal}");

            return(Ok(
                       JsonConvert.SerializeObject(
                           Mapper.Map <GoalData>(goal))));
        }
Example #4
0
        public async Task <IHttpActionResult> GetPeriodStatsAsync(int goalId)
        {
            _log.LogDebug($"Request: goalId={goalId}");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            Goal goal = await _goalStore.GetGoalAsync(goalId);

            if (goal == null || goal.UserId != user.Id)
            {
                _log.LogDebug($"Goal {goalId} not found for user {user.Id}.");
                return(NotFound());
            }

            GetPeriodBoundsForTime(goal, _dateTime.Now, out DateTime periodStart, out DateTime periodEnd);

            List <GoalAttempt> attemptsInDateOrder = await GetAttemptsForPeriod(goalId, periodStart, periodEnd);

            attemptsInDateOrder.Sort((a1, a2) => a1.Timestamp.CompareTo(a2.Timestamp));

            var mostRecentAttempt = attemptsInDateOrder.LastOrDefault(a => true);

            var stats = new GoalPeriodStatsData
            {
                GoalId             = goal.Id,
                PeriodStart        = periodStart,
                PeriodEnd          = periodEnd,
                AttemptCount       = attemptsInDateOrder.Count,
                LastAttemptDate    = mostRecentAttempt?.Timestamp,
                TargetAttemptCount = goal.FrequencyWithinPeriod
            };

            await PopulateWithGoalCompletionStats(goalId, stats);

            _log.LogDebug($"Retrieved stats for user {user.Id}, goal {goalId} : {JsonConvert.SerializeObject(stats)}");

            return(Ok(JsonConvert.SerializeObject(stats)));
        }
Example #5
0
        public void GetUserForRequestHeaderTokenAsync_GivenNoToken_ShouldRaiseException()
        {
            // Arrange.
            var controller = Substitute.For <ApiController>();
            var tokenStore = Substitute.For <ITokenStore>();
            var userStore  = Substitute.For <IUserStore>();
            var log        = Substitute.For <ILogger>();

            controller.ControllerContext = new HttpControllerContext
            {
                Request = new HttpRequestMessage()
            };

            // Act & Assert.
            Assert.That(
                async() => await ControllerUtils.GetUserForRequestHeaderTokenAsync(controller, tokenStore, userStore, log),
                Throws.TypeOf <AuthenticationException>().With.Message.EqualTo("No token provided."));
        }
Example #6
0
        public void GetUserForRequestHeaderTokenAsync_GivenTokenNotInStore_ShouldRaiseException()
        {
            // Arrange.
            var controller = Substitute.For <ApiController>();
            var tokenStore = Substitute.For <ITokenStore>();
            var userStore  = Substitute.For <IUserStore>();
            var log        = Substitute.For <ILogger>();

            controller.ControllerContext = new HttpControllerContext
            {
                Request = new HttpRequestMessage()
            };
            controller.ControllerContext.Request.Headers.Add("auth", Guid.NewGuid().ToString());

            // Act & Assert.
            Assert.That(
                async() => await ControllerUtils.GetUserForRequestHeaderTokenAsync(controller, tokenStore, userStore, log),
                Throws.TypeOf <AuthenticationException>().With.Message.EqualTo("User token not found, it may have expired."));
        }
        public async Task <IHttpActionResult> DeleteAttemptAsync(int attemptId)
        {
            _log.LogDebug($"Request: attemptId={attemptId}");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            GoalAttempt attempt = await _attemptStore.GetAttemptAsync(attemptId);

            if (attempt == null)
            {
                _log.LogDebug($"Goal-attempt not found with id {attemptId} for user {user.Id}.");
                return(NotFound());
            }

            Goal goal = await _goalStore.GetGoalAsync(attempt.GoalId);

            if (goal == null || goal.UserId != user.Id)
            {
                _log.LogDebug($"Goal not found with id {attempt.GoalId} for user {user.Id}.");
                return(NotFound());
            }

            await _attemptStore.RemoveAttemptAsync(attemptId);

            _log.LogInfo($"Deleted goal-attempt {attemptId} for user {user.Id}.");

            return(Ok());
        }
        public async Task <IHttpActionResult> GetAttemptsAsync(int goalId)
        {
            _log.LogDebug($"Request: goalId={goalId}");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            Goal goal = await _goalStore.GetGoalAsync(goalId);

            if (goal == null || goal.UserId != user.Id)
            {
                _log.LogDebug($"Goal not found with id {goalId} for user {user.Id}.");
                return(NotFound());
            }

            var attempts = await _attemptStore.GetAttempts(goalId).ToListAsync();

            var attemptDatas = new List <GoalAttemptData>();

            attempts.ForEach(a => attemptDatas.Add(Mapper.Map <GoalAttemptData>(a)));

            string serialisedAttempts = JsonConvert.SerializeObject(attemptDatas);

            _log.LogDebug($"Found attempts for goal id {goalId} for user {user.Id} : {serialisedAttempts}");

            return(Ok(serialisedAttempts));
        }
Example #9
0
        public void GetUserForRequestHeaderTokenAsync_GivenValidTokenButUserNotFound_ShouldRaiseException()
        {
            // Arrange.
            var controller = Substitute.For <ApiController>();
            var tokenStore = Substitute.For <ITokenStore>();
            var userStore  = Substitute.For <IUserStore>();
            var log        = Substitute.For <ILogger>();
            var guid       = Guid.NewGuid();

            controller.ControllerContext = new HttpControllerContext
            {
                Request = new HttpRequestMessage()
            };
            controller.ControllerContext.Request.Headers.Add("auth", guid.ToString());

            tokenStore.GetExistingValidTokenByGuidAsync(guid).Returns(new Token());

            // Act & Assert.
            Assert.That(
                async() => await ControllerUtils.GetUserForRequestHeaderTokenAsync(controller, tokenStore, userStore, log),
                Throws.TypeOf <InternalServerException>());
        }
        public async Task <IHttpActionResult> DeleteLastAttemptAsync(int goalId)
        {
            _log.LogDebug($"Request: goalId={goalId}");

            User user;

            try
            {
                user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(this, _tokenStore, _userStore, _log);
            }
            catch (AuthenticationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (InternalServerException)
            {
                return(InternalServerError());
            }

            Goal goal = await _goalStore.GetGoalAsync(goalId);

            if (goal == null || goal.UserId != user.Id)
            {
                _log.LogDebug($"Goal not found with id {goalId} for user {user.Id}.");
                return(NotFound());
            }

            GoalAttempt lastAttempt =
                await _attemptStore.GetAttempts(goalId)
                .OrderByDescending(a => a.Timestamp)
                .FirstOrDefaultAsync();

            await _attemptStore.RemoveAttemptAsync(lastAttempt.Id);

            _log.LogInfo($"Deleted goal-attempt {lastAttempt.Id} for user {user.Id}.");

            return(Ok());
        }
Example #11
0
        public async Task GetUserForRequestHeaderTokenAsync_GivenValidToken_ShouldReturnUser()
        {
            // Arrange.
            var controller = Substitute.For <ApiController>();
            var tokenStore = Substitute.For <ITokenStore>();
            var userStore  = Substitute.For <IUserStore>();
            var log        = Substitute.For <ILogger>();
            var guid       = Guid.NewGuid();

            controller.ControllerContext = new HttpControllerContext
            {
                Request = new HttpRequestMessage()
            };
            controller.ControllerContext.Request.Headers.Add("auth", guid.ToString());

            tokenStore.GetExistingValidTokenByGuidAsync(guid).Returns(new Token());
            userStore.GetUserAsync(Arg.Any <Token>()).Returns(new User());

            // Act.
            User user = await ControllerUtils.GetUserForRequestHeaderTokenAsync(controller, tokenStore, userStore, log);

            // Assert.
            Assert.NotNull(user);
        }