<commit_before>﻿// Copyright (c) <NAME> & <NAME>. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System;
using System.Net.Http;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using IdentityModel.AspNetCore.OAuth2Introspection.Infrastructure;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace IdentityModel.AspNetCore.OAuth2Introspection
{
    public class OAuth2IntrospectionMiddleware : AuthenticationMiddleware<OAuth2IntrospectionOptions>
    {
        LazyAsync<IntrospectionClient> _client;
        private readonly IDistributedCache _cache;
        private readonly ILoggerFactory _loggerFactory;

        public OAuth2IntrospectionMiddleware(RequestDelegate next, IOptions<OAuth2IntrospectionOptions> options, UrlEncoder urlEncoder, ILoggerFactory loggerFactory, IDistributedCache cache = null)
            : base(next, options, loggerFactory, urlEncoder)
        {
            _loggerFactory = loggerFactory;

            if (options.Value.Authority.IsMissing() && options.Value.IntrospectionEndpoint.IsMissing())
            {
                throw new InvalidOperationException("You must either set Authority or IntrospectionEndpoint");
            }

            if (options.Value.ScopeName.IsMissing() && options.Value.IntrospectionHttpHandler == null)
            {
                throw new InvalidOperationException("You must either set a ScopeName or set an introspection HTTP handler");
            }

            if (options.Value.TokenRetriever == null)
            {
                throw new ArgumentException("TokenRetriever must be set", nameof(options.Value.TokenRetriever));
            }

            if (options.Value.EnableCaching == true && cache == null)
            {
                throw new ArgumentException("Caching is enabled, but no cache is found in the services collection", nameof(cache));
            }

            _cache = cache;
            _client = new LazyAsync<IntrospectionClient>(InitializeIntrospectionClient);

            if (options.Value.DelayLoadDiscoveryDocument == false)
            {
                var temp = _client.GetValue();
            }
        }

        private async Task<IntrospectionClient> InitializeIntrospectionClient()
        {
            string endpoint;

            if (Options.IntrospectionEndpoint.IsPresent())
            {
                endpoint = Options.IntrospectionEndpoint;
            }
            else
            {
                endpoint = await GetIntrospectionEndpointFromDiscoveryDocument().ConfigureAwait(false);
                Options.IntrospectionEndpoint = endpoint;
            }

            IntrospectionClient client;<commit_msg>Fixed broken test<commit_after>﻿// Copyright (c) <NAME> & <NAME>. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System;
using System.Net.Http;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using IdentityModel.AspNetCore.OAuth2Introspection.Infrastructure;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace IdentityModel.AspNetCore.OAuth2Introspection
{
    public class OAuth2IntrospectionMiddleware : AuthenticationMiddleware<OAuth2IntrospectionOptions>
    {
        LazyAsync<IntrospectionClient> _client;
        private readonly IDistributedCache _cache;
        private readonly ILoggerFactory _loggerFactory;

        public OAuth2IntrospectionMiddleware(RequestDelegate next, IOptions<OAuth2IntrospectionOptions> options, UrlEncoder urlEncoder, ILoggerFactory loggerFactory, IDistributedCache cache = null)
            : base(next, options, loggerFactory, urlEncoder)
        {
            _loggerFactory = loggerFactory;

            if (options.Value.Authority.IsMissing() && options.Value.IntrospectionEndpoint.IsMissing())
            {
                throw new InvalidOperationException("You must either set Authority or IntrospectionEndpoint");
            }

            if (options.Value.ScopeName.IsMissing() && options.Value.IntrospectionHttpHandler == null)
            {
                throw new InvalidOperationException("You must either set a ScopeName or set an introspection HTTP handler");
            }

            if (options.Value.TokenRetriever == null)
            {
                throw new ArgumentException("TokenRetriever must be set", nameof(options.Value.TokenRetriever));
            }

            if (options.Value.EnableCaching == true && cache == null)
            {
                throw new ArgumentException("Caching is enabled, but no cache is found in the services collection", nameof(cache));
            }

            _cache = cache;
            _client = new LazyAsync<IntrospectionClient>(InitializeIntrospectionClient);

            if (options.Value.DelayLoadDiscoveryDocument == false)
            {
                _client.GetValue().Wait();
            }
        }

        private async Task<IntrospectionClient> InitializeIntrospectionClient()
        {
            string endpoint;

            if (Options.IntrospectionEndpoint.IsPresent())
            {
                endpoint = Options.IntrospectionEndpoint;
            }
            else
            {
                endpoint = await GetIntrospectionEndpointFromDiscoveryDocument().ConfigureAwait(false);
                Options.IntrospectionEndpoint = endpoint;
            }

            IntrospectionClient client;
{'fraction_non_alphanumeric': 0.07448229792919171, 'fraction_numerical': 0.0026720106880427524, 'mean_word_length': 2.6991970352069177, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2565188', 'n_tokens_mistral': 1436, 'n_tokens_neox': 1436, 'n_words': 345}