public IActionResult Confirmation(int itemId, int distributorId, int quantity)
        {
            if (quantity <= 0)
            {
                quantity = 1;
            }

            var distributor = _context.Distributors.Find(distributorId);
            var item        = _context.Items.Find(itemId);
            var user        = _context.Users.Find(Convert.ToInt32(CookieUtil.GetCookie(Request, CookieUtil.USER_ID_KEY)));

            if (user == null)
            {
                return(NotFound());
            }

            var receipt = new Receipt();

            receipt.Distributor = distributor;
            receipt.Item        = item;
            receipt.Tax         = Math.Round((0.13 * ((item.MRP * quantity) + distributor.ShipPrice)), 2);
            receipt.ReceiveDate = DateTime.Now.AddDays(distributor.TimeToShip);
            receipt.Date        = DateTime.Now;
            receipt.Quantity    = quantity;
            receipt.Total       = Math.Round((receipt.Tax + (item.MRP * quantity) + distributor.ShipPrice), 2);
            receipt.User        = user;

            _context.Receipts.Add(receipt);

            _context.SaveChanges();

            return(View("Confirmation", receipt));
        }
        public async Task <IActionResult> OrderForm()
        {
            if (CookieUtil.GetCookie(Request, CookieUtil.USER_ID_KEY) == null)
            {
                return(this.NotLoggedIn());
            }

            var distributor = await _context
                              .Distributors
                              .ToListAsync();

            var item = await _context
                       .Items
                       .ToListAsync();


            var itemDistributorList = new ItemDistributorList();

            itemDistributorList.DistributorId = distributor;

            itemDistributorList.ItemId = item;


            return(View(itemDistributorList));
        }
Example #3
0
        public async Task <IActionResult> ResetPasswordForm(string _newPassword, string _confirmPassword)
        {
            if (_newPassword == null || _newPassword.Trim() == "")
            {
                ViewBag.ErrorMessage = "Password is empty";
            }
            if (_newPassword != _confirmPassword)
            {
                ViewBag.ErrorMessage = "Passwords do not match";
            }
            if (ViewBag.ErrorMessage != null)
            {
                return(View());
            }
            var credentials = _context.Credentials.Find(CookieUtil.GetCookie(Request, CookieUtil.CREDENTIALS_ID_KEY).ToInt());

            if (credentials == null)
            {
                return(NotFound());
            }
            credentials.Password = _newPassword;

            await _context.SaveChangesAsync();

            CookieUtil.DeleteCookie(Response, CookieUtil.CREDENTIALS_ID_KEY);
            return(RedirectToAction("LoginForm", "Signin"));
        }
Example #4
0
        public IActionResult Index() // dafault index returns default graph
        {
            if (CookieUtil.GetCookie(Request, CookieUtil.USER_ID_KEY) == null)
            {
                return(this.NotLoggedIn());
            }

            List <Item> items = _context.Items.ToList();
            List <Sale> sales = _context.Sales.ToList();

            ViewBag.Items = items;
            if (sales.Count == 0) // if no data do not call sales data
            {
                ViewBag.Graph = new Graph()
                {
                    name = "Item Sales Every  Week", shared = "true", xTitle = "Date", xValueFormatString = "DD MMM YYYY", yTitle = "Number Of Units Sold"
                };
            }
            else
            {
                ViewBag.Graph = SalesByWeekGraph(items, sales.Min(s => s.Date), sales.Max(s => s.Date), 1);
            }
            ViewBag.GraphTypeList = graphTypeList;
            return(View());
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var provider = ServiceExtension.Get <IActionDescriptorCollectionProvider>();
            var desc1    = (context.ActionDescriptor as ControllerActionDescriptor);
            var desc2    = provider.ActionDescriptors.Items.Cast <ControllerActionDescriptor>()
                           .Where(t => t.MethodInfo.GetCustomAttribute <ActionAttribute>() != null && t.DisplayName == desc1.DisplayName).FirstOrDefault();
            var desc3  = desc2 ?? desc1;
            var action = desc3.MethodInfo.GetCustomAttribute <ActionAttribute>();

            if (action != null)
            {
                var actions = ServiceExtension.Get <IPermissionService>();
                if (actions != null && !actions.HasPermission(context, desc3.Id))
                {
                    return;
                }
            }

            if (desc3.ActionName == "Index" && desc3.ControllerName == "Home")
            {
                if (User.Identity.IsAuthenticated)
                {
                    string path = HttpContext.Request.Query["from"];
                    if (string.IsNullOrEmpty(path))
                    {
                        path = CookieUtil.GetCookie(Constants.LAST_LOGIN_PATH);
                    }
                    if (!string.IsNullOrEmpty(path) && path != "/")
                    {
                        context.Result = Redirect(path);
                    }
                }
            }
            base.OnActionExecuting(context);
        }
        public BackstageCookie GetUserCook()
        {
            string          cookie = DataProtectionUtil.UnProtect(CookieUtil.GetCookie(Constants.WEBSITE_AUTHENTICATION_SCHEME));
            BackstageCookie back   = new BackstageCookie();

            back = cookie.GetModel <BackstageCookie>();
            return(back);
        }
Example #7
0
 public static bool Has(string url, IEnumerable <string> urlList)
 {
     if (CookieUtil.GetCookie <int>(GlobalVar.CookieName, GlobalVar.Level) < GlobalVar.MaxLevel)
     {
         return(urlList.Any(a => string.Equals(a.Trim().Trim('/'), url.Trim().Trim('/'), StringComparison.CurrentCultureIgnoreCase)));
     }
     return(true);
 }
        public MyResult <object> Login(BackstageUserAdd model)
        {
            MyResult result      = new MyResult();
            string   sessionCode = string.Empty;

            try
            {
                var code = CookieUtil.GetCookie(Constants.WEBSITE_VERIFICATION_CODE);
                if (code != null)
                {
                    sessionCode = DataProtectionUtil.UnProtect(code);
                }
            }
            catch (Exception ex)
            {
                LogUtil <AccountService> .Error(ex.Message);
            }
            if (model.ErrCount >= 3)
            {
                if (!model.VerCode.ToString().ToLower().Equals(sessionCode.ToLower()))
                {
                    return(result.SetStatus(ErrorCode.NotFound, "验证码输入不正确!"));
                }
            }

            BackstageUser account = this.First <BackstageUser>(t => t.LoginName == model.LoginName);

            if (account == null)
            {
                return(result.SetStatus(ErrorCode.NotFound, "账号不存在!"));
            }
            string pwd = SecurityUtil.MD5(model.Password);

            if (!account.Password.Equals(pwd, StringComparison.OrdinalIgnoreCase))
            {
                return(result.SetStatus(ErrorCode.InvalidPassword));
            }
            switch (account.AccountStatus)
            {
            case (int)AccountStatus.Disabled:
                return(result.SetStatus(ErrorCode.AccountDisabled, "账号不可用!"));
            }

            account.LastLoginTime = DateTime.Now;
            account.LastLoginIp   = "";//MvcHelper.ClientIP;
            this.Update(account, true);
            MvcIdentity identity = new MvcIdentity(account.Id, account.LoginName, account.LoginName, account.Email, (int)account.RoleId, null, account.LastLoginTime);

            identity.Login(Constants.WEBSITE_AUTHENTICATION_SCHEME, x =>
            {
                x.Expires  = DateTime.Now.AddHours(5);//滑动过期时间
                x.HttpOnly = true;
            });

            return(result);
        }
        /*
         * The UserReceipts method was created by Richard Perocho
         */
        public IActionResult UserReceipts()
        {
            if (CookieUtil.GetCookie(Request, CookieUtil.USER_ID_KEY) == null)
            {
                return(this.NotLoggedIn());
            }

            return(View(_context.Receipts
                        .Include(r => r.Item)
                        .Where(r => r.User.Id == Convert.ToInt32(CookieUtil.GetCookie(Request, CookieUtil.USER_ID_KEY))).ToList()));
        }
Example #10
0
        public IActionResult SecurityQuestionForm()
        {
            var credentials = _context.Credentials.Find(CookieUtil.GetCookie(Request, CookieUtil.CREDENTIALS_ID_KEY).ToInt());

            if (credentials == null)
            {
                return(Content("something went wrong"));
            }
            ViewBag.SecurityQuestion = credentials.SecurityQuestion;
            return(View());
        }
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     if (!filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any())
     {
         if (!string.IsNullOrEmpty(CookieUtil.GetCookie(GlobalVar.CookieName)))
         {
             var userId   = CookieUtil.GetCookie <int>(GlobalVar.CookieName, GlobalVar.UserId);
             var userName = CookieUtil.GetCookie(GlobalVar.CookieName, GlobalVar.UserName);
             var level    = CookieUtil.GetCookie <int>(GlobalVar.CookieName, GlobalVar.Level);
             var token    = CookieUtil.GetCookie(GlobalVar.CookieName, GlobalVar.AuthToken);
             if (userId > 0 && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(token))
             {
                 var userKey     = CacheKey.GetUserKey(userId);
                 var cacheClient = DependencyResolver.Current.GetService <ICache>();
                 var userInfo    = cacheClient.Get <UserInfo>(userKey);
                 var expiresAt   = DateTime.Now.AddMinutes(cacheMinute);
                 if (userInfo != null && userInfo.UserName == userName && userInfo.Token == token && cacheClient.ExpireAt(userKey, expiresAt))
                 {
                     var values = filterContext.RouteData.Values;
                     var url    = string.Format("/{0}/{1}", values["controller"] as string, values["action"] as string);
                     if (level >= GlobalVar.MaxLevel ||
                         pubUrls.Any(a => string.Equals(a, url, StringComparison.CurrentCultureIgnoreCase)) ||
                         userInfo.Urls.Any(a => string.Equals(a, url, StringComparison.CurrentCultureIgnoreCase)))
                     {
                         return;
                     }
                 }
             }
         }
         if (filterContext.HttpContext.Request.HttpMethod == "GET")
         {
             filterContext.Result = new ContentResult()
             {
                 Content     = string.Format("<script>window.location='{0}';</script>", UrlVar.User_SignIn),
                 ContentType = "text/html; charset=utf-8"
             };
         }
         else
         {
             var mes = GrainManage.Message.CacheMessage.Get <StatusCode>(s => s.IdentityFailed);
             filterContext.Result = new NewtonsoftJsonResult {
                 Data = new BaseOutput {
                     code = mes.Code, msg = mes.Description, data = UrlVar.User_SignIn
                 }
             };
         }
     }
 }
Example #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (CookieUtil.GetCookie("tUserCookie") != "")
                {
                    txtUser.Text = CookieUtil.GetCookie("tUserCookie");
                }
                CookieUtil.UpdateCookie(loginnameCookie, "");
                CookieUtil.UpdateCookie(loginidCookie, "");
                CookieUtil.RemoveCookie(loginnameCookie);
                CookieUtil.RemoveCookie(loginidCookie);
            }

            InitLanguage();
        }
 public IActionResult Index()
 {
     if (User.Identity.IsAuthenticated)
     {
         string path = HttpContext.Request.Query["from"];
         if (string.IsNullOrEmpty(path))
         {
             path = CookieUtil.GetCookie(Constants.LAST_LOGIN_PATH);
         }
         if (!string.IsNullOrEmpty(path) && path != "/")
         {
             return(Redirect(System.Web.HttpUtility.UrlDecode(path)));
         }
     }
     return(View());
 }
Example #14
0
        public ActionResult goOrder()
        {
            GoOrder goOrder = new GoOrder();

            JavaScriptSerializer jss = new JavaScriptSerializer();
            string    car            = CookieUtil.GetCookie("ShoppingCartObj");
            ShopCarVM carList        = jss.Deserialize <ShopCarVM>(car);

            if (carList != null)
            {
                ProductBll bll = new ProductBll();
                List <CarProductDetail> list = new List <CarProductDetail>();
                foreach (var item in carList.List)
                {
                    CarProductDetail m;
                    int i = -1;
                    if (int.TryParse(item.Attrs, out i))
                    {
                        m = bll.GetProDetail(item.ID, i, item.Type);
                    }
                    else
                    {
                        m = bll.GetProDetail(item.ID, -1, item.Type);
                    }
                    if (m != null)
                    {
                        m.Qty      = int.Parse(item.Qty);
                        m.lastAttr = item.Attrs;
                        list.Add(m);
                    }
                }
                //car list
                goOrder.carProList = list;
                //会员等级
                string          uid        = Session["memberID"].ToString();
                MemberLevelBLL  memLeveBll = new MemberLevelBLL();
                DAO.MemberLevel memLevel   = memLeveBll.GetLeveByUid(uid);
                goOrder.userLevel = memLevel;
                //

                return(View(goOrder));
            }
            else
            {
                return(RedirectToAction("index", "Car"));
            }
        }
Example #15
0
        /// <summary>
        /// 登陆
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            if (User.Identity.IsAuthenticated)
            {
                //return RedirectToAction("Index", "Home");
            }
            var model = new LogOnModel
            {
                UserName = HttpUtility.UrlDecode(CookieUtil.GetCookie(AppConst.LoginUserNameCookieName)),
                Password = HttpUtility.UrlDecode(CookieUtil.GetCookie(AppConst.LoginUserCookiePwd)),
            };

            if (!string.IsNullOrEmpty(model.Password))
            {
                model.Password   = DESHelper.ToDESDecrypt(model.Password, AppConst.EncryptKey);
                model.RememberMe = true;
            }
            return(View(model));
        }
Example #16
0
 /// <summary>
 /// 获取当前用户ID
 /// </summary>
 /// <returns></returns>
 public static int GetCurrentUserID()
 {
     return(ExceptionUtil.LogException(() =>
     {
         string sign = CookieUtil.GetCookie(_CurrentUserCookieSign_Key);
         string userStr = CookieUtil.GetCookie(_CurrentUserID_Key);
         if (sign.IsNullOrEmptyWhiteSpace() || userStr.IsNullOrEmptyWhiteSpace())
         {
             return -99;
         }
         var decodeString = DESProviderUtil.Decode(userStr, GetCurrentUserSignKey);
         string checkSign = (userStr + GetCurrentUserCookieSignKey).ToMd5();
         if (sign.Equals(checkSign))
         {
             return decodeString.ToSafeInt32(-99);
         }
         return -99;
     }, memberName: "PublicUtil-GetCurrentUserID"));
 }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var values = filterContext.RouteData.Values;
            var url    = string.Format("/{0}/{1}", values["controller"] as string, values["action"] as string);

            if (urlList.Any(s => string.Equals(s, url, StringComparison.CurrentCultureIgnoreCase)))
            {
                var       headers = filterContext.HttpContext.Request.Headers;
                ActionLog model   = new ActionLog();
                model.Path      = HttpUtility.UrlDecode(filterContext.HttpContext.Request.Url.AbsolutePath, Encoding.UTF8);
                model.ClientIP  = HttpUtil.RequestHostAddress;
                model.UserName  = CookieUtil.GetCookie(GlobalVar.CookieName, GlobalVar.UserName);
                model.Method    = filterContext.HttpContext.Request.HttpMethod;
                model.Para      = HttpUtil.GetInputPara();
                model.Level     = CookieUtil.GetCookie <int>(GlobalVar.CookieName, GlobalVar.Level);
                model.StartTime = DateTime.Now;
                model.Id        = LogService.AddActionLog(model);
                headers.Set(name, string.Format("{0},{1}", model.Id.ToString(), model.StartTime.ToString("yyyy-MM-dd HH:mm:ss")));
            }
        }
Example #18
0
        public IActionResult Index()
        {
            IndexView model = new IndexView(Context.HttpContext);

            if (User.Identity.IsAuthenticated)
            {
                string accountSource = CookieUtil.GetCookie(AccountSource.LoginSource, User);
                if (accountSource == AccountSource.Git)
                {
                    //直接返回cookie中的结果,并建立session
                    model.User    = _signService.GetGitUser();
                    model.IsLogin = true;
                }
            }
            else
            {
                model.IsLogin = false;
            }
            return(View(model));
        }
Example #19
0
        public ActionResult GetCar()
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string    car            = CookieUtil.GetCookie("ShoppingCartObj");
            ShopCarVM carList        = jss.Deserialize <ShopCarVM>(car);

            if (carList != null)
            {
                ProductBll bll = new ProductBll();
                List <CarProductDetail> list = new List <CarProductDetail>();
                foreach (var item in carList.List)
                {
                    CarProductDetail m;
                    int i = -1;
                    if (item.Qty != null)
                    {
                        if (int.TryParse(item.Attrs, out i))
                        {
                            m = bll.GetProDetail(item.ID, i, item.Type);
                        }
                        else
                        {
                            m = bll.GetProDetail(item.ID, -1, item.Type);
                        }
                        if (m != null)
                        {
                            //m.Qty = int.Parse(item.Qty);
                            //暂时限定所有商品只能购买一件
                            m.Qty      = 1;
                            m.lastAttr = item.Attrs;
                            list.Add(m);
                        }
                    }
                }
                return(View(list));
            }
            else
            {
                return(View());
            }
        }
Example #20
0
        public async Task <UserView> SigninByGit(GitSignInPara data)
        {
            UserView user = new UserView();

            if (User.Identity.IsAuthenticated)
            {
                string accountSource = CookieUtil.GetCookie(AccountSource.LoginSource, User);
                if (accountSource == AccountSource.Git)
                {
                    //直接返回cookie中的结果,并建立session
                    user = SignInService.GetGitUser();
                }
            }
            else
            {
                //没有授权 先获取授权,插入自己的库,再加cookie
                user = await SignInService.OauthFromGit(data);
            }

            return(user);
        }
Example #21
0
        public IActionResult SecurityQuestionForm(string _answer)
        {
            var credentials = _context.Credentials.Find(CookieUtil.GetCookie(Request, CookieUtil.CREDENTIALS_ID_KEY).ToInt());

            if (credentials == null)
            {
                return(Content("something went wrong"));
            }
            if (_answer == null || _answer.Trim() == "")
            {
                ViewBag.ErrorMessage = "Enter an answer";
            }
            else if (_answer != credentials.SecurityAnswer)
            {
                ViewBag.ErrorMessage = "Answers did not match";
            }

            if (ViewBag.ErrorMessage != null)
            {
                ViewBag.SecurityQuestion = credentials.SecurityQuestion;
                return(View());
            }
            return(RedirectToAction("ResetPasswordForm"));
        }
Example #22
0
        public IActionResult Index(GraphForm graphForm)
        {
            if (CookieUtil.GetCookie(Request, CookieUtil.USER_ID_KEY) == null) // unable to open unless signed in
            {
                return(this.NotLoggedIn());
            }

            if (graphForm.MinDate == null || graphForm.MaxDate == null || graphForm.MaxDate < graphForm.MinDate || graphForm.MinDate > graphForm.MaxDate) // form validation
            {
                ModelState.AddModelError("MinDate", "MinDate must be before MaxDate");
                ModelState.AddModelError("MaxDate", "MinDate must be before MaxDate");
            }
            if (graphForm.NumWeeks == null || graphForm.NumWeeks <= 0)
            {
                ModelState.AddModelError("NumWeeks", "Must specify how many weeks per DataPoint");
            }
            if (graphForm.ChosenItems.Count(c => c) == 0)
            {
                ModelState.AddModelError("ChosenItems", "Must Select at least 1 item");
            }
            if (!ModelState.IsValid) // if invalid return null graph
            {
                List <Item> items1 = _context.Items.ToList();
                List <Sale> sales1 = _context.Sales.ToList();
                ViewBag.Items         = items1;
                ViewBag.Graph         = SalesByWeekGraph(items1, sales1.Min(s => s.Date), sales1.Max(s => s.Date), 1);
                ViewBag.GraphTypeList = graphTypeList;
                return(View());
            }

            List <Item> items         = _context.Items.ToList(); // obtain specific info for graph
            List <Sale> sales         = _context.Sales.ToList();
            List <Item> selectedItems = new List <Item>();

            for (int i = 0; i < items.Count; i++)
            {
                if (graphForm.ChosenItems[i])
                {
                    selectedItems.Add(items[i]);
                }
            }

            if (graphForm.Type == graphTypeList[0]) // select graph type based on given
            {
                ViewBag.Graph = SalesByWeekGraph(selectedItems, graphForm.MinDate, graphForm.MaxDate, (int)(graphForm.NumWeeks ?? 1));
            }
            else if (graphForm.Type == graphTypeList[1])
            {
                ViewBag.Graph = TotalSalesByWeekGraph(selectedItems, graphForm.MinDate, graphForm.MaxDate, (int)(graphForm.NumWeeks ?? 1));
            }
            else if (graphForm.Type == graphTypeList[2])
            {
                ViewBag.Graph = ProfitByWeekGraph(selectedItems, graphForm.MinDate, graphForm.MaxDate, (int)(graphForm.NumWeeks ?? 1));
            }
            else if (graphForm.Type == graphTypeList[3])
            {
                ViewBag.Graph = SalesGrowthByWeekGraph(selectedItems, graphForm.MinDate, graphForm.MaxDate, (int)(graphForm.NumWeeks ?? 1));
            }

            ViewBag.Items         = items;
            ViewBag.GraphTypeList = graphTypeList;
            return(View());
        }
Example #23
0
        public ActionResult goOrder()
        {
            GoOrder goOrder          = new GoOrder();
            string  UID              = Session["memberID"].ToString();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string    car            = CookieUtil.GetCookie("ShoppingCartObj");
            ShopCarVM carList        = jss.Deserialize <ShopCarVM>(car);

            if (carList != null)
            {
                ProductBll bll = new ProductBll();
                List <CarProductDetail> list = new List <CarProductDetail>();
                foreach (var item in carList.List)
                {
                    CarProductDetail m;
                    int i = -1;
                    if (item.Qty != null)
                    {
                        if (int.TryParse(item.Attrs, out i))
                        {
                            m = bll.GetProDetail(item.ID, i, item.Type);
                        }
                        else
                        {
                            m = bll.GetProDetail(item.ID, -1, item.Type);
                        }
                        if (m != null)
                        {
                            //m.Qty = int.Parse(item.Qty);
                            //暂时限定所有商品只能购买一件
                            m.Qty      = 1;
                            m.lastAttr = item.Attrs;
                            list.Add(m);

                            List <DAO.OrderProList> orderPlist = bll.GetOrderIs(UID, m.proDetail.ID);
                            foreach (var orderItem in orderPlist)
                            {
                                bool isC = bll.GetCrowdFunding(orderItem.ProductID.ToString());
                                if (isC)
                                {
                                    this.Response.Write(" <script language=javascript>alert('您的订单已有众筹产品,产品限购一个!如未支付请直接支付');window.window.location.href='/Product/getCar';</script> ");

                                    return(View("~/Views/Product/getCar.cshtml"));
                                }
                            }

                            if ((double)m.proDetail.Price == 0.01)
                            {
                                if (orderPlist != null)
                                {
                                    foreach (var orderItem in orderPlist)
                                    {
                                        if ((double)orderItem.Price == 0.01)
                                        {
                                            this.Response.Write(" <script language=javascript>alert('您的订单已经有此产品,活动产品限购一个!如未支付请直接支付');window.window.location.href='/Product/getCar';</script> ");

                                            return(View("~/Views/Product/getCar.cshtml"));
                                        }
                                    }
                                }
                                //this.Response.Write(" <script language=javascript>alert('您已经购买过活动产品');window.window.location.href='WebForm2.aspx';</script> ");
                            }
                        }
                    }
                }
                //car list
                goOrder.carProList = list;
                //会员等级
                string          uid        = Session["memberID"].ToString();
                MemberLevelBLL  memLeveBll = new MemberLevelBLL();
                DAO.MemberLevel memLevel   = memLeveBll.GetLeveByUid(uid);
                goOrder.userLevel = memLevel;
                return(View(goOrder));
            }
            else
            {
                return(RedirectToAction("GetCar", "Product"));
            }
        }
Example #24
0
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            AuthorizationPolicy effectivePolicy = Policy;

            if (effectivePolicy == null)
            {
                if (PolicyProvider == null)
                {
                    throw new InvalidOperationException("An AuthorizationPolicy cannot be created without a valid instance of IAuthorizationPolicyProvider.");
                }
                effectivePolicy = await AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData);
            }
            if (effectivePolicy != null)
            {
                MvcPrincipal newPrincipal  = null;
                string       currentScheme = effectivePolicy.AuthenticationSchemes.FirstOrDefault();
                if (!string.IsNullOrEmpty(currentScheme))
                {
                    if (!(context.HttpContext.User.Identity is MvcIdentity) || !context.HttpContext.User.Identity.IsAuthenticated)
                    {
                        string cookie = CookieUtil.GetCookie(currentScheme, true);
                        if (!string.IsNullOrEmpty(cookie))
                        {
                            try
                            {
                                string      value    = DataProtectionUtil.UnProtect(cookie);
                                MvcIdentity identity = JsonExtension.GetModel <MvcIdentity>(value, "");
                                if (identity != null)
                                {
                                    newPrincipal = identity.GetPrincipal();
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        newPrincipal = (context.HttpContext.User as MvcPrincipal);
                    }
                }
                if (newPrincipal == null)
                {
                    context.HttpContext.User = MvcIdentity.Instance.GetPrincipal();
                }
                else
                {
                    context.HttpContext.User = newPrincipal;
                }
                if (!context.Filters.Any((IFilterMetadata item) => item is IAllowAnonymousFilter))
                {
                    if (context.HttpContext.User.Identity.IsAuthenticated)
                    {
                        if (AuthorizeFilter == null)
                        {
                            AuthorizeFilter = ServiceProviderServiceExtensions.GetService <IAuthorizeFilter>(context.HttpContext.RequestServices);
                        }
                        if (AuthorizeFilter != null)
                        {
                            await AuthorizeFilter.OnAuthorizedAsync(context, currentScheme);
                        }
                    }
                    else
                    {
                        context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
                    }
                }
            }
        }