using CallCenterApi.Common;
using CallCenterApi.Interface.Models.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace CallCenterApi.Interface
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //clq 增加异常日志记录 自定义 HandleErrorAttribute
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        }
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            var context = app.Context;
            if (context == null) throw new ArgumentNullException("context");
            var token = context.Request["token"];
            if (string.IsNullOrWhiteSpace(token)) return;
            try
            {
                //获取缓存
                var dict = CacheHelper.Get(token);
                if (dict == null) return;
                Cache.Models.CurrentUserInfo userData = null;
                //获取FormsAuthenticationTicket对象
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
                if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
                    userData = (new JavaScriptSerializer()).Deserialize<Cache.Models.CurrentUserInfo>(ticket.UserData); //还原用户数据
                if (ticket != null && userData != null)
                    context.User = new FormsPrincipal<Cache.Models.CurrentUserInfo>(ticket, userData);//重新给context.User赋值。
            }
            catch { /* 有异常也不要抛出，防止攻击者试探。 */ }
        }


    }
}
