using System;
using System.Text;
using GxPress.Auth;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;

namespace GxPress.Api.ServiceExtensions
{
    public static class AuthenticationExtension
    {
        /// <summary>
        ///     添加Jwt认证授权
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwtAuthentication(this IServiceCollection services,
            IConfiguration configuration)
        {
            var jwtSection = configuration.GetSection("JwtOptions");
            var jwtOptions = new JwtOptions
            {
                Key = jwtSection["Key"],
                Issuer = jwtSection["Issuer"],
                Audience = jwtSection["Audience"],
                Expires = TimeSpan.FromDays(int.Parse(jwtSection["Expires"]))
            };

            services.AddHttpContextAccessor();
            services.Configure<JwtOptions>(jwtSection);
            services.TryAddSingleton<ILoginContext, LoginContext>();

            ////添加授权
            //services.AddAuthorization(options =>
            //{
            //    options.AddPolicy("Permission", policy =>
            //    {
            //        policy.Requirements.Add(new PermissionRequirement());
            //    });
            //});
            //services.AddSingleton<IAuthorizationHandler, PermissionHandler>();

            //添加认证
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ClockSkew = TimeSpan.FromMinutes(5),
                        ValidIssuer = jwtOptions.Issuer,
                        ValidAudience = jwtOptions.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key))
                    };
                });

            return services;
        }

        /// <summary>
        ///     使用jwt认证
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseJwtAuthorization(this IApplicationBuilder app)
        {
            app.UseAuthentication();
            app.UseAuthorization();
            return app;
        }
    }
}