using System.Web.Helpers;

namespace System.Web.Mvc
{
    /// <summary>
    /// Represents an attribute that is used to prevent forgery of a request when using .
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ValidateAngularAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        internal Action<string, string> ValidateAction { get; private set; }
        private const string XsrfHeaderName = "X-XSRF-TOKEN";

        public ValidateAngularAntiForgeryTokenAttribute()
            : this(AntiForgery.Validate)
        {
        }

        internal ValidateAngularAntiForgeryTokenAttribute(Action<string, string> validateAction)
        {
            ValidateAction = validateAction;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");

            var cookieToken = GetCookieValue(filterContext.HttpContext.Request, AntiForgeryConfig.CookieName);
            var formToken = filterContext.HttpContext.Request.Headers.Get(XsrfHeaderName);

            ValidateAction(cookieToken, formToken);
        }

        private static string GetCookieValue(HttpRequestBase request, string cookieName)
        {
            var cookie = request.Cookies.Get(cookieName);
            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
                return null;

            return cookie.Value;
        }
    }
}