Esempio n. 1
0
        public virtual async Task <GResult> CreateAsync(TEntity entity)
        {
            var errors = new List <GError>();

            foreach (var v in _validators)
            {
                var result = await v.ValidateAsync(entity);

                errors.AddRange(result);
            }

            if (errors.Count > 0)
            {
                return(GResult.Failed(errors.ToArray()));
            }
            await _repository.AddAsync(entity);

            try
            {
                await _unitOfWork.SaveChangesAsync();

                DomainEvents.Dispatch(new EntityCreatedEvent <TEntity>(entity));
                return(GResult.Success);
            }
            catch
            {
                return(GResult.Failed(ErrorDescriber.DefaultError()));
            }
        }
Esempio n. 2
0
        public virtual async Task <GResult <IEnumerable <TEntity> > > ReadAsync(MultiResultSpec <TEntity> spec)
        {
            var result = await _repository.GetAsync(spec);

            if (result != null || result?.Count > 0)
            {
                return(GResult <IEnumerable <TEntity> > .Success(result));
            }
            else
            {
                return(GResult <IEnumerable <TEntity> > .Failed(ErrorDescriber.NotFound()));
            }
        }
Esempio n. 3
0
        public virtual async Task <GResult <TEntity> > ReadAsync(SingleResultSpec <TEntity> spec)
        {
            var result = await _repository.GetAsync(spec);

            if (result != null)
            {
                return(GResult <TEntity> .Success(result));
            }
            else
            {
                return(GResult <TEntity> .Failed(ErrorDescriber.NotFound()));
            }
        }
Esempio n. 4
0
        public virtual async Task <GResult> DeleteAsync(TEntity entity)
        {
            await _repository.DeleteAsync(entity);

            try
            {
                await _unitOfWork.SaveChangesAsync();

                DomainEvents.Dispatch(new EntityDeletedEvent <TEntity>(entity));
                return(GResult.Success);
            }
            catch
            {
                return(GResult.Failed(ErrorDescriber.DefaultError()));
            }
        }
        public async void CreateDublicateEmailNotAllowed()
        {
            // Arrange
            var user1 = new User {
                Name = "user1", Email = "*****@*****.**"
            };
            var user2 = new User {
                Name = "user2", Email = "*****@*****.**"
            };

            user1.PasswordHash = _userService.PasswordHasher.Hash("user1_password");
            user2.PasswordHash = _userService.PasswordHasher.Hash("user2_password");

            // Act
            var result1 = await _userService.CreateAsync(user1);

            var result2 = await _userService.CreateAsync(user2);

            // Assert
            Assert.Equal(GResult.Failed(_errorDescriber.DuplicateEmail(user2.Email)), result2);
        }
        public async Task <GResult <TokenModel> > RefreshTokenAsync(string expiredToken, string refreshToken)
        {
            ClaimsPrincipal principal = null;
            var             errors    = new List <GError>();

            // Validate Jwt Token
            try
            {
                var tokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jsonWebTokenOptions.Key)),
                    ValidIssuer              = _jsonWebTokenOptions.Issuer,
                    ValidAudience            = _jsonWebTokenOptions.Audience,
                    ValidateAudience         = !string.IsNullOrWhiteSpace(_jsonWebTokenOptions.Audience),
                    ValidateIssuer           = !string.IsNullOrWhiteSpace(_jsonWebTokenOptions.Issuer),
                    ValidateIssuerSigningKey = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidateLifetime = false
                };
                var tokenHandler = new JwtSecurityTokenHandler();
                principal = tokenHandler.ValidateToken(expiredToken, tokenValidationParameters, out var securityToken);

                if (!IsValidSecurityToken(securityToken))
                {
                    throw new SecurityTokenException("Invalid security token");
                }

                var expiryDateUnix    = long.Parse(principal.FindFirst(JwtClaimNames.Exp).Value);
                var expiryDateTimeUtc = DateTime.UnixEpoch.AddSeconds(expiryDateUnix);

                if (expiryDateTimeUtc > DateTime.UtcNow)
                {
                    return(GResult <TokenModel> .Success(new TokenModel { AccessToken = expiredToken, RefreshToken = refreshToken }));
                }
            }
            catch (SecurityTokenException ex)
            {
                errors.Add(ErrorDescriber.InvalidToken(ex.Message));
            }

            if (errors.Count > 0)
            {
                return(GResult <TokenModel> .Failed(errors.ToArray()));
            }
            // Validate Refresh Token
            else
            {
                var userId = Guid.Parse(principal?.FindFirst(ClaimTypes.NameIdentifier).Value);
                var jwtId  = principal?.FindFirstValue(JwtClaimNames.Jti);
                // Check if refresh token already registered for this user
                var readUserLoginResult = await base.ReadAsync(new FindUserLogin <UserLogin>(userId, jwtId, refreshToken));

                if (readUserLoginResult.Succeeded)
                {
                    var userLogin = readUserLoginResult.Outcome;
                    if (DateTime.UtcNow > userLogin.ExpiryDate)
                    {
                        await base.DeleteAsync(userLogin);

                        return(GResult <TokenModel> .Failed(ErrorDescriber.InvalidToken("")));
                    }
                    else
                    {
                        var readUserResult = await UserService.ReadAsync(new FindByIdSpec <User>(userId));

                        if (readUserResult.Succeeded)
                        {
                            var user   = readUserResult.Outcome;
                            var claims = await _userClaimsFactory.CreateAsync(user);

                            var newJwtId = claims.FirstOrDefault(c => c.Type == JwtClaimNames.Jti).Value;
                            var newToken = _jsonWebTokenCoder.Encode(claims);
                            userLogin.JwtId = newJwtId;
                            // Check if refresh token required update
                            if (DateTime.UtcNow > userLogin.RequiredUpdateDate)
                            {
                                userLogin.RefreshToken       = _refreshTokenGenerator.Generate(user);
                                userLogin.ExpiryDate         = DateTime.UtcNow + _jsonWebTokenOptions.RefreshToken.Expires;
                                userLogin.RequiredUpdateDate = DateTime.UtcNow + _jsonWebTokenOptions.RefreshToken.UpdateRequired;
                            }

                            var updateUserLoginResult = await base.UpdateAsync(userLogin);

                            if (!updateUserLoginResult.Succeeded)
                            {
                                return(GResult <TokenModel> .Failed(updateUserLoginResult.Errors.ToArray()));
                            }
                            return(GResult <TokenModel> .Success(new TokenModel { AccessToken = newToken, RefreshToken = userLogin.RefreshToken }));
                        }
                        else
                        {
                            return(GResult <TokenModel> .Failed(ErrorDescriber.InvalidCredentials()));
                        }
                    }
                }
                else
                {
                    return(GResult <TokenModel> .Failed(ErrorDescriber.InvalidCredentials()));
                }
            }
        }