예제 #1
0
        protected virtual string Serialize([CanBeNull] DeviceCode deviceCode)
        {
            if (deviceCode == null)
            {
                return(null);
            }

            return(PersistentGrantSerializer.Serialize(deviceCode));
        }
        public async Task Should_Find_Existing_UserCode(TestDatabase testDb)
        {
            var loggerMock = new Mock <ILogger <DeviceFlowStore> >();
            var serializer = new PersistentGrantSerializer();

            var testDeviceCode = $"device_{Guid.NewGuid()}";
            var testUserCode   = $"user_{Guid.NewGuid()}";

            var expectedSubject        = $"sub_{Guid.NewGuid()}";
            var expectedDeviceCodeData = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 12, 07, 14, 15, 16),
                Lifetime        = 42,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(
                    new ClaimsIdentity(
                        new List <Claim> {
                    new Claim(JwtClaimTypes.Subject, expectedSubject)
                }
                        )
                    )
            };

            using (var session = testDb.SessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    await session.SaveAsync(new DeviceFlowCodes
                    {
                        DeviceCode   = testDeviceCode,
                        ID           = testUserCode,
                        ClientId     = expectedDeviceCodeData.ClientId,
                        SubjectId    = expectedDeviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                        CreationTime = expectedDeviceCodeData.CreationTime,
                        Expiration   = expectedDeviceCodeData.CreationTime.AddSeconds(expectedDeviceCodeData.Lifetime),
                        Data         = serializer.Serialize(expectedDeviceCodeData)
                    });

                    await tx.CommitAsync();
                }
            }

            DeviceCode code;

            using (var session = testDb.SessionFactory.OpenSession())
            {
                var store = new DeviceFlowStore(session, serializer, loggerMock.Object);
                code = await store.FindByUserCodeAsync(testUserCode);
            }

            code.Should().BeEquivalentTo(expectedDeviceCodeData, assertionOptions => assertionOptions.Excluding(x => x.Subject));
            code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull();

            await CleanupTestDataAsync(testDb);
        }
예제 #3
0
        private bool TryGetConditions(int pageIndex, int pageSize, out Hashtable conditions)
        {
            var errors = new List <string>();

            Int32 pageStart = pageSize * (pageIndex - 1) + 1;
            Int32 pageEnd   = pageSize * pageIndex;

            EndDate = EndDate.AddDays(1).AddSeconds(-1);
            var logType = GetLogType();

            conditions = new Hashtable()
            {
                { "RecordType", logType },
                { "StartDate", StartDate },
                { "EndDate", EndDate },
                { "PageStart", pageStart },
                { "PageEnd", pageEnd },
            };

            if (!string.IsNullOrWhiteSpace(DeviceCode))
            {
                if (DeviceCode.ToInt32() == ConvertorExtension.ConvertionFailureValue)
                {
                    errors.Add("设备编号的输入值必须是数字");
                }
                if (ApplicationManager.GetInstance().AuthorizationDevices.All(x => x.Code != DeviceCode))
                {
                    errors.Add("输入的设备编号不存在系统中");
                }

                conditions.Add("DeviceCode", DeviceCode);
            }


            if (!string.IsNullOrWhiteSpace(DeviceUserId))
            {
                if (DeviceUserId.ToInt32() == ConvertorExtension.ConvertionFailureValue)
                {
                    errors.Add("人员工号的输入值必须是数字");
                }

                conditions.Add("DeviceUserId", DeviceUserId);
            }

            if (errors.Any())
            {
                var message = string.Join("\n", errors);
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    Messenger.Default.Send(new NotificationMessage(message), Tokens.DeviceTrafficLogPage_ShowNotification);
                });
                return(false);
            }

            return(true);
        }
예제 #4
0
        public void Set(DeviceCode code, ushort offset, ushort[] values)
        {
            var page = this.Map[code];

            for (int i = 0; i < values.Length; i++)
            {
                var address = this.EnsureAddress(offset + i);
                page[address] = values[i];
            }
        }
예제 #5
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);
        }
        public void ConnectPlayer(string nickname, DeviceCode deviceCode)
        {
            Dictionary <byte, object> operationParameters = new Dictionary <byte, object>
            {
                { (byte)ConnectPlayerParameterCode.Nickname, nickname },
                { (byte)ConnectPlayerParameterCode.DeviceCode, deviceCode }
            };

            SendOperation(DeviceOperationCode.ConnectPlayer, operationParameters);
        }
    /// <summary>
    /// Stores the device authorization request.
    /// </summary>
    /// <param name="userCode">The user code.</param>
    /// <param name="data">The data.</param>
    /// <returns></returns>
    public async Task <string> StoreDeviceAuthorizationAsync(string userCode, DeviceCode data)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("DefaultDeviceFlowCodeService.SendLogoutNotifStoreDeviceAuthorization");

        var deviceCode = await _handleGenerationService.GenerateAsync();

        await _store.StoreDeviceAuthorizationAsync(deviceCode.Sha256(), userCode.Sha256(), data);

        return(deviceCode);
    }
예제 #8
0
        public static Command Parse(string commandLine)
        {
            var    splited         = commandLine.Split('=');
            string devicesToString = null;
            string valuesToString  = null;

            if (splited.Length == 2)
            {
                devicesToString = splited[0];
                valuesToString  = splited[1];
            }
            else if (splited.Length == 1)
            {
                devicesToString = splited[0];
            }
            else
            {
                return(null);
            }

            DeviceCode code    = DeviceCode.None;
            var        devices = ParseDevices(devicesToString, out code);

            if (devices == null)
            {
                return(null);
            }

            if (valuesToString == null)
            {
                var command = new CommandGet();
                command.DeviceCode = code;
                command.Offset     = devices.Item1;
                command.Count      = devices.Item2;

                return(command);
            }
            else
            {
                int count  = devices.Item2;
                var values = ParseValues(valuesToString);

                if (values.Length != count)
                {
                    return(null);
                }

                var command = new CommandSet();
                command.DeviceCode = code;
                command.Offset     = devices.Item1;
                command.Values     = values;

                return(command);
            }
        }
예제 #9
0
 public static PollReply CreatePollReply(
     string manufacture, string modelName, DmxMode length,
     bool hasWiFiIf, bool hasEthIf, DeviceCode dc,
     byte dmxIn, byte dmxOut, byte midiIn,
     byte midiOut, byte laserOut, byte stripOut
     ) => new PollReply(
     header,
     manufacture, modelName, length,
     hasWiFiIf, hasEthIf, dc,
     dmxIn, dmxOut, midiIn,
     midiOut, laserOut, stripOut);
예제 #10
0
        // OpenSession(u32 device_code, u32 unk) -> object<nn::clkrst::IClkrstSession>
        public ResultCode OpenSession(ServiceCtx context)
        {
            DeviceCode deviceCode = (DeviceCode)context.RequestData.ReadUInt32();
            uint       unknown    = context.RequestData.ReadUInt32();

            // TODO: Service checks the deviceCode and the unk value.

            MakeObject(context, new IClkrstSession(deviceCode, unknown));

            return(ResultCode.Success);
        }
예제 #11
0
        public EyeTrackerDevice(TrackerBrowser browser)
        {
            _config  = new EyeTrackerRecordingConfiguration();
            _browser = browser;

            Code = DeviceCode.Create(this, DeviceType.Physiological.EYETRACKER)
                   .RequiresCalibrationBeforeStart(true)
                   .ConnectionType(DeviceConnectionType.Port)
                   .RunsOnMainThread(false)
                   .Build();
        }
예제 #12
0
        public static int GetDeviceNumber(DeviceCode code)
        {
            switch (code)
            {
            case DeviceCode.ONE:
                return(1);

            case DeviceCode.TWO:
                return(2);

            case DeviceCode.THREE:
                return(3);

            case DeviceCode.FOUR:
                return(4);

            case DeviceCode.FIVE:
                return(5);

            case DeviceCode.SIX:
                return(6);

            case DeviceCode.SEVEN:
                return(7);

            case DeviceCode.EIGHT:
                return(8);

            case DeviceCode.NINE:
                return(9);

            case DeviceCode.TEN:
                return(10);

            case DeviceCode.ELEVEN:
                return(11);

            case DeviceCode.TWELVE:
                return(12);

            case DeviceCode.THIRTEEN:
                return(13);

            case DeviceCode.FOURTEEN:
                return(14);

            case DeviceCode.FIFTEEN:
                return(15);

            case DeviceCode.SIXTEEN:
                return(16);
            }
            throw (new ApplicationException("Device Code out of range"));
        }
예제 #13
0
        public void RemoteOperation(DeviceCode deviceCode, byte operationCode, Dictionary <byte, object> operationParameters)
        {
            Dictionary <byte, object> parameters = new Dictionary <byte, object>
            {
                { (byte)RemoteOperationParameterCode.DeviceCode, (byte)deviceCode },
                { (byte)RemoteOperationParameterCode.OperationCode, operationCode },
                { (byte)RemoteOperationParameterCode.Parameters, operationParameters }
            };

            SendOperation(PlayerOperationCode.RemoteOperation, parameters);
        }
    /// <summary>
    /// Stores the device authorization request.
    /// </summary>
    /// <param name="deviceCode">The device code.</param>
    /// <param name="userCode">The user code.</param>
    /// <param name="data">The data.</param>
    /// <returns></returns>
    public Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.StoreDeviceAuthorization");

        lock (_repository)
        {
            _repository.Add(new InMemoryDeviceAuthorization(deviceCode, userCode, data));
        }

        return(Task.CompletedTask);
    }
        /// <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);
        }
        public async Task FindByDeviceCodeAsync_WhenDeviceCodeExists_ExpectDataRetrievedCorrectly()
        {
            using var ravenStore = GetDocumentStore();
            await new DeviceFlowCodeIndex().ExecuteAsync(ravenStore);

            var testDeviceCode = $"device_{Guid.NewGuid().ToString()}";
            var testUserCode   = $"user_{Guid.NewGuid().ToString()}";

            var expectedSubject        = $"sub_{Guid.NewGuid().ToString()}";
            var expectedDeviceCodeData = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                {
                    new Claim(JwtClaimTypes.Subject, expectedSubject)
                }))
            };

            using (var session = ravenStore.OpenSession())
            {
                session.Store(new DeviceFlowCode
                {
                    DeviceCode   = testDeviceCode,
                    UserCode     = testUserCode,
                    ClientId     = expectedDeviceCodeData.ClientId,
                    SubjectId    = expectedDeviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                    CreationTime = expectedDeviceCodeData.CreationTime,
                    Expiration   = expectedDeviceCodeData.CreationTime.AddSeconds(expectedDeviceCodeData.Lifetime),
                    Data         = serializer.Serialize(expectedDeviceCodeData)
                });
                session.SaveChanges();
            }

            WaitForIndexing(ravenStore);

            DeviceCode code;

            using (var session = ravenStore.OpenAsyncSession())
            {
                var store = new DeviceFlowStore(session, new PersistentGrantSerializer(),
                                                FakeLogger <DeviceFlowStore> .Create());
                code = await store.FindByDeviceCodeAsync(testDeviceCode);
            }

            code.Should().BeEquivalentTo(expectedDeviceCodeData,
                                         assertionOptions => assertionOptions.Excluding(x => x.Subject));

            code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject)
            .Should().NotBeNull();
        }
예제 #17
0
        public async Task Should_Throw_Exception_If_DeviceCode_Already_Exists(TestDatabase testDb)
        {
            var loggerMock = new Mock <ILogger <DeviceFlowStore> >();
            var serializer = new PersistentGrantSerializer();

            var existingUserCode = $"user_{Guid.NewGuid()}";
            var deviceCodeData   = new DeviceCode()
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 12, 07, 8, 00, 00),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(
                    new ClaimsIdentity(
                        new List <Claim> {
                    new Claim(JwtClaimTypes.Subject, $"sub_{Guid.NewGuid()}")
                }
                        )
                    )
            };

            using (var session = testDb.SessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    await session.SaveAsync(new DeviceFlowCodes()
                    {
                        DeviceCode   = $"device_{Guid.NewGuid()}",
                        ID           = existingUserCode,
                        ClientId     = deviceCodeData.ClientId,
                        SubjectId    = deviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                        CreationTime = deviceCodeData.CreationTime,
                        Expiration   = deviceCodeData.CreationTime.AddSeconds(deviceCodeData.Lifetime),
                        Data         = serializer.Serialize(deviceCodeData)
                    });

                    await tx.CommitAsync();
                }
            }

            using (var session = testDb.SessionFactory.OpenSession())
            {
                var store = new DeviceFlowStore(session, new PersistentGrantSerializer(), loggerMock.Object);

                Func <Task> act = async() => await store.StoreDeviceAuthorizationAsync($"device_{Guid.NewGuid()}", existingUserCode, deviceCodeData);

                await act.Should().ThrowAsync <HibernateException>();
            }

            await CleanupTestDataAsync(testDb);
        }
예제 #18
0
        public VideoStreamerDevice(FFmpegStreamer streamer, IVideoStreamerConfiguration configuration)
        {
            _config          = configuration;
            _recordingConfig = new VideoStreamerRecordingConfiguration(configuration);

            _streamer = streamer;
            _streamer.ProcessExited += (_, __) => ConnectionError?.Invoke(this, new ConnectionException("Webcam video process exited."));

            Code = DeviceCode.Create(this, DeviceType.Streaming.WEBCAM_VIDEO)
                   .RunsOnMainThread(false)
                   .ConnectionType(DeviceConnectionType.Process)
                   .Build();
        }
예제 #19
0
        public ScreenCastStreamerDevice(FFmpegStreamer streamer, IScreenCastStreamerConfiguration configuration)
        {
            _config          = configuration;
            _recordingConfig = new VideoStreamerRecordingConfiguration(configuration);

            _streamer = streamer;
            _streamer.ProcessExited += (_, e) => ConnectionError?.Invoke(this, new ConnectionException("Screencast process exited."));

            Code = DeviceCode.Create(this, DeviceType.Streaming.SCREENCAST)
                   .RunsOnMainThread(false)
                   .ConnectionType(DeviceConnectionType.Process)
                   .Build();
        }
예제 #20
0
        public ushort[] Get(DeviceCode code, ushort offset, ushort count)
        {
            var page   = this.Map[code];
            var values = new ushort[count];

            for (int i = 0; i < count; i++)
            {
                var address = this.EnsureAddress(offset + i);
                values[i] = page[address];
            }

            return(values);
        }
예제 #21
0
        public void AddDevice(Device device, DeviceCode deviceCode)
        {
            switch (deviceCode)
            {
            case DeviceCode.Head:
                HeadDeviceConnected = true;
                break;

            case DeviceCode.HandTake:
                HandTakeDeviceConnected = true;
                break;
            }
            deviceDictionary.Add(device, deviceCode);
        }
예제 #22
0
        /// <summary>
        /// Updates device authorization, searching by user code.
        /// </summary>
        /// <param name="userCode">The user code.</param>
        /// <param name="data">The data.</param>
        public Task UpdateByUserCodeAsync(string userCode, DeviceCode data)
        {
            lock (_repository)
            {
                var foundData = _repository.FirstOrDefault(x => x.UserCode == userCode);

                if (foundData != null)
                {
                    foundData.Data = data;
                }
            }

            return(Task.CompletedTask);
        }
예제 #23
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (header_ != null)
            {
                hash ^= Header.GetHashCode();
            }
            if (UserName.Length != 0)
            {
                hash ^= UserName.GetHashCode();
            }
            if (Password.Length != 0)
            {
                hash ^= Password.GetHashCode();
            }
            if (ValidCode.Length != 0)
            {
                hash ^= ValidCode.GetHashCode();
            }
            if (ValidId.Length != 0)
            {
                hash ^= ValidId.GetHashCode();
            }
            if (PhoneNumber.Length != 0)
            {
                hash ^= PhoneNumber.GetHashCode();
            }
            if (DeviceCode.Length != 0)
            {
                hash ^= DeviceCode.GetHashCode();
            }
            if (InviteCode.Length != 0)
            {
                hash ^= InviteCode.GetHashCode();
            }
            if (LoginType != 0)
            {
                hash ^= LoginType.GetHashCode();
            }
            if (Register != false)
            {
                hash ^= Register.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
 internal override bool Handle(PlayerOperationCode operationCode, Dictionary <byte, object> parameters, out string errorMessage)
 {
     if (base.Handle(operationCode, parameters, out errorMessage))
     {
         DeviceCode deviceCode          = (DeviceCode)parameters[(byte)RemoteOperationParameterCode.DeviceCode];
         byte       remoteOperationCode = (byte)parameters[(byte)RemoteOperationParameterCode.OperationCode];
         Dictionary <byte, object> remoteOperationParameters = (Dictionary <byte, object>)parameters[(byte)RemoteOperationParameterCode.Parameters];
         subject.EventManager.RemoteOperation(deviceCode, remoteOperationCode, remoteOperationParameters);
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #25
0
        public async Task Should_Remove_Existing_DeviceCode(TestDatabase testDb)
        {
            var loggerMock = new Mock <ILogger <DeviceFlowStore> >();
            var serializer = new PersistentGrantSerializer();

            var testDeviceCode = $"device_{Guid.NewGuid()}";
            var testUserCode   = $"user_{Guid.NewGuid()}";

            var existingDeviceCode = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 12, 7, 14, 15, 16),
                Lifetime        = 42,
                IsOpenId        = true
            };

            using (var session = testDb.SessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    await session.SaveAsync(new DeviceFlowCodes
                    {
                        DeviceCode   = testDeviceCode,
                        ID           = testUserCode,
                        ClientId     = existingDeviceCode.ClientId,
                        CreationTime = existingDeviceCode.CreationTime,
                        Expiration   = existingDeviceCode.CreationTime.AddSeconds(existingDeviceCode.Lifetime),
                        Data         = serializer.Serialize(existingDeviceCode)
                    });

                    await tx.CommitAsync();
                }
            }

            using (var session = testDb.SessionFactory.OpenSession())
            {
                var store = new DeviceFlowStore(session, serializer, loggerMock.Object);
                await store.RemoveByDeviceCodeAsync(testDeviceCode);
            }

            using (var session = testDb.SessionFactory.OpenSession())
            {
                (await session.GetAsync <DeviceFlowCodes>(testUserCode)).Should().BeNull();
            }

            await CleanupTestDataAsync(testDb);
        }
        public async Task <DeviceCode> FindByDeviceCodeAsync(string deviceCode)
        {
            DocumentSnapshot deviceFlowCodes =
                await GetDeviceFlow(nameof(DeviceFlowCodes.DeviceCode), deviceCode).ConfigureAwait(false);

            if (!deviceFlowCodes.Exists)
            {
                return(null);
            }

            DeviceCode model = ToModel(deviceFlowCodes.ConvertTo <DeviceFlowCodes>().Data);

            _logger.LogDebug("{deviceCode} found in database: {deviceCodeFound}", deviceCode, model != null);

            return(model);
        }
    /// <summary>
    /// Updates device authorization, searching by user code.
    /// </summary>
    /// <param name="userCode">The user code.</param>
    /// <param name="data">The data.</param>
    public Task UpdateByUserCodeAsync(string userCode, DeviceCode data)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("InMemoryDeviceFlowStore.UpdateByUserCode");

        lock (_repository)
        {
            var foundData = _repository.FirstOrDefault(x => x.UserCode == userCode);

            if (foundData != null)
            {
                foundData.Data = data;
            }
        }

        return(Task.CompletedTask);
    }
예제 #28
0
        /// <summary>
        /// Get the device code
        /// </summary>
        /// <param name="mparam">The model parameters</param>
        /// <param name="dparam">The device parameters</param>
        /// <param name="ckt">The circuit identifier</param>
        /// <param name="model">The model identifier</param>
        /// <returns></returns>
        protected string GetDeviceCode(SpiceParam mparam, SpiceParam dparam, string ckt = "ckt", string model = "Model")
        {
            string code = DeviceCode.Trim();

            code = ApplyGeneral(code, ckt);
            code = ApplyParameters(code, DeviceParameter, dparam, DeviceVariablesExtra);
            code = ApplyParameters(code, ModelParameter, mparam, ModelVariablesExtra, model + ".");

            // Replace all shared variables
            foreach (var s in SharedLocalVariables)
            {
                code = Regex.Replace(code, $@"(?<!\w){s.Key}(?!\w)", $"{model}.{s.Key}");
            }

            return(code);
        }
예제 #29
0
        public async Task FindByUserCodeAsync_WhenUserCodeExists_ExpectDataRetrievedCorrectly()
        {
            var testDeviceCode = $"device_{Guid.NewGuid().ToString()}";
            var testUserCode   = $"user_{Guid.NewGuid().ToString()}";

            var expectedSubject        = $"sub_{Guid.NewGuid().ToString()}";
            var expectedDeviceCodeData = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                    new Claim(JwtClaimTypes.Subject, expectedSubject)
                }))
            };

            var repo = g.operationalDb.GetRepository <Storage.Entities.DeviceFlowCodes>();

            var entity = new Storage.Entities.DeviceFlowCodes
            {
                DeviceCode   = testDeviceCode,
                UserCode     = testUserCode,
                ClientId     = expectedDeviceCodeData.ClientId,
                SubjectId    = expectedDeviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = expectedDeviceCodeData.CreationTime,
                Expiration   = expectedDeviceCodeData.CreationTime.AddSeconds(expectedDeviceCodeData.Lifetime),
                Data         = serializer.Serialize(expectedDeviceCodeData)
            };

            repo.Insert(entity);


            DeviceCode code;

            var store = new DeviceFlowStore(g.operationalDb, new PersistentGrantSerializer(), FakeLogger <DeviceFlowStore> .Create());

            code = await store.FindByUserCodeAsync(testUserCode);


            code.Should().BeEquivalentTo(expectedDeviceCodeData,
                                         assertionOptions => assertionOptions.Excluding(x => x.Subject));

            code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull();
        }
    public async Task FindByDeviceCodeAsync_WhenDeviceCodeExists_ExpectDataRetrievedCorrectly(DbContextOptions <PersistedGrantDbContext> options)
    {
        var testDeviceCode = $"device_{Guid.NewGuid().ToString()}";
        var testUserCode   = $"user_{Guid.NewGuid().ToString()}";

        var expectedSubject        = $"sub_{Guid.NewGuid().ToString()}";
        var expectedDeviceCodeData = new DeviceCode
        {
            ClientId        = "device_flow",
            RequestedScopes = new[] { "openid", "api1" },
            CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
            Lifetime        = 300,
            IsOpenId        = true,
            Subject         = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                new Claim(JwtClaimTypes.Subject, expectedSubject)
            }))
        };

        using (var context = new PersistedGrantDbContext(options))
        {
            context.DeviceFlowCodes.Add(new DeviceFlowCodes
            {
                DeviceCode   = testDeviceCode,
                UserCode     = testUserCode,
                ClientId     = expectedDeviceCodeData.ClientId,
                SubjectId    = expectedDeviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = expectedDeviceCodeData.CreationTime,
                Expiration   = expectedDeviceCodeData.CreationTime.AddSeconds(expectedDeviceCodeData.Lifetime),
                Data         = serializer.Serialize(expectedDeviceCodeData)
            });
            context.SaveChanges();
        }

        DeviceCode code;

        using (var context = new PersistedGrantDbContext(options))
        {
            var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), FakeLogger <DeviceFlowStore> .Create(), new NoneCancellationTokenProvider());
            code = await store.FindByDeviceCodeAsync(testDeviceCode);
        }

        code.Should().BeEquivalentTo(expectedDeviceCodeData,
                                     assertionOptions => assertionOptions.Excluding(x => x.Subject));

        code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull();
    }
예제 #31
0
 public X10AddressCommand(HouseCode houseCode, DeviceCode deviceCode)
 {
     this.House = houseCode;
     this.Device = deviceCode;
 }
예제 #32
0
        /// <summary>
        /// Creates the address code <see cref="byte"/> to send to the controller
        /// </summary>
        /// <param name="houseCode"><see cref="HouseCode"/></param>
        /// <param name="deviceCode"><see cref="DeviceCode"/></param>
        /// <returns><see cref="byte"/> to send</returns>
        private static byte CreateAddressCode(HouseCode houseCode, DeviceCode deviceCode)
        {
            // create code
            BitArray result = new BitArray(8);
            BitArray ba = new BitArray(new byte[] { (byte)deviceCode });
            result[3] = ba[3];
            result[2] = ba[2];
            result[1] = ba[1];
            result[0] = ba[0];

            ba = new BitArray(new byte[] { (byte)houseCode });
            result[7] = ba[3];
            result[6] = ba[2];
            result[5] = ba[1];
            result[4] = ba[0];

            byte[] byteArray = new byte[(int)Math.Ceiling((double)result.Length / 8)];
            result.CopyTo(byteArray, 0);

            return byteArray[0];
        }
예제 #33
0
 public static int GetDeviceNumber(DeviceCode code)
 {
     switch (code)
     {
         case DeviceCode.ONE:
             return (1);
         case DeviceCode.TWO:
             return (2);
         case DeviceCode.THREE:
             return (3);
         case DeviceCode.FOUR:
             return 4;
         case DeviceCode.FIVE:
             return (5);
         case DeviceCode.SIX:
             return (6);
         case DeviceCode.SEVEN:
             return (7);
         case DeviceCode.EIGHT:
             return (8);
         case DeviceCode.NINE:
             return (9);
         case DeviceCode.TEN:
             return (10);
         case DeviceCode.ELEVEN:
             return (11);
         case DeviceCode.TWELVE:
             return (12);
         case DeviceCode.THIRTEEN:
             return (13);
         case DeviceCode.FOURTEEN:
             return (14);
         case DeviceCode.FIFTEEN:
             return (15);
         case DeviceCode.SIXTEEN:
             return (16);
     }
     throw (new ApplicationException("Device Code out of range"));
 }