﻿using Radial.Web;
using Radial.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WishStore.WebSite.Areas.Admin
{


    /// <summary>
    /// Privilege Authorize Attribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class PrivilegeAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="PrivilegeAuthorizeAttribute"/> class.
        /// </summary>
        public PrivilegeAuthorizeAttribute() { }

        /// <summary>
        /// Initializes a new instance of the <see cref="PrivilegeAuthorizeAttribute" /> class.
        /// </summary>
        /// <param name="privilege">The privilege.</param>
        public PrivilegeAuthorizeAttribute(int privilege)
        {
            Privilege = privilege;
        }

        private int? Privilege { get; set; }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var op = OperatorContext.Current;

            if (op == null)
            {
                filterContext.Result = new RedirectResult(OperatorContext.GetSignInUrl());
                return;
            }

            if (Privilege != null && !op.IsPermitted(Privilege.Value))
            {
                string redirectUrl = "~/admin";
                if (filterContext.HttpContext.Request.UrlReferrer != null)
                    redirectUrl = filterContext.HttpContext.Request.UrlReferrer.ToString();

                filterContext.Result = new AlertResult("对不起，你的权限不足，无法使用此项功能", redirectUrl);

                return;
            }

        }
    }
}