diff options
| author | Danail Dimitrov <danaildimitrov321@gmail.com> | 2021-01-03 21:49:47 +0200 |
|---|---|---|
| committer | Danail Dimitrov <danaildimitrov321@gmail.com> | 2021-01-03 21:49:47 +0200 |
| commit | be9c9e7721610536259f1ea997c259956c894bbd (patch) | |
| tree | 57db31d4fe42376d3e45cfba59d4b6bd21ec1329 /src/DevHive.Services | |
| parent | 278130d86378a6b2db6ba443631f303fb7d7e207 (diff) | |
| download | DevHive-be9c9e7721610536259f1ea997c259956c894bbd.tar DevHive-be9c9e7721610536259f1ea997c259956c894bbd.tar.gz DevHive-be9c9e7721610536259f1ea997c259956c894bbd.zip | |
added user validation for deleting and updating comments
Diffstat (limited to 'src/DevHive.Services')
| -rw-r--r-- | src/DevHive.Services/Services/PostService.cs | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/src/DevHive.Services/Services/PostService.cs b/src/DevHive.Services/Services/PostService.cs index 0c0fd5c..b2ea694 100644 --- a/src/DevHive.Services/Services/PostService.cs +++ b/src/DevHive.Services/Services/PostService.cs @@ -1,21 +1,26 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using DevHive.Data.Models; using DevHive.Data.Repositories; using DevHive.Services.Models.Post.Comment; using DevHive.Services.Models.Post.Post; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; namespace DevHive.Services.Services { public class PostService { private readonly PostRepository _postRepository; + private readonly UserRepository _userRepository; private readonly IMapper _postMapper; - public PostService(PostRepository postRepository, IMapper postMapper) + public PostService(PostRepository postRepository, UserRepository userRepository , IMapper postMapper) { this._postRepository = postRepository; + this._userRepository = userRepository; this._postMapper = postMapper; } @@ -94,5 +99,41 @@ namespace DevHive.Services.Services return result; } + + //Validate + public async Task<bool> ValidateJwtForComment(Guid commentId, string rawTokenData) + { + Comment comment = await this._postRepository.GetCommentByIdAsync(commentId); + User user = await this.GetUserForValidation(rawTokenData); + + if (comment.IssuerId != user.Id) + return false; + + return true; + } + + private async Task<User> GetUserForValidation(string rawTokenData) + { + var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); + + string jwtUserName = this.GetClaimTypeValues("unique_name", jwt.Claims)[0]; + //List<string> jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims); + + User user = await this._userRepository.GetByUsername(jwtUserName) + ?? throw new ArgumentException("User does not exist!"); + + return user; + } + + private List<string> GetClaimTypeValues(string type, IEnumerable<Claim> claims) + { + List<string> toReturn = new(); + + foreach(var claim in claims) + if (claim.Type == type) + toReturn.Add(claim.Value); + + return toReturn; + } } }
\ No newline at end of file |
