Exemplo n.º 1
0
        public async void ValidateAsync_ACT02Code_InvalidProductKey()
        {
            var logger = new LoggerFactory().CreateLogger <LicenseService>();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                     .UseSqlite(connection)
                                     .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    var service = new LicenseService(context, logger);
                    var request = new LicenseRegisterRequest
                    {
                        LicenseUuid = Guid.NewGuid()
                    };

                    var result = await service.ValidateAsync(request);

                    Assert.Equal("ACT.02", result.Code);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 2
0
        private Task <string> CreateLicenseAsync(LicenseRegisterRequest request, LicenseRegistration registration, LicenseProduct product, Guid activationId)
        {
            var task = Task.Run(() =>
            {
                try
                {
                    var license = License.New()
                                  .WithUniqueIdentifier(registration.LicenseRegistrationId)
                                  .WithActivationId(activationId)
                                  .As(registration.LicenseType)
                                  .ExpiresAt(registration.ExpireUtc == null ? DateTime.MaxValue : registration.ExpireUtc.Value)
                                  .WithMaximumUtilization(registration.Quantity)
                                  .LicensedTo(registration.LicenseName, registration.LicenseEmail, (c) => c.Company = registration.LicenseName)
                                  .WithAdditionalAttributes(request.Attributes != null ? request.Attributes : new Dictionary <string, string>())
                                  .CreateAndSign(product.SignKeyName);

                    return(license.ToString());
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, ex.Message);

                    throw;
                }
            });

            return(task);
        }
Exemplo n.º 3
0
        public async void CreateAsync_NotValid()
        {
            var logger = new LoggerFactory().CreateLogger <LicenseService>();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                     .UseSqlite(connection)
                                     .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    context.Database.EnsureCreated();
                    var service = new LicenseService(context, logger);

                    var request = new LicenseRegisterRequest();

                    var result = await service.CreateAsync(request, "test-user");

                    Assert.Equal("ACT.01", result.Failure.Code);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 4
0
        public async Task <LicenseRegisterResult> CreateAsync(LicenseRegisterRequest request, string userName)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }

            try
            {
                _logger.LogDebug(JsonSerializer.Serialize(request));

                var failure = await ValidateAsync(request);

                if (failure != null)
                {
                    return(new LicenseRegisterResult
                    {
                        Failure = (GeneralValidationFailure)failure
                    });
                }

                string attributesJson     = null;
                string attributesChecksum = null;

                if (request.Attributes != null && request.Attributes.Any())
                {
                    attributesJson     = JsonSerializer.Serialize(request.Attributes);
                    attributesChecksum = Utils.GetSha256HashFromString(attributesJson);
                }

                var activationId  = Guid.NewGuid();
                var product       = _context.Products.Single(x => x.LicenseProductId == request.ProductUuid);
                var registration  = _context.Registrations.Single(x => x.LicenseRegistrationId == request.LicenseUuid);
                var licenseString = await CreateLicenseAsync(request, registration, product, activationId);

                await CreateLicenseRecordAsync(registration, licenseString, attributesJson, attributesChecksum, userName, activationId);

                var result = new LicenseRegisterResult();
                result.License = licenseString;

                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);

                return(new LicenseRegisterResult
                {
                    Failure = (GeneralValidationFailure)FailureStrings.Get(FailureStrings.ACT06Code)
                });
            }
        }
Exemplo n.º 5
0
        public async void IsActiveAsync()
        {
            var logger = Substitute.For <ILogger <LicenseService> >();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                License license        = null;
                var     contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                         .UseSqlite(connection)
                                         .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    context.Database.EnsureCreated();
                    var service = new LicenseService(context, logger);

                    var product = CreateProduct();
                    context.Add(product);
                    context.SaveChanges();

                    var registration = CreateRegistration(product);
                    registration.Quantity = 1;
                    context.Add(registration);
                    context.SaveChanges();

                    var request = new LicenseRegisterRequest
                    {
                        LicenseUuid = registration.LicenseRegistrationId,
                        ProductUuid = product.LicenseProductId
                    };

                    var createdResult = await service.CreateAsync(request, "test-user");

                    license = License.Load(createdResult.License);
                }

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    var service = new LicenseService(context, logger);
                    var active  = await service.IsActiveAsync(license.ActivationUuid);

                    Assert.True(active);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Post([FromBody] LicenseRegisterRequest request)
        {
            if (request == null)
            {
                return(BadRequest());
            }

            var result = await _licenseService.CreateAsync(request, string.IsNullOrWhiteSpace(User.Identity.Name)?Environment.UserName : User.Identity.Name);

            return(Ok(result));
        }
Exemplo n.º 7
0
        public async void ValidateAsync_ACT05Code_OverusedLicense()
        {
            var logger = new LoggerFactory().CreateLogger <LicenseService>();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                     .UseSqlite(connection)
                                     .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    context.Database.EnsureCreated();
                    var service = new LicenseService(context, logger);

                    var product = CreateProduct();
                    context.Add(product);
                    context.SaveChanges();

                    var registration = CreateRegistration(product);
                    registration.Quantity = 2;
                    context.Add(registration);
                    context.SaveChanges();

                    var licenseA = CreateLicense(registration);
                    var licenseB = CreateLicense(registration);
                    context.Add(licenseA);
                    context.Add(licenseB);
                    context.SaveChanges();

                    var request = new LicenseRegisterRequest
                    {
                        LicenseUuid = registration.LicenseRegistrationId,
                        ProductUuid = registration.ProductId
                    };

                    var result = await service.ValidateAsync(request);

                    Assert.Equal("ACT.05", result.Code);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 8
0
        public async void CreateAsync_Throws_ACT06Code()
        {
            var logger = Substitute.For <ILogger <LicenseService> >();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                     .UseSqlite(connection)
                                     .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    context.Database.EnsureCreated();
                    var service = new LicenseService(context, logger);

                    var product = CreateProduct();
                    product.SignKeyName = ""; // Force to throw
                    context.Add(product);
                    context.SaveChanges();

                    var registration = CreateRegistration(product);
                    registration.Quantity = 1;
                    context.Add(registration);
                    context.SaveChanges();

                    var request = new LicenseRegisterRequest
                    {
                        LicenseUuid = registration.LicenseRegistrationId,
                        ProductUuid = product.LicenseProductId
                    };

                    var result = await service.CreateAsync(request, "test-user");

                    Assert.Equal("ACT.06", result.Failure.Code);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 9
0
        public Task <IValidationFailure> ValidateAsync(LicenseRegisterRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.LicenseUuid == Guid.Empty)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT01Code)));
            }
            if (request.ProductUuid == Guid.Empty)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT02Code)));
            }

            var registration = _context.Registrations.SingleOrDefault(x => x.LicenseRegistrationId == request.LicenseUuid);

            if (registration == null)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT01Code)));
            }

            if (registration.ProductId != request.ProductUuid)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT02Code)));
            }

            if (registration.IsActive == false)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT03Code)));
            }

            if (registration.ExpireUtc != null && registration.ExpireUtc <= DateTime.UtcNow)
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT04Code)));
            }

            if (registration.Quantity > 1 && (LicenseGetUsage(request.LicenseUuid) >= registration.Quantity))
            {
                return(Task.FromResult(FailureStrings.Get(FailureStrings.ACT05Code)));
            }

            return(Task.FromResult <IValidationFailure>(null));
        }
Exemplo n.º 10
0
        public async void CreateAsync()
        {
            var logger = Substitute.For <ILogger <LicenseService> >();

            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var contextOptions = new DbContextOptionsBuilder <EfDbContext>()
                                     .UseSqlite(connection)
                                     .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(contextOptions))
                {
                    context.Database.EnsureCreated();
                    var service = new LicenseService(context, logger);

                    var product = CreateProduct();
                    context.Add(product);
                    context.SaveChanges();

                    var expireDate   = DateTime.UtcNow.AddDays(1);
                    var registration = CreateRegistration(product);
                    registration.Quantity  = 2;
                    registration.ExpireUtc = expireDate;
                    context.Add(registration);
                    context.SaveChanges();

                    var request = new LicenseRegisterRequest
                    {
                        LicenseUuid = registration.LicenseRegistrationId,
                        ProductUuid = registration.ProductId,
                        Attributes  = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    };

                    request.Attributes.Add("AppId", "app-id-0001");

                    var result = await service.CreateAsync(request, "test-user");

                    var lic           = context.Licenses.ToArray();
                    var licenseRecord = await context.Licenses.SingleAsync(x => x.LicenseId == registration.LicenseRegistrationId);

                    Assert.Null(result.Failure);
                    Assert.NotNull(result.License);
                    Assert.NotNull(licenseRecord);
                    Assert.False(licenseRecord.LicenseActivationId == Guid.Empty);
                    Assert.Equal(registration.LicenseRegistrationId, licenseRecord.LicenseId);
                    Assert.Equal(registration.ProductId, licenseRecord.ProductId);
                    Assert.Equal(registration.CompanyId, licenseRecord.CompanyId);
                    Assert.NotNull(licenseRecord.LicenseString);
                    Assert.NotNull(licenseRecord.LicenseAttributes);
                    Assert.NotNull(licenseRecord.LicenseChecksum);
                    Assert.NotNull(licenseRecord.AttributesChecksum);
                    Assert.Equal(Utils.ChecksumType, licenseRecord.ChecksumType);
                    Assert.Equal(DateTime.UtcNow.ToString("yyyyMMdd"), licenseRecord.CreatedDateTimeUtc.ToString("yyyyMMdd"));
                    Assert.NotNull(licenseRecord.CreatedByUser);

                    var license = License.Load(result.License);

                    var failure = FailureStrings.Get(FailureStrings.VAL04Code);

                    var failures = license.Validate()
                                   .ExpirationDate()
                                   .When(lic => lic.Type == LicenseType.Standard)
                                   .And()
                                   .Signature()
                                   .And()
                                   .AssertThat(x => string.Equals(request.Attributes["AppId"], x.AdditionalAttributes.Get("AppId"), StringComparison.OrdinalIgnoreCase), failure)
                                   .AssertValidLicense().ToList();

                    // Valid
                    Assert.False(failures.Any());

                    // License
                    Assert.Equal(licenseRecord.LicenseActivationId, license.ActivationUuid);
                    Assert.Equal(request.LicenseUuid, license.Id);
                    Assert.Equal(registration.LicenseType, license.Type);
                    Assert.Equal(expireDate.ToString("yyyyMMdd"), license.ExpirationUtc.ToString("yyyyMMdd"));
                    Assert.Equal(2, license.Quantity);
                    Assert.Equal(registration.LicenseName, license.Customer.Name);
                    Assert.Equal(registration.LicenseEmail, license.Customer.Email);
                    Assert.Equal(registration.LicenseName, license.Customer.Company);
                    Assert.Equal(request.Attributes["AppId"], license.AdditionalAttributes.Get("AppId"));
                }
            }
            finally
            {
                connection.Close();
            }
        }