using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;

namespace BasicREST.Filters
{
    public class BasicAuthorizationAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authorizationHeader = actionContext.Request.Headers.Authorization;
            if (authorizationHeader != null && authorizationHeader.Scheme.ToLower() == "basic" && !string.IsNullOrEmpty(authorizationHeader.Parameter))
            {
                var credentials = Encoding.GetEncoding("iso-8859-1").GetString(Convert.FromBase64String(authorizationHeader.Parameter)).Split(':');
                var username = credentials[0];
                var password = credentials[1];
                if (username == "pawel" && password == "tajne")
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("pawel"), new string[] { });
                    return;
                }
            }

            actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add("WWW-Authenticate", "BASIC realm='RESTful test'");
        }
    }
}