private Message <TModel> Unprotect(string data)
    {
        var json    = _protector.Unprotect(data);
        var message = ObjectSerializer.FromString <Message <TModel> >(json);

        return(message);
    }
        public static async Task <T> ReadJsonAsync <T>(
            this HttpRequest request)
        {
            var body = await ReadAsync(request);

            return(ObjectSerializer.FromString <T>(body) !);
        }
Beispiel #3
0
        public AuthenticationProperties Unprotect(string protectedText, string purpose)
        {
            // Decrypt the key and retrieve the data from the cache.
            var key      = Protector.Unprotect(protectedText);
            var cacheKey = $"{CacheKeyPrefix}-{purpose}-{key}";
            var json     = Cache.GetString(cacheKey);

            return(ObjectSerializer.FromString <AuthenticationProperties>(json));
        }
 public void FromString_Returns_Default_When_Value_Is_NullOrEmpty(
     string value)
 {
     Assert.Null(ObjectSerializer.FromString <string>(value));
     Assert.Null(ObjectSerializer.FromString <TestObject>(value));
     Assert.Equal(
         0,
         ObjectSerializer.FromString <int>(value));
 }
Beispiel #5
0
        private IEnumerable <string> DecodeList(string value)
        {
            if (value.IsPresent())
            {
                var bytes = Base64Url.Decode(value);
                value = Encoding.UTF8.GetString(bytes);
                return(ObjectSerializer.FromString <string[]>(value));
            }

            return(Enumerable.Empty <string>());
        }
Beispiel #6
0
        private string DecodeAnonumousId(string encodedId)
        {
            if (encodedId.IsPresent())
            {
                var bytes = Base64Url.Decode(encodedId);
                encodedId = Encoding.UTF8.GetString(bytes);
                return(ObjectSerializer.FromString <string>(encodedId));
            }

            return(null);
        }
        /// <inheritdoc/>
        public async Task <Message <IDictionary <string, string[]> > > ReadAsync(string id)
        {
            var cacheKey = $"{CacheKeyPrefix}-{id}";
            var json     = await _distributedCache.GetStringAsync(cacheKey);

            if (json == null)
            {
                return(new Message <IDictionary <string, string[]> >(new Dictionary <string, string[]>()));
            }

            return(ObjectSerializer.FromString <Message <IDictionary <string, string[]> > >(json));
        }
        /// <inheritdoc/>
        public async Task <Message <NameValueCollection> > ReadAsync(string id)
        {
            var cacheKey = $"{CacheKeyPrefix}-{id}";
            var json     = await _distributedCache.GetStringAsync(cacheKey);

            if (json == null)
            {
                return(new Message <NameValueCollection>(new NameValueCollection()));
            }

            return(ObjectSerializer.FromString <Message <NameValueCollection> >(json));
        }
Beispiel #9
0
    /// <inheritdoc/>
    public virtual async Task <Message <IDictionary <string, string[]> > > ReadAsync(string id)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("DistributedCacheAuthorizationParametersMessageStore.Read");

        var cacheKey = $"{CacheKeyPrefix}-{id}";
        var json     = await _distributedCache.GetStringAsync(cacheKey);

        if (json == null)
        {
            return(new Message <IDictionary <string, string[]> >(new Dictionary <string, string[]>()));
        }

        return(ObjectSerializer.FromString <Message <IDictionary <string, string[]> > >(json));
    }
        public async Task <PolicyResult> GetPolicyAsync(HttpContext context)
        {
            String accessToken = await context.GetTokenAsync("access_token");

            if (accessToken.IsMissing())
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            String content = await client.GetStringAsync($"{_options.Authority}/{Constants.ProtocolRoutePaths.Permission}?clientId={_options.ClientId}");

            PolicyResult result = ObjectSerializer.FromString <PolicyResult>(content);

            return(result);
        }
        public Task <Message <TModel> > ReadAsync(string value)
        {
            Message <TModel> result = null;

            if (!String.IsNullOrWhiteSpace(value))
            {
                try
                {
                    var bytes = Base64Url.Decode(value);
                    bytes = _protector.Unprotect(bytes);
                    var json = Encoding.UTF8.GetString(bytes);
                    result = ObjectSerializer.FromString <Message <TModel> >(json);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Exception reading protected message");
                }
            }

            return(Task.FromResult(result));
        }
    /// <summary>
    /// Unprotects the specified protected text.
    /// </summary>
    /// <param name="protectedText">The protected text.</param>
    /// <param name="purpose">The purpose.</param>
    /// <returns></returns>
    public AuthenticationProperties Unprotect(string protectedText, string purpose)
    {
        if (String.IsNullOrWhiteSpace(protectedText))
        {
            return(null);
        }

        // Decrypt the key and retrieve the data from the cache.
        var key      = Protector.Unprotect(protectedText);
        var cacheKey = $"{CacheKeyPrefix}-{_name}-{purpose}-{key}";
        var json     = Cache.GetString(cacheKey);

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

        var props = ObjectSerializer.FromString <AuthenticationProperties>(json);

        return(props);
    }
        public void FromString_Returns_Expected_Object()
        {
            var expected = new TestObject
            {
                Property1 = "value",
                Property2 = "value",
                Property3 = 0,
            };

            var actual = ObjectSerializer.FromString <TestObject>(
                "{\"property1\":\"value\",\"property2\":\"value\"}");

            Assert.Equal(
                expected.Property1,
                actual.Property1);
            Assert.Equal(
                expected.Property2,
                actual.Property2);
            Assert.Equal(
                expected.Property3,
                actual.Property3);
        }
Beispiel #14
0
    /// <inheritdoc />
    public virtual Task <Message <TModel> > ReadAsync(string value)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("ProtectedDataMessageStore.Read");

        Message <TModel> result = null;

        if (!String.IsNullOrWhiteSpace(value))
        {
            try
            {
                var bytes = Base64Url.Decode(value);
                bytes = Protector.Unprotect(bytes);
                var json = Encoding.UTF8.GetString(bytes);
                result = ObjectSerializer.FromString <Message <TModel> >(json);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Exception reading protected message");
            }
        }

        return(Task.FromResult(result));
    }
Beispiel #15
0
        private void loadText(string path)
        {
            var targetDirectory = Path.Combine(Path.GetDirectoryName(path), DataFolder);

            using (var directoryReader = new SafeDirectoryReader(targetDirectory))
            {
                var indexPath = directoryReader.GetPath("index.yaml");
                var indexRoot = TinyToken.Read(indexPath);

                var indexVersion = indexRoot.Value <int>("FormatVersion");
                if (indexVersion > Version)
                {
                    throw new InvalidOperationException("This project was saved with a more recent version, you need to update to open it");
                }

                var userPath = directoryReader.GetPath("user.yaml");
                if (File.Exists(userPath))
                {
                    var userRoot = TinyToken.Read(userPath);

                    var userVersion = userRoot.Value <int>("FormatVersion");
                    if (userVersion > Version)
                    {
                        throw new InvalidOperationException("This project's user settings were saved with a more recent version, you need to update to open it");
                    }

                    var savedBy = userRoot.Value <string>("Editor");
                    Debug.Print($"Project saved by {savedBy}");

                    OwnsOsb = userRoot.Value <bool>("OwnsOsb");
                }

                MapsetPath = indexRoot.Value <string>("MapsetPath");
                SelectBeatmap(indexRoot.Value <long>("BeatmapId"), indexRoot.Value <string>("BeatmapName"));
                ImportedAssemblies = indexRoot.Values <string>("Assemblies");

                // Load effects
                var layerInserters = new Dictionary <string, Action>();
                foreach (var effectPath in Directory.EnumerateFiles(directoryReader.Path, "effect.*.yaml", SearchOption.TopDirectoryOnly))
                {
                    var guidMatch = effectGuidRegex.Match(effectPath);
                    if (!guidMatch.Success || guidMatch.Groups.Count < 2)
                    {
                        throw new InvalidDataException($"Could not parse effect Guid from '{effectPath}'");
                    }

                    var effectRoot = TinyToken.Read(effectPath);

                    var effectVersion = effectRoot.Value <int>("FormatVersion");
                    if (effectVersion > Version)
                    {
                        throw new InvalidOperationException("This project contains an effect that was saved with a more recent version, you need to update to open it");
                    }

                    var effect = AddEffect(effectRoot.Value <string>("Script"));
                    effect.Guid = Guid.Parse(guidMatch.Groups[1].Value);
                    effect.Name = effectRoot.Value <string>("Name");

                    var configRoot = effectRoot.Value <TinyObject>("Config");
                    var fieldIndex = 0;
                    foreach (var fieldProperty in configRoot)
                    {
                        var fieldRoot = fieldProperty.Value;

                        var fieldTypeName = fieldRoot.Value <string>("Type");
                        var fieldContent  = fieldRoot.Value <string>("Value");
                        var fieldValue    = ObjectSerializer.FromString(fieldTypeName, fieldContent);

                        var allowedValues = fieldRoot
                                            .Value <TinyObject>("AllowedValues")?
                                            .Select(p => new NamedValue {
                            Name = p.Key, Value = ObjectSerializer.FromString(fieldTypeName, p.Value.Value <string>()),
                        })
                                            .ToArray();

                        effect.Config.UpdateField(fieldProperty.Key, fieldRoot.Value <string>("DisplayName") ?? fieldProperty.Key, fieldIndex++, fieldValue?.GetType(), fieldValue, allowedValues);
                    }

                    var layersRoot = effectRoot.Value <TinyObject>("Layers");
                    foreach (var layerProperty in layersRoot)
                    {
                        var layerEffect = effect;
                        var layerGuid   = layerProperty.Key;
                        var layerRoot   = layerProperty.Value;
                        layerInserters.Add(layerGuid, () => layerEffect.AddPlaceholder(new EditorStoryboardLayer(layerRoot.Value <string>("Name"), layerEffect)
                        {
                            Guid         = Guid.Parse(layerGuid),
                            OsbLayer     = layerRoot.Value <OsbLayer>("OsbLayer"),
                            DiffSpecific = layerRoot.Value <bool>("DiffSpecific"),
                            Visible      = layerRoot.Value <bool>("Visible"),
                        }));
                    }
                }

                // Insert layers defined in the index
                var layersOrder = indexRoot.Values <string>("Layers");
                if (layersOrder != null)
                {
                    foreach (var layerGuid in layersOrder.Distinct())
                    {
                        if (layerInserters.TryGetValue(layerGuid, out var insertLayer))
                        {
                            insertLayer();
                        }
                    }
                }

                // Insert all remaining layers
                foreach (var key in layersOrder == null ? layerInserters.Keys : layerInserters.Keys.Except(layersOrder))
                {
                    var insertLayer = layerInserters[key];
                    insertLayer();
                }
            }
        }