Esempio n. 1
0
        /// <summary>
        /// Updates device authorization, searching by user code.
        /// </summary>
        /// <param name="userCode">The user code.</param>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public virtual async Task UpdateByUserCodeAsync(string userCode, DeviceCode data)
        {
            DeviceFlowCodes existingUserCode = await Context.GetEntityBlobAsync <DeviceFlowCodes>(userCode, Context.UserCodeBlobContainer);

            if (existingUserCode == null)
            {
                Logger.LogError("{userCode} not found in blob storage", userCode);
                throw new InvalidOperationException("Could not update device code");
            }

            string          deviceCode         = existingUserCode.DeviceCode;
            DeviceFlowCodes existingDeviceCode = await Context.GetEntityBlobAsync <DeviceFlowCodes>(deviceCode, Context.DeviceCodeBlobContainer);

            if (existingDeviceCode == null)
            {
                Logger.LogError("{deviceCode} not found in blob storage", deviceCode);
                throw new InvalidOperationException("Could not update device code");
            }

            var entity = ToEntity(data, deviceCode, userCode);

            Logger.LogDebug("{userCode} found in blob storage", userCode);

            existingUserCode.SubjectId = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value;
            existingUserCode.Data      = entity.Data;

            string entityJson = JsonConvert.SerializeObject(existingUserCode);
            await Task.WhenAll(Context.SaveBlobWithHashedKeyAsync(deviceCode, entityJson, Context.DeviceCodeBlobContainer),
                               Context.SaveBlobWithHashedKeyAsync(userCode, entityJson, Context.UserCodeBlobContainer));
        }
Esempio n. 2
0
        public async Task OnPostAsync()
        {
            // Arrange
            var deviceFlowCode = new DeviceFlowCodes {
                UserCode = $"{Guid.NewGuid()}"
            };
            var deviceFlowCodes = new Mock <DbSet <DeviceFlowCodes> >();

            deviceFlowCodes.Setup(x => x.FindAsync(deviceFlowCode.UserCode)).ReturnsAsync(deviceFlowCode);
            var context = new Mock <IPersistedGrantDbContext>();

            context.Setup(x => x.DeviceFlowCodes).Returns(deviceFlowCodes.Object);
            var delete = new DeleteModel(context.Object)
            {
                DeviceFlowCode = deviceFlowCode
            };

            // Act
            var post = await delete.OnPostAsync().ConfigureAwait(false);

            // Assert
            deviceFlowCodes.Verify(x => x.FindAsync(deviceFlowCode.UserCode), Times.Once);
            deviceFlowCodes.Verify(x => x.Remove(deviceFlowCode), Times.Once);
            context.Verify(x => x.SaveChangesAsync(), Times.Once);
            var result = Assert.IsType <RedirectToPageResult>(post);

            Assert.Equal("./Index", result.PageName);
        }
Esempio n. 3
0
        public async Task OnPostAsync_InvalidUserCode()
        {
            // Arrange
            var deviceFlowCode = new DeviceFlowCodes {
                UserCode = $"{Guid.NewGuid()}"
            };
            var deviceFlowCodes = new Mock <DbSet <DeviceFlowCodes> >();

            deviceFlowCodes.Setup(x => x.FindAsync(deviceFlowCode.UserCode)).ReturnsAsync(deviceFlowCode);
            var context = new Mock <IPersistedGrantDbContext>();

            context.Setup(x => x.DeviceFlowCodes).Returns(deviceFlowCodes.Object);
            var delete = new DeleteModel(context.Object)
            {
                DeviceFlowCode = new DeviceFlowCodes {
                    UserCode = string.Empty
                }
            };

            // Act
            var post = await delete.OnPostAsync().ConfigureAwait(false);

            // Assert
            deviceFlowCodes.Verify(x => x.FindAsync(deviceFlowCode.UserCode), Times.Never);
            deviceFlowCodes.Verify(x => x.Remove(deviceFlowCode), Times.Never);
            context.Verify(x => x.SaveChangesAsync(), Times.Never);
            Assert.IsType <PageResult>(post);
        }
        public async Task Should_Not_Remove_Still_Valid_Device_Code(TestDatabase testDb)
        {
            var validDeviceCode = new DeviceFlowCodes
            {
                DeviceCode   = Guid.NewGuid().ToString(),
                ID           = "1234",
                ClientId     = "test-app",
                SubjectId    = "42",
                CreationTime = DateTime.UtcNow.AddDays(-4),
                Expiration   = DateTime.UtcNow.AddDays(3),
                Data         = "testdata"
            };

            using (var session = testDb.OpenSession())
            {
                await session.SaveAsync(validDeviceCode);

                await session.FlushAsync();
            }

            await CreateTokenCleanupServiceSut(testDb, TestOperationalStoreOptions).RemoveExpiredGrantsAsync();

            using (var session = testDb.OpenSession())
            {
                (await session.GetAsync <DeviceFlowCodes>(validDeviceCode.ID)).Should().NotBeNull();
            }

            await CleanupTestDataAsync(testDb);
        }
Esempio n. 5
0
        public async Task RemoveExpiredGrantsAsync_WhenExpiredDeviceGrantsExist_ExpectExpiredDeviceGrantsRemoved(DbContextOptions <PersistedGrantDbContext> options)
        {
            var expiredGrant = new DeviceFlowCodes
            {
                DeviceCode   = Guid.NewGuid().ToString(),
                UserCode     = Guid.NewGuid().ToString(),
                ClientId     = "app1",
                SubjectId    = "123",
                CreationTime = DateTime.UtcNow.AddDays(-4),
                Expiration   = DateTime.UtcNow.AddDays(-3),
                Data         = "{!}"
            };

            using (var context = new PersistedGrantDbContext(options, StoreOptions))
            {
                context.DeviceFlowCodes.Add(expiredGrant);
                context.SaveChanges();
            }

            await CreateSut(options).RemoveExpiredGrantsAsync();

            using (var context = new PersistedGrantDbContext(options, StoreOptions))
            {
                context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == expiredGrant.DeviceCode).Should().BeNull();
            }
        }
Esempio n. 6
0
        public static DeviceCode ToModel(this DeviceFlowCodes deviceFlowCode)
        {
            if (deviceFlowCode == null || string.IsNullOrWhiteSpace(deviceFlowCode.Data))
            {
                return(null);
            }

            return(_serializer.Deserialize <DeviceCode>(deviceFlowCode.Data));
        }
Esempio n. 7
0
        /// <summary>
        /// Finds device authorization by device code.
        /// </summary>
        /// <param name="deviceCode">The device code.</param>
        /// <returns></returns>
        public virtual async Task <DeviceCode> FindByDeviceCodeAsync(string deviceCode)
        {
            DeviceFlowCodes deviceFlowCodes = await Context.GetEntityBlobAsync <DeviceFlowCodes>(deviceCode, Context.DeviceCodeBlobContainer);

            DeviceCode model = ToModel(deviceFlowCodes?.Data);

            Logger.LogDebug("{deviceCode} found in blob storage: {deviceCodeFound}", deviceCode, model != null);

            return(model);
        }
        /// <summary>
        /// Finds device authorization by user code.
        /// </summary>
        /// <param name="userCode">The user code.</param>
        /// <returns></returns>
        public virtual async Task <DeviceCode> FindByUserCodeAsync(string userCode)
        {
            DeviceFlowCodes deviceFlowCodes = await Context.GetEntityBlobAsync <DeviceFlowCodes>(userCode, Context.UserCodeBlobContainer)
                                              .ConfigureAwait(false);

            DeviceCode model = ToModel(deviceFlowCodes?.Data);

            Logger.LogDebug("{userCode} found in blob storage: {userCodeFound}", userCode, model != null);

            return(model);
        }
        private static CacheItem CreateCacheItem(
            DeviceFlowCodes entity)
        {
            CacheItem item = new CacheItem(entity);

            item.Tags = GetTags(entity);

            if (entity.GetExpiration().HasValue)
            {
                TimeSpan span = entity.GetExpiration().Value - DateTime.UtcNow;
                item.Expiration = new Expiration(ExpirationType.Absolute, span);
            }

            return(item);
        }
Esempio n. 10
0
        public async Task <IActionResult> OnGetAsync([FromRoute] string userCode)
        {
            if (string.IsNullOrEmpty(userCode))
            {
                return(NotFound());
            }

            DeviceFlowCode = await _context.DeviceFlowCodes.FindAsync(userCode).ConfigureAwait(false);

            if (DeviceFlowCode == null)
            {
                return(NotFound());
            }

            return(Page());
        }
Esempio n. 11
0
        /// <summary>
        /// Removes the device authorization, searching by device code.
        /// </summary>
        /// <param name="deviceCode">The device code.</param>
        /// <returns></returns>
        public virtual async Task RemoveByDeviceCodeAsync(string deviceCode)
        {
            DeviceFlowCodes deviceFlowCodes = await Context.GetEntityBlobAsync <DeviceFlowCodes>(deviceCode, Context.DeviceCodeBlobContainer);

            if (deviceFlowCodes != null)
            {
                Logger.LogDebug("removing {deviceCode} device code from blob storage", deviceCode);

                await Task.WhenAll(Context.DeleteBlobAsync(deviceCode, Context.DeviceCodeBlobContainer),
                                   Context.DeleteBlobAsync(deviceFlowCodes.UserCode, Context.UserCodeBlobContainer));
            }
            else
            {
                Logger.LogDebug("no {deviceCode} device code found in blob storage", deviceCode);
            }
        }
Esempio n. 12
0
        public async Task RemoveExpiredGrantsAsync_WhenValidDeviceGrantsExist_ExpectValidDeviceGrantsInDb()
        {
            var validGrant = new DeviceFlowCodes
            {
                DeviceCode   = Guid.NewGuid().ToString(),
                UserCode     = "2468",
                ClientId     = "app1",
                SubjectId    = "123",
                CreationTime = DateTime.UtcNow.AddDays(-4),
                Expiration   = DateTime.UtcNow.AddDays(3),
                Data         = "{!}"
            };

            await _context.DeviceFlowCodes.AddAsync(validGrant);

            await CreateSut().RemoveExpiredGrantsAsync();

            (await _context.DeviceFlowCodes.WhereEqualTo("DeviceCode", validGrant.DeviceCode).GetSnapshotAsync()).Count.Should().Be(1);
        }
Esempio n. 13
0
        public async Task OnGetAsync()
        {
            // Arrange
            var deviceFlowCode = new DeviceFlowCodes {
                UserCode = $"{Guid.NewGuid()}"
            };
            var deviceFlowCodes = new Mock <DbSet <DeviceFlowCodes> >();

            deviceFlowCodes.Setup(x => x.FindAsync(deviceFlowCode.UserCode)).ReturnsAsync(deviceFlowCode);
            var context = new Mock <IPersistedGrantDbContext>();

            context.Setup(x => x.DeviceFlowCodes).Returns(deviceFlowCodes.Object);
            var index = new IndexModel(context.Object);

            // Act
            var get = await index.OnGetAsync(deviceFlowCode.UserCode).ConfigureAwait(false);

            // Assert
            deviceFlowCodes.Verify(x => x.FindAsync(deviceFlowCode.UserCode), Times.Once);
            Assert.Equal(deviceFlowCode, index.DeviceFlowCode);
            Assert.IsType <PageResult>(get);
        }
Esempio n. 14
0
        public async Task OnGetAsync_InvalidUserCode()
        {
            // Arrange
            var deviceFlowCode = new DeviceFlowCodes {
                UserCode = $"{Guid.NewGuid()}"
            };
            var deviceFlowCodes = new Mock <DbSet <DeviceFlowCodes> >();

            deviceFlowCodes.Setup(x => x.FindAsync(deviceFlowCode.UserCode)).ReturnsAsync(deviceFlowCode);
            var context = new Mock <IPersistedGrantDbContext>();

            context.Setup(x => x.DeviceFlowCodes).Returns(deviceFlowCodes.Object);
            var delete = new DeleteModel(context.Object);

            // Act
            var get = await delete.OnGetAsync(string.Empty).ConfigureAwait(false);

            // Assert
            deviceFlowCodes.Verify(x => x.FindAsync(deviceFlowCode.UserCode), Times.Never);
            Assert.Null(delete.DeviceFlowCode);
            Assert.IsType <NotFoundResult>(get);
        }
        public async Task UpdateByUserCodeAsync(string userCode, DeviceCode data)
        {
            DocumentSnapshot deviceFlowCodes =
                await GetDeviceFlow(nameof(DeviceFlowCodes.UserCode), userCode).ConfigureAwait(false);

            if (!deviceFlowCodes.Exists)
            {
                _logger.LogError("{userCode} not found in database", userCode);
                throw new InvalidOperationException("Could not update device code");
            }

            DeviceFlowCodes existing = deviceFlowCodes.ConvertTo <DeviceFlowCodes>();

            DeviceFlowCodes entity = ToEntity(data, existing.DeviceCode, userCode);

            _logger.LogDebug("{userCode} found in database", userCode);

            existing.SubjectId = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value;
            existing.Data      = entity.Data;

            await deviceFlowCodes.Reference.SetAsync(existing).ConfigureAwait(false);
        }
Esempio n. 16
0
        public async Task <DeviceFlowCodesDto> FindByDeviceCodeAsync(string deviceCode)
        {
            DeviceFlowCodes item = await DeviceFlowCodesRepository.FindByDeviceCodeAsync(deviceCode);

            return(ObjectMapper.Map <DeviceFlowCodes, DeviceFlowCodesDto>(item));
        }
 private static string GetKey(DeviceFlowCodes item)
 {
     return(GenerateKey(item.GetKey()));
 }
 public async Task AddAsync(DeviceFlowCodes item)
 {
     var item1 = CreateCacheItem(item);
     var key   = GetKey(item);
     await _handle.cache.InsertAsync(key, item1);
 }
 private static Tag[] GetTags(DeviceFlowCodes item)
 {
     return(GenerateTags(item.GetTags()));
 }
Esempio n. 20
0
        public async Task <IActionResult> VerificationAsync(string userCode)
        {
            DeviceFlowCodes deviceFlowCode = await DeviceFlowCodesRepository.FindByUserCodeAsync(userCode);

            return(Json(deviceFlowCode));
        }