Ejemplo n.º 1
0
        public async Task <ActionResult <EpisodeWithValidUntilClaim> > GetCurrentClaimedEpisode()
        {
            try
            {
                User user = await _auth.GetUserFromValidToken(Request);

                EpisodeWithValidUntilClaim claimedEpisode = await _claim.GetUserByClaimedEpisodeAsync(user.Id);

                if (claimedEpisode == null)
                {
                    return(BadRequest("Currently there are no claimed episodes by this user."));
                }
                return(Ok(claimedEpisode));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Sequence contains no elements"))
                {
                    return(BadRequest("Currently there are no claimed episodes by this user."));
                }

                _logger.LogError($"Error while trying to get the episode the user currently has claimed. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> PostSubmit()
        {
            try
            {
                User user = await _auth.GetUserFromValidToken(Request);

                Episode claimedEpisode = await _claim.GetUserByClaimedEpisodeAsync(user.Id);

                await _claim.DeleteClaimByEpisodeIdAsync(claimedEpisode.Id);

                return(Ok());
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Sequence contains no elements"))
                {
                    return(BadRequest("Currently there are no claimed episodes by this user."));
                }

                _logger.LogError($"Error trying to submit a claimed episode. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> ForceDelete(int id) // id = EpisodeId
        {
            if (id == 0)
            {
                return(BadRequest("Id cannot be 0!"));
            }
            if (id < 0)
            {
                return(BadRequest("Id cannot be smaller than 0!"));
            }

            User user = null;

            try
            {
                user = await _auth.GetUserFromValidToken(Request);
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                _logger.LogError($"Error trying to get the user that is deleting the claim on episode with id {id}. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
                return(Problem());
            }

            try
            {
                if (!await _auth.CheckIfUserHasElivatedPermission(Request))
                {
                    return(Unauthorized());
                }

                await _claim.DeleteClaimByEpisodeIdAsync(id);

                return(Ok());
            }
            catch (EpisodeUnclaimedButAlreadyHasTopcisException e)
            {
                return(BadRequest("Episode is already claimed!"));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while trying to delete the claim on episode with id: {id}. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
Ejemplo n.º 4
0
        public async Task <ActionResult <ClaimResponse> > ReassingEpisode([FromBody] TopicReasingPostRequest topicReasing)
        {
            User user = null;

            try
            {
                user = await _auth.GetUserFromValidToken(Request);
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while trying to get user trying to reassing episode with id: {topicReasing.EpisodeId} to user with id: {topicReasing.UserId}. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
                return(Problem());
            }

            try
            {
                if (!await _auth.CheckIfUserHasElivatedPermission(Request))
                {
                    return(Unauthorized());
                }
                _logger.LogInformation($"A user with the id: {user.Id} and the role id: {user.RolesId} is reassigning the episode with the id: {topicReasing.EpisodeId} to the user with the id: {topicReasing.UserId}");

                EpisodeExtended episode = await _database.GetMinimalEpisodeAsync(topicReasing.EpisodeId);

                if (episode.Claimed)
                {
                    return(BadRequest("Episode is already claimed!"));
                }

                ClaimResponse response = await _claim.ReassingClaimAsync(episode, topicReasing.UserId);

                return(Ok(response));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while trying to reassing claim. Reassing was requested by user with id: {user.Id}. Episode requested to be reassigned is episode with id: {topicReasing.EpisodeId}. The user it should be reassigned to has is: {topicReasing.UserId}. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
        public async Task <ActionResult> GetEpisode(int episodeId)
        {
            bool isEditingRequestedEpisode = false;
            int  userId = 0;

            try
            {
                User user = await _authenticationService.GetUserFromValidToken(Request);

                userId = user.Id;
                if (await _authenticationService.CheckIfUserHasElivatedPermissionByUserObject(user))
                {
                    isEditingRequestedEpisode = true;
                }
                else
                {
                    Episode claimedEpisode = await _claims.GetUserByClaimedEpisodeAsync(user.Id);

                    isEditingRequestedEpisode = claimedEpisode.Id == episodeId;
                }
            }
            catch (TokenDoesNotExistException e)
            {
                // ignore lol -> could happen all the time
            }
            catch (InvalidOperationException e)
            {
                // Ignore
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                _logger.LogError(e.Message);
            }

            try
            {
                return(Ok(await _databaseService.GetEpisodeAsync(episodeId, isEditingRequestedEpisode, userId)));
            }
            catch (InvalidOperationException e)
            {
                return(NoContent());
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                _logger.LogError(e.Message);
                return(Problem());
            }
        }
        public async Task <ActionResult <List <TopicExtended> > > PostTopicList([FromBody] TopicRequest request)
        {
            if (request.Topics == null)
            {
                return(BadRequest("Topic list is null!"));
            }

            try
            {
                User user = await _auth.GetUserFromValidToken(Request);

                Episode claimedEpisode = await _claims.GetUserByClaimedEpisodeAsync(user.Id);

                // Topics and Subtopics
                await _database.DeleteTopicAndSubtopicAsync(claimedEpisode.Id);

                await _database.ResetIdentityForTopicAndSubtopicsAsync();

                for (int i = 0; i < request.Topics.Count; i++)
                {
                    await _database.InsertTopicAsync(new ProcessedTopicPostRequest(request.Topics[i]), claimedEpisode.Id, user.Id);
                }

                // People
                await _database.DeletePeopleFromEpisodeByEpisodeIdAsync(claimedEpisode.Id);

                await _database.ResetIdentityForPersonInEpisodeTableAsync();

                await _database.InsertPeopleInEpisodeAsync(request.People, claimedEpisode.Id);

                EpisodeExtendedExtra episode = await _database.GetEpisodeAsync(claimedEpisode.Id, true, user.Id);

                return(Ok(episode));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Sequence contains no elements"))
                {
                    return(Unauthorized("User has no claimed episode!"));
                }

                SentrySdk.CaptureException(e);
                _logger.LogError("Error while trying to post a list of topics. Error:\n" + e.Message);
                return(Problem());
            }
        }
        public async Task <ActionResult <EpisodeResponse> > GetEpisodes(int page, int per_page)
        {
            if (page == 0)
            {
                page = 1;
            }

            int userId = 0;

            try
            {
                User user = await _authenticationService.GetUserFromValidToken(Request);

                userId = user.Id;
            }
            catch (TokenDoesNotExistException e)
            {
                // ignore lol -> could happen all the time
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                _logger.LogError(e.Message);
            }

            try
            {
                EpisodeResponse episodeResponse = new EpisodeResponse();

                episodeResponse.Data = await _databaseService.GetEpisodesAsync(page, per_page, userId);

                episodeResponse.Meta.EpisodeCount = await _databaseService.GetEpisodeCountAsync();

                episodeResponse.Meta.EpisodeMaxPageCount = (int)Math.Ceiling((decimal)episodeResponse.Meta.EpisodeCount / per_page);

                if (episodeResponse.Data.Count == 0)
                {
                    return(NoContent());
                }

                return(Ok(episodeResponse));
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                _logger.LogError(e.Message);
                return(Problem());
            }
        }
Ejemplo n.º 8
0
        public async Task <ActionResult <ClaimResponse> > Post(int id) // id = EpisodeId
        {
            if (id == 0)
            {
                return(BadRequest("Id cannot be 0!"));
            }
            if (id < 0)
            {
                return(BadRequest("Id cannot be smaller than 0!"));
            }

            try
            {
                User user = await _auth.GetUserFromValidToken(Request);

                EpisodeExtended episode = await _database.GetMinimalEpisodeAsync(id);

                if (episode.Claimed)
                {
                    return(BadRequest("Episode is already claimed!"));
                }

                ClaimResponse response = await _claim.ClaimEpisodeAsync(episode, user.Id);

                return(Ok(response));
            }
            catch (EpisodeUnclaimedButAlreadyHasTopcisException e)
            {
                return(BadRequest("Episode is already claimed!"));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                if (e.Message.Contains("23505") || e.Message.Contains("unique_user"))
                {
                    _logger.LogError($"User tried to claim episode wiht id {id}. But the user already claimed another episode.");
                    return(BadRequest("User already has another claimed episode!"));
                }

                _logger.LogError($"Error while trying to claim episode with id: {id}. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
        public async Task <IActionResult> Post(int id)
        {
            try
            {
                User user = await _authenticationService.GetUserFromValidToken(Request);

                if (!await _authenticationService.CheckIfUserHasElivatedPermissionByUserObject(user))
                {
                    return(Unauthorized());
                }

                EpisodeExtendedExtra episode = await _databaseService.GetEpisodeAsync(id, true, user.Id);

                if (episode.Topic == null || episode.Topic.Count == 0)
                {
                    return(BadRequest("Episode has nothing to verify."));
                }

                if (episode.Verified)
                {
                    return(BadRequest("Episode is already verified."));
                }

                await _databaseService.VerifyEpisodeAsync(id);

                await _search.AddTopicsAsync(episode.Topic);

                return(Ok());
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Sequence contains no elements"))
                {
                    return(BadRequest("Episode is not open to verify."));
                }

                SentrySdk.CaptureException(e);
                _logger.LogError(e.Message);
                return(Problem());
            }
        }
        public async Task <ActionResult <EpisodeAlternateResponse> > GetUnverifiedAllEpisodes(int page, int per_page)
        {
            if (page == 0)
            {
                page = 1;
            }

            try
            {
                User user = await _authenticationService.GetUserFromValidToken(Request);

                if (!await _authenticationService.CheckIfUserHasElivatedPermissionByUserObject(user))
                {
                    return(Unauthorized());
                }

                EpisodeAlternateResponse episodeResponse = new EpisodeAlternateResponse();

                episodeResponse.Data = await _databaseService.GetEpisodeAwaitingVerificationAsync(page, per_page);

                episodeResponse.Meta.EpisodeCount = await _databaseService.GetUnverifiedEpisodeCountAsync();

                episodeResponse.Meta.EpisodeMaxPageCount = (int)Math.Ceiling((decimal)episodeResponse.Meta.EpisodeCount / per_page);

                if (episodeResponse.Data.Count == 0)
                {
                    return(NoContent());
                }

                return(Ok(episodeResponse));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                _logger.LogError(e.Message);
                return(Problem());
            }
        }
        public async Task <TokenExtended> LoginAsync(string username, string password)
        {
            User       user             = null;
            TokenCache cachedToken      = CheckForValidTokenByUsername(username);
            bool       validTokenCached = cachedToken == null;

            if (validTokenCached)
            {
                user = await _databaseService.GetUserByUsernameAsync(username);
            }
            else
            {
                user = cachedToken.User;
            }

            if (user.EmailVerifiedAt == null || user.EmailVerificationId != "")
            {
                throw new UserEmailNotVerifiedException();
            }

            string tempPassword = $"{_configuration["Auth:FrontSalt"]}{password}{_configuration["Auth:BackSalt"]}";

            byte[] salt           = user.Salt;
            string hashedPassword = HashPassword(tempPassword, salt);

            TokenExtended token = null;

            if (hashedPassword == user.Password)
            {
                token = CreateToken(user.Id);
                await _databaseService.CreateRefreshTokenAsync(token);

                TokenCache.Add(new TokenCache(token, user));
            }
            else
            {
                throw new PasswordOrEmailIncorrectException();
            }

            return(token);
        }
        public async Task <ActionResult> Post(int episodeId)
        {
            try
            {
                User user = await _auth.GetUserFromValidToken(Request);

                await _database.DeleteVoteForEpisode(episodeId, user.Id);

                return(Ok());
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while trying to delete vote for episode with id: {episodeId}. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
Ejemplo n.º 13
0
        public async Task <ActionResult <ClaimResponse> > PostAdditionalTime()
        {
            try
            {
                User user = await _auth.GetUserFromValidToken(Request);

                Episode claimedEpisode = await _claim.GetUserByClaimedEpisodeAsync(user.Id);

                await _claim.AddExtraTimeToClaimAsync(user.Id);

                return(Ok(await _claim.GetValidUntilByUserId(user.Id)));
            }
            catch (TimeExtendedTooOftenException)
            {
                return(BadRequest("The time was already extended too often."));
            }
            catch (ClaimNotNearEnoughToInvalidationException)
            {
                return(BadRequest("Claim is not close enough to invalidation, please wait until the last 5 minutes to extend the valid until time."));
            }
            catch (TokenDoesNotExistException e)
            {
                return(Unauthorized());
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Sequence contains no elements"))
                {
                    return(BadRequest("Currently there are no claimed episodes by this user."));
                }

                _logger.LogError($"Error extend claim time. Error:\n{e.Message}");
                SentrySdk.CaptureException(e);
            }

            return(Problem());
        }
        public async Task <Token> RefreshTokenAsync(RefreshTokenRequest refreshTokenRequest)
        {
            User user = await _databaseService.GetUserByUserIdAsync(refreshTokenRequest.UserId);

            // This logic checks if a refresh token exists. If not, it will throw the exception 'RefreshTokenDoesNotExist'.
            try
            {
                TokenCache token = await _databaseService.GetRefreshTokenAsync(refreshTokenRequest.RefreshToken);
            }
            catch (RefreshTokenDoesNotExist e)
            {
                throw new RefreshTokenDoesNotExist();
            }

            TokenExtended extendedToken = CreateToken(user.Id);

            extendedToken.RefreshToken = refreshTokenRequest.RefreshToken;
            TokenCache cacheToken = new TokenCache(extendedToken, user);

            TokenCache.Add(cacheToken);
            Token newToken = new Token(cacheToken);

            return(newToken);
        }
 public async Task <bool> CheckIfUserHasElivatedPermissionByUserObject(User user)
 {
     return(RoleMisc.UserHasElevatedPermission(user.RolesId));
 }
        /// <summary>
        /// Wrapper to check if the user has elivated Permissions (Moderator or Admin role).
        /// </summary>
        /// <param name="request"></param>
        /// <returns>True/False</returns>
        /// <exception cref="TokenDoesNotExistException"></exception>
        public async Task <bool> CheckIfUserHasElivatedPermission(HttpRequest request)
        {
            User user = await GetUserFromValidToken(request);

            return(RoleMisc.UserHasElevatedPermission(user.RolesId));
        }