using System;
using System.Text;
using System.Web;
using System.Net;
using System.Security.Principal;

namespace ProfitGroup.SampleService.Core.Middlewares
{
    public class BasicAuthMiddleware : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += OnAuthenticateRequest;
        }

        public void Dispose()
        {

        }

        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;
            string authHeader = context.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Basic"))
            {
                string encodedCredentials = authHeader.Substring("Basic".Length).Trim();
                byte[] credentialsBytes = Convert.FromBase64String(encodedCredentials);
                string credentials = Encoding.ASCII.GetString(credentialsBytes);
                string[] usernamePassword = credentials.Split(':');

                if (usernamePassword.Length == 2)
                {
                    string username = usernamePassword[0];
                    string password = usernamePassword[1];

                    if (IsUserValid(username, password))
                    {
                        context.User = new GenericPrincipal(new GenericIdentity(username), null);
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"Your Realm\"");
                        context.Response.End();
                    }
                }
            }
        }

        private bool IsUserValid(string username, string password)
        {
            return username == "111" && password == "111";
        }
    }
}