Exemplo n.º 1
0
        public async Task <Domain.DataTransferObject.Token> RefreshAsync(string nameId, string tokenId, int expiresMilliseconds,
                                                                         IDictionary <string, string> parameters = default)
        {
            if (string.IsNullOrEmpty(nameId) || string.IsNullOrEmpty(tokenId))
            {
                return(new Domain.DataTransferObject.Token
                {
                    Status = TokenStatus.BadRequest
                });
            }

            var tokenEntity = await _tokenRepository.GetAsync(nameId, tokenId);

            if (tokenEntity.Status != TokenStatus.Created)
            {
                return(new Domain.DataTransferObject.Token
                {
                    Status = tokenEntity.Status
                });
            }

            var token = await _tokenService.RefreshAsync(nameId, tokenEntity.AccessToken, expiresMilliseconds);

            await _tokenRepository.AddAsync(token.ToEntity());

            _ = _tokenRepository.DeleteAsync(nameId, tokenId);

            return(token);
        }
        public async Task GetAndRemoveByProjectIdOrDefaultProjectIdAsync()
        {
            await _repository.AddAsync(new List <Token> {
                new Token {
                    OrganizationId = TestConstants.OrganizationId, CreatedUtc = SystemClock.UtcNow, UpdatedUtc = SystemClock.UtcNow, Id = StringExtensions.GetNewToken()
                },
                new Token {
                    OrganizationId = TestConstants.OrganizationId, ProjectId = TestConstants.ProjectId, CreatedUtc = SystemClock.UtcNow, UpdatedUtc = SystemClock.UtcNow, Id = StringExtensions.GetNewToken()
                },
                new Token {
                    OrganizationId = TestConstants.OrganizationId, ProjectId = TestConstants.ProjectIdWithNoRoles, CreatedUtc = SystemClock.UtcNow, UpdatedUtc = SystemClock.UtcNow, Id = StringExtensions.GetNewToken()
                },
                new Token {
                    OrganizationId = TestConstants.OrganizationId, DefaultProjectId = TestConstants.ProjectId, CreatedUtc = SystemClock.UtcNow, UpdatedUtc = SystemClock.UtcNow, Id = StringExtensions.GetNewToken()
                },
                new Token {
                    OrganizationId = TestConstants.OrganizationId, DefaultProjectId = TestConstants.ProjectIdWithNoRoles, CreatedUtc = SystemClock.UtcNow, UpdatedUtc = SystemClock.UtcNow, Id = StringExtensions.GetNewToken()
                },
                new Token {
                    DefaultProjectId = TestConstants.ProjectIdWithNoRoles, UserId = TestConstants.UserId, CreatedUtc = SystemClock.UtcNow, UpdatedUtc = SystemClock.UtcNow, Id = StringExtensions.GetNewToken()
                }
            }, o => o.ImmediateConsistency());

            Assert.Equal(5, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(2, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(3, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);

            await _repository.RemoveAllByProjectIdAsync(TestConstants.OrganizationId, TestConstants.ProjectId);

            await _configuration.Client.RefreshAsync(Indices.All);

            Assert.Equal(4, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(1, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(3, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);

            await _repository.RemoveAllByProjectIdAsync(TestConstants.OrganizationId, TestConstants.ProjectIdWithNoRoles);

            await _configuration.Client.RefreshAsync(Indices.All);

            Assert.Equal(3, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(1, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(2, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);

            await _repository.RemoveAllByOrganizationIdAsync(TestConstants.OrganizationId);

            await _configuration.Client.RefreshAsync(Indices.All);

            Assert.Equal(0, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(0, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(1, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);
        }
Exemplo n.º 3
0
        public async Task CreateOrganizationAndProjectAsync(User user)
        {
            if (await _tokenRepository.ExistsAsync(TEST_API_KEY).AnyContext())
            {
                return;
            }

            var organization = new Organization {
                Id = TEST_ORG_ID, Name = "Acme"
            };

            _billingManager.ApplyBillingPlan(organization, _billingPlans.UnlimitedPlan, user);
            organization = await _organizationRepository.AddAsync(organization, o => o.ImmediateConsistency().Cache()).AnyContext();

            var project = new Project {
                Id                       = TEST_PROJECT_ID,
                Name                     = "Disintegrating Pistol",
                OrganizationId           = organization.Id,
                NextSummaryEndOfDayTicks = SystemClock.UtcNow.Date.AddDays(1).AddHours(1).Ticks
            };

            project.Configuration.Settings.Add("IncludeConditionalData", "true");
            project.AddDefaultNotificationSettings(user.Id);
            project = await _projectRepository.AddAsync(project, o => o.ImmediateConsistency().Cache()).AnyContext();

            await _tokenRepository.AddAsync(new List <Token>()
            {
                new Token {
                    Id             = TEST_API_KEY,
                    OrganizationId = organization.Id,
                    ProjectId      = project.Id,
                    CreatedUtc     = SystemClock.UtcNow,
                    UpdatedUtc     = SystemClock.UtcNow,
                    Type           = TokenType.Access
                },
                new Token {
                    Id         = TEST_USER_API_KEY,
                    UserId     = user.Id,
                    CreatedUtc = SystemClock.UtcNow,
                    UpdatedUtc = SystemClock.UtcNow,
                    Type       = TokenType.Access
                }
            }, o => o.ImmediateConsistency().Cache()).AnyContext();

            user.OrganizationIds.Add(organization.Id);
            await _userRepository.SaveAsync(user, o => o.ImmediateConsistency().Cache()).AnyContext();

            _logger.LogDebug("Created Organization {OrganizationName} and Project {ProjectName}", organization.Name, project.Name);
        }
        public async Task CreateAndGetEntity_Test()
        {
            // Arrange
            var tokenDescriptor = GenerateTokenDescriptor();
            var createResult    = await _tokenRepository.AddAsync(tokenDescriptor);

            createResult.Should().BeTrue();

            // Act
            var result = await _tokenRepository.GetAsync(tokenDescriptor.Issuer, tokenDescriptor.Audience);

            // Assert
            result.Should().BeEquivalentTo(tokenDescriptor, x => x.Excluding(y => y.ExpirationDate));
            result.ExpirationDate.Should().BeCloseTo(tokenDescriptor.ExpirationDate, TimeSpan.FromMilliseconds(0.001));
        }
Exemplo n.º 5
0
        public async Task GenerateTokenAsync(GetTokenCommand tokenCommand)
        {
            var now        = DateTime.UtcNow;
            var userClaims = GetNamesUserRoles(await _identityRepository.GetUserRoleAsync(tokenCommand.UserId));
            var userRoles  = userClaims as string[] ?? userClaims?.ToArray();
            var claims     = PrepareClaims(tokenCommand.UserId, now, userRoles);
            var expires    = GetExperienceTime(now);

            var signingCredentials = new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_securitySettings.Key)),
                SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: _securitySettings.Issuer,
                audience: _securitySettings.Audience,
                claims: claims,
                notBefore: now,
                expires: expires,
                signingCredentials: signingCredentials
                );

            var token        = new JwtSecurityTokenHandler().WriteToken(jwt);
            var refreshToken = await GenerateRefreshTokenAsync(tokenCommand.UserId);

            var objToken = ParsingTokenToDto(token, refreshToken);
            // var jsonToken = ParsingTokenToJson(objToken);

            var tokenDatabaseModel = _mapper.Map <Token>(objToken);

            await _tokenRepository.AddAsync(tokenDatabaseModel, tokenCommand.UserId);

            _cache.Add(GenerateCacheObject(tokenCommand.IdRequest, objToken));
        }
        //private ByteArrayContent CompressString(string data) {
        //    byte[] bytes = Encoding.UTF8.GetBytes(data);
        //    using (var stream = new MemoryStream()) {
        //        using (var zipper = new GZipStream(stream, CompressionMode.Compress, true))
        //            zipper.Write(bytes, 0, bytes.Length);

        //        var content = new ByteArrayContent(stream.ToArray());
        //        content.Headers.ContentType = new MediaTypeHeaderValue("text/plain") {
        //            CharSet = "utf-8"
        //        };
        //        content.Headers.ContentEncoding.Add("gzip");
        //        return content;
        //    }
        //}

        //private ByteArrayContent JsonCompress(object data) {
        //    byte[] bytes = Encoding.UTF8.GetBytes(_serializer.SerializeToString(data));
        //    using (var stream = new MemoryStream()) {
        //        using (var zipper = new GZipStream(stream, CompressionMode.Compress, true))
        //            zipper.Write(bytes, 0, bytes.Length);

        //        var content = new ByteArrayContent(stream.ToArray());
        //        content.Headers.ContentType = new MediaTypeHeaderValue("application/json") {
        //            CharSet = "utf-8"
        //        };
        //        content.Headers.ContentEncoding.Add("gzip");
        //        return content;
        //    }
        //}

        private Task CreateOrganizationAndProjectsAsync()
        {
            return(Task.WhenAll(
                       _organizationRepository.AddAsync(OrganizationData.GenerateSampleOrganizations(), o => o.ImmediateConsistency()),
                       _projectRepository.AddAsync(ProjectData.GenerateSampleProjects(), o => o.ImmediateConsistency()),
                       _tokenRepository.AddAsync(TokenData.GenerateSampleApiKeyToken(), o => o.ImmediateConsistency())
                       ));
        }
Exemplo n.º 7
0
        public async Task CreateOrganizationAndProjectAsync(string userId)
        {
            if (await _tokenRepository.GetByIdAsync(TEST_API_KEY).AnyContext() != null)
            {
                return;
            }

            User user = await _userRepository.GetByIdAsync(userId, true).AnyContext();

            var organization = new Organization {
                Id = TEST_ORG_ID, Name = "Acme"
            };

            BillingManager.ApplyBillingPlan(organization, BillingManager.UnlimitedPlan, user);
            organization = await _organizationRepository.AddAsync(organization, true).AnyContext();

            var project = new Project {
                Id = TEST_PROJECT_ID, Name = "Disintegrating Pistol", OrganizationId = organization.Id
            };

            project.NextSummaryEndOfDayTicks = SystemClock.UtcNow.Date.AddDays(1).AddHours(1).Ticks;
            project.Configuration.Settings.Add("IncludeConditionalData", "true");
            project.AddDefaultOwnerNotificationSettings(userId);
            project = await _projectRepository.AddAsync(project, true).AnyContext();

            await _tokenRepository.AddAsync(new Token {
                Id             = TEST_API_KEY,
                OrganizationId = organization.Id,
                ProjectId      = project.Id,
                CreatedUtc     = SystemClock.UtcNow,
                ModifiedUtc    = SystemClock.UtcNow,
                Type           = TokenType.Access
            }).AnyContext();

            await _tokenRepository.AddAsync(new Token {
                Id          = TEST_USER_API_KEY,
                UserId      = user.Id,
                CreatedUtc  = SystemClock.UtcNow,
                ModifiedUtc = SystemClock.UtcNow,
                Type        = TokenType.Access
            }).AnyContext();

            user.OrganizationIds.Add(organization.Id);
            await _userRepository.SaveAsync(user, true).AnyContext();
        }
Exemplo n.º 8
0
        public async Task AddUserTokenAsync(UserToken userToken)
        {
            if (!_configuration.Value.AllowMultipleLoginsFromTheSameUser)
            {
                await InvalidateUserTokensAsync(userToken.UserId);
            }
            await DeleteTokensWithSameRefreshTokenSourceAsync(userToken.RefreshTokenIdHashSource);

            await _tokenRepository.AddAsync(userToken);
        }
        public async Task AddTokenAsync(TokenDescriptor tokenDescriptor, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(tokenDescriptor.PrivateKey))
            {
                tokenDescriptor.PrivateKey = _passwordProvider.GetNextStringPassword(ValidationConstants.MaxPasswordLength);
            }

            _tokenDescriptorModelValidator.EnsureValidation(tokenDescriptor);

            await _tokenRepository.AddAsync(tokenDescriptor, cancellationToken);

            _notifier.Notify(new TokenAddedNotifyMessage(tokenDescriptor));
        }
Exemplo n.º 10
0
        public async Task CreateTestOrganizationAsync(string userId, string organizationId, string organizationName, string apiKey, string userApiKey)
        {
            if (await _tokenRepository.GetByIdAsync(apiKey).AnyContext() != null)
            {
                return;
            }

            var user = await _userRepository.GetByIdAsync(userId, true).AnyContext();

            var organization = new Organization {
                Id = organizationId, Name = organizationName
            };

            organization = await _organizationRepository.AddAsync(organization).AnyContext();

            await _tokenRepository.AddAsync(new Token
            {
                Id             = apiKey,
                OrganizationId = organization.Id,
                CreatedUtc     = DateTime.UtcNow,
                UpdatedUtc     = DateTime.UtcNow,
                Type           = TokenType.Access
            }).AnyContext();

            await _tokenRepository.AddAsync(new Token
            {
                Id             = userApiKey,
                UserId         = user.Id,
                OrganizationId = organization.Id,
                CreatedUtc     = DateTime.UtcNow,
                UpdatedUtc     = DateTime.UtcNow,
                Type           = TokenType.Access
            }).AnyContext();

            user.AddAdminMembership(organization.Id);
            await _userRepository.SaveAsync(user, true).AnyContext();
        }
Exemplo n.º 11
0
        private async Task<string> GetOrCreateAccessTokenAsync(User user) {
            var userTokens = await _tokenRepository.GetByTypeAndUserIdAsync(TokenType.Access, user.Id);
            var validAccessToken = userTokens.Documents.FirstOrDefault(t => (!t.ExpiresUtc.HasValue || t.ExpiresUtc > SystemClock.UtcNow));
            if (validAccessToken != null)
                return validAccessToken.Id;

            var token = await _tokenRepository.AddAsync(new Token {
                Id = Core.Extensions.StringExtensions.GetNewToken(),
                UserId = user.Id,
                CreatedUtc = SystemClock.UtcNow,
                UpdatedUtc = SystemClock.UtcNow,
                ExpiresUtc = SystemClock.UtcNow.AddMonths(3),
                CreatedBy = user.Id,
                Type = TokenType.Access
            }, o => o.ImmediateConsistency(true).Cache());

            return token.Id;
        }
Exemplo n.º 12
0
        private async Task <string> GetTokenAsync(User user)
        {
            var userTokens = await _tokenRepository.GetByUserIdAsync(user.Id);

            var validAccessToken = userTokens.Documents.FirstOrDefault(t => (!t.ExpiresUtc.HasValue || t.ExpiresUtc > SystemClock.UtcNow) && t.Type == TokenType.Access);

            if (validAccessToken != null)
            {
                return(validAccessToken.Id);
            }

            var token = await _tokenRepository.AddAsync(new Token {
                Id         = Core.Extensions.StringExtensions.GetNewToken(),
                UserId     = user.Id,
                CreatedUtc = SystemClock.UtcNow,
                UpdatedUtc = SystemClock.UtcNow,
                CreatedBy  = user.Id,
                Type       = TokenType.Access
            });

            return(token.Id);
        }
Exemplo n.º 13
0
        public async Task GetAndRemoveByProjectIdOrDefaultProjectIdAsync()
        {
            await RemoveDataAsync();

            await _repository.AddAsync(new Token { OrganizationId = TestConstants.OrganizationId, CreatedUtc = DateTime.UtcNow, ModifiedUtc = DateTime.UtcNow, Id = StringExtensions.GetNewToken() });

            await _repository.AddAsync(new Token { OrganizationId = TestConstants.OrganizationId, ProjectId = TestConstants.ProjectId, CreatedUtc = DateTime.UtcNow, ModifiedUtc = DateTime.UtcNow, Id = StringExtensions.GetNewToken() });

            await _repository.AddAsync(new Token { OrganizationId = TestConstants.OrganizationId, ProjectId = TestConstants.ProjectIdWithNoRoles, CreatedUtc = DateTime.UtcNow, ModifiedUtc = DateTime.UtcNow, Id = StringExtensions.GetNewToken() });

            await _repository.AddAsync(new Token { OrganizationId = TestConstants.OrganizationId, DefaultProjectId = TestConstants.ProjectId, CreatedUtc = DateTime.UtcNow, ModifiedUtc = DateTime.UtcNow, Id = StringExtensions.GetNewToken() });

            await _repository.AddAsync(new Token { OrganizationId = TestConstants.OrganizationId, DefaultProjectId = TestConstants.ProjectIdWithNoRoles, CreatedUtc = DateTime.UtcNow, ModifiedUtc = DateTime.UtcNow, Id = StringExtensions.GetNewToken() });

            await _repository.AddAsync(new Token { DefaultProjectId = TestConstants.ProjectIdWithNoRoles, UserId = TestConstants.UserId, CreatedUtc = DateTime.UtcNow, ModifiedUtc = DateTime.UtcNow, Id = StringExtensions.GetNewToken() });

            await _client.RefreshAsync();

            Assert.Equal(5, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(2, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(3, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);

            await _repository.RemoveAllByProjectIdsAsync(new [] { TestConstants.ProjectId });

            await _client.RefreshAsync();

            Assert.Equal(4, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(1, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(3, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);

            await _repository.RemoveAllByProjectIdsAsync(new[] { TestConstants.ProjectIdWithNoRoles });

            await _client.RefreshAsync();

            Assert.Equal(3, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(1, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(2, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);

            await _repository.RemoveAllByOrganizationIdsAsync(new[] { TestConstants.OrganizationId });

            await _client.RefreshAsync();

            Assert.Equal(0, (await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId)).Total);
            Assert.Equal(0, (await _repository.GetByProjectIdAsync(TestConstants.ProjectId)).Total);
            Assert.Equal(1, (await _repository.GetByProjectIdAsync(TestConstants.ProjectIdWithNoRoles)).Total);
        }
        private async Task <AuthenticationResult> GenerateAuthenticationResultForUserAsync(User user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            var claims       = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim("id", user.Id)
            };
            var userClaims = await _userManager.GetClaimsAsync(user);

            claims.AddRange(userClaims);
            var userRoles = await _userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                var role = await _roleManager.FindByNameAsync(userRole);

                if (role == null)
                {
                    continue;
                }
                var roleClaims = await _roleManager.GetClaimsAsync(role);

                foreach (var roleClaim in roleClaims)
                {
                    if (claims.Contains(roleClaim))
                    {
                        continue;
                    }

                    claims.Add(roleClaim);
                }
            }
            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject            = new System.Security.Claims.ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.Add(_jwtSettings.Tokenlifetime),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token        = tokenHandler.CreateToken(tokenDescriptor);
            var refreshToken = new RefreshToken()
            {
                //Token = Guid.NewGuid().ToString(), //TODO:  this is shit to change
                JwtId        = token.Id,
                UserId       = user.Id,
                CreationDate = DateTime.UtcNow,
                ExpiryDate   = DateTime.UtcNow.AddMonths(_jwtSettings.RefreshTokenLifeMonths)
            };
            await _tokenRepository.AddAsync(refreshToken);

            return(new AuthenticationResult()
            {
                Success = true,
                Token = tokenHandler.WriteToken(token),
                RefreshToken = refreshToken.Token
            });
        }