Пример #1
0
        public ActionResult Index(int logInDefault = 0)
        {
            //获取该用户拥有的相关模块
            var cookie = Request.Cookies.Get(TianYuConsts.SystemLoginCookieName);

            var menuViewModel = CacheHelper.Get <IEnumerable <SystemMenuRoleViewModel> >(TianYuConsts.GetLoginUserMenuCacheKey(cookie.Value));
            //读取一级菜单
            var oneLevelMenu = menuViewModel.Where(x => x.Level == 1).OrderBy(x => x.MenuSort).ToList();

            ViewBag.OneLevelMenu = oneLevelMenu;

            if (logInDefault == 0 && oneLevelMenu != null)
            {
                logInDefault = oneLevelMenu.FirstOrDefault().Id;
            }
            ViewBag.Refres = logInDefault;

            //读取一级以下菜单
            ViewBag.OtherLevelMenuHtml = GetSubMenuHtml(menuViewModel.ToList(), logInDefault);

            //ViewBag.LogoutUrl = ConfigHelper.GetAppsettingValue(TianYuConsts.SystemManagerLogoutDomain + "/Home/Login");

            var loginInfo = CacheHelper.Get <SystemLoginUserInfo>(TianYuConsts.GetLoginUserInfoCacheKey(cookie.Value));

            return(View(loginInfo));
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(MvcIgnoreLoginAttribute), true).Any() || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(MvcIgnoreLoginAttribute), true).Any())
            {
                base.OnActionExecuting(filterContext);
                return;
            }
            //未登录时,跳转到登录
            var cookie = CookieHelper.GetCookieValue(TianYuConsts.SystemLoginCookieName);

            var loginInfoCacheKey = TianYuConsts.GetLoginUserInfoCacheKey(cookie);

            var loginInfo = CacheHelper.Get <SystemLoginUserInfo>(loginInfoCacheKey);

            if (loginInfo == null)
            {
                var loginUrl = "/Home/Login";

                var request = filterContext.RequestContext.HttpContext.Request;
                //取消回调地址,因使用首页框架内嵌页面,此处回调只能回调首页
                //var returnUrl = request.Url.OriginalString;
                var returnUrl = string.Format("{0}://{1}/Home/Index", request.Url.Scheme, request.Url.Authority);

                var redirect = new RedirectResult(string.Format("{0}?redirectUrl={1}", loginUrl,
                                                                WebUtility.UrlEncode(returnUrl)));
                filterContext.Result = redirect;
                return;
            }

            base.OnActionExecuting(filterContext);
            return;
        }
Пример #3
0
        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="sessionid">登录会话Id</param>
        /// <returns></returns>
        private BusinessBaseViewModel <object> ValidateLogin(string sessionid, HttpActionContext actionContext)
        {
            var response = new BusinessBaseViewModel <object> {
                Status = ResponseStatus.Fail
            };

            if (sessionid.IsNullOrWhiteSpace())
            {
                response.Status = ResponseStatus.UnSessionIdParamsError;
                return(response);
            }
            string deviceNo          = string.Empty;
            string sessionidCacheKey = TianYuConsts.GetSessionIdCacheKey(sessionid);
            var    userGroup         = Cache.CacheHelper.Get <SystemLoginUserInfo>(sessionidCacheKey);

            if (userGroup.IsNull())
            {
                var model = LoginSessionDataHelper.GetSessionInfoModel(sessionid);
                if (model.IsNull())
                {
                    response.Status = ResponseStatus.SessionIdError;
                    return(response);
                }
                else
                {
                    deviceNo = model.DeviceNo;
                }
            }
            else
            {
                // deviceNo = userGroup.DeviceNo;
            }
            string ticket = actionContext.Request.Headers.Authorization.Parameter;

            if (ticket.IsNullOrWhiteSpace())
            {
                response.Status = ResponseStatus.UnAuthorityError;
                return(response);
            }
            //解密票据
            string key = TianYuConsts.GetTicketCacheKey(ticket);
            var    ticketDetailsModel = CacheHelper.Get <AuthenticationTicketDetailsModel>(key);

            if (ticketDetailsModel.IsNull())
            {
                response.Status = ResponseStatus.AuthenticationTicketTimeOut;
                return(response);
            }
            if (ticketDetailsModel.ClientType != AuthClientType.SamllApp.GetEnumDescription() && ticketDetailsModel.DeviceNo != deviceNo)
            {
                response.Status       = ResponseStatus.SessionIdOtherLogin;
                response.BusinessData = deviceNo;
                return(response);
            }
            response.BusinessData = userGroup;
            response.Status       = ResponseStatus.Success;

            return(response);
        }
        internal void AddAuthenticationTicketDetails(AuthenticationTicketDetailsModel model)
        {
            if (model.IsNull())
            {
                return;
            }
            StringBuilder builder = new StringBuilder();

            builder.Append("INSERT INTO AuthenticationTicketDetails(TicketId,Ticket,TicketAppID,TicketSecond,LastRefreshDate,DeviceNo,ClientType,CreateTime)");
            builder.Append("VALUES(@TicketId,@Ticket,@TicketAppID,@TicketSecond,@LastRefreshDate,@DeviceNo,@ClientType,@CreateTime)");
            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter()
                {
                    ParameterName = "@TicketId", Value = model.TicketId
                },
                new SqlParameter()
                {
                    ParameterName = "@Ticket", Value = model.Ticket
                },
                new SqlParameter()
                {
                    ParameterName = "@TicketAppID", Value = model.TicketAppID
                },
                new SqlParameter()
                {
                    ParameterName = "@TicketSecond", Value = model.TicketSecond
                },
                new SqlParameter()
                {
                    ParameterName = "@LastRefreshDate", Value = model.LastRefreshDate
                },
                new SqlParameter()
                {
                    ParameterName = "@DeviceNo", Value = model.DeviceNo
                },
                new SqlParameter()
                {
                    ParameterName = "@ClientType", Value = model.ClientType
                },
                new SqlParameter()
                {
                    ParameterName = "@CreateTime", Value = model.CreateTime
                },
                //new SqlParameter(){  ParameterName="AppSecret",Value=model.AppSecret},
            };
            bool flag = ExecuteNonQuery(builder.ToString(), parameters) > 0;

            if (flag)
            {
                string key = TianYuConsts.GetTicketCacheKey(model.Ticket);
                Cache.CacheHelper.Insert(key, model, 7200);
            }
        }
        /// <summary>
        /// 刷新缓存
        /// </summary>
        /// <param name="token"></param>
        internal void RefreshCache(string token)
        {
            string key   = TianYuConsts.GetTicketCacheKey(token);
            var    model = Cache.CacheHelper.Get <AuthenticationTicketDetailsModel>(key);

            if (model.IsNull())
            {
                return;
            }
            Cache.CacheHelper.Remove(token);
            model.LastRefreshDate = DateTime.Now;
            Cache.CacheHelper.Insert(key, model, 7200);
        }
Пример #6
0
        /// <summary>
        /// 获取登录用户菜单
        /// </summary>
        /// <returns></returns>
        public IEnumerable <SystemMenuRoleViewModel> GetLoginUserMenu(string controllerName = "")
        {
            IEnumerable <SystemMenuRoleViewModel> menuList = null;
            var token = CookieHelper.GetCookieValue(TianYuConsts.SystemLoginCookieName);

            if (!token.IsNullOrWhiteSpace())
            {
                menuList = CacheHelper.Get <IEnumerable <SystemMenuRoleViewModel> >(TianYuConsts.GetLoginUserMenuCacheKey(token));

                if (menuList != null && !controllerName.IsNullOrWhiteSpace())
                {
                    menuList = menuList.Where(x => x.MenuUrl != null && x.MenuUrl.Contains(controllerName)).ToList();
                }
            }
            return(menuList);
        }
Пример #7
0
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public BusinessBaseViewModel <string> Logout()
        {
            var response = new BusinessBaseViewModel <string>()
            {
                Status = ResponseStatus.Fail
            };

            var token = CookieHelper.GetCookieValue(TianYuConsts.SystemLoginCookieName);

            if (!token.IsNullOrWhiteSpace())
            {
                CookieHelper.RemoveCookie(TianYuConsts.SystemLoginCookieName);
                CacheHelper.Remove(TianYuConsts.GetSessionIdCacheKey(token));
            }
            response.Status = ResponseStatus.Success;
            return(response);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(MvcIgnorePowerAttribute), true).Any() || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(MvcIgnorePowerAttribute), true).Any())
            {
                base.OnActionExecuting(filterContext);
                return;
            }
            string areaName       = filterContext.RouteData.DataTokens["area"].IsNull() ? "" : filterContext.RouteData.DataTokens["area"].ToString();
            string controllerName = filterContext.RouteData.Values["controller"].ToString();
            string actionName     = filterContext.RouteData.Values["action"].ToString();
            var    actionUrl      = string.Format("{0}/{1}/{2}", areaName, controllerName, actionName);
            ////未登录时,跳转到登录
            var currCookie = CookieHelper.GetCookieValue(TianYuConsts.SystemLoginCookieName);

            var loginInfoCacheKey = TianYuConsts.GetLoginUserInfoCacheKey(currCookie);


            //if (token.IsNullOrWhiteSpace())
            //{
            //    var loginUrl = ConfigHelper.GetAppsettingValue(TianYuConsts.SystemManagerLoginUrl);
            //    var request = filterContext.RequestContext.HttpContext.Request;
            //    var redirect = new RedirectResult(string.Format("{0}?redirectUrl={1}", loginUrl,
            //        WebUtility.UrlEncode(request.Url.OriginalString)));
            //    filterContext.Result = redirect;
            //    return;
            //}
            var loginInfo = CacheHelper.Get <SystemLoginUserInfo>(loginInfoCacheKey);

            //if (userGroup == null)
            //{
            //    var loginUrl = ConfigHelper.GetAppsettingValue(TianYuConsts.SystemManagerLoginUrl);
            //    var request = filterContext.RequestContext.HttpContext.Request;
            //    var redirect = new RedirectResult(string.Format("{0}?redirectUrl={1}", loginUrl,
            //        WebUtility.UrlEncode(request.Url.OriginalString)));
            //    filterContext.Result = redirect;
            //    return;
            //}
            if (loginInfo == null)
            {
                throw new Exception("没有找到登录用户信息");
            }

            //延长cookie时间
            //      CookieHelper.AppendCookieTime(TianYuConsts.SystemLoginCookieName, 24);

            var cookie = HttpContext.Current.Request.Cookies[TianYuConsts.SystemLoginCookieName];

            cookie.Domain   = ConfigHelper.GetAppsettingValue("CookieDomainName");
            cookie.Expires  = DateTime.Now.AddHours(24);
            cookie.HttpOnly = false;
            cookie.Path     = "/";
            filterContext.HttpContext.Response.Cookies.Add(cookie);

            if (IsPowerAction(actionUrl, loginInfo))
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                var jsonResult = new JsonResult();
                var result     = new BaseResponse()
                {
                    Status       = HttpStatusCode.Unauthorized,
                    ErrorMessage = "您没有访问权限"
                };
                jsonResult.Data = result;
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

                    jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    filterContext.Result           = jsonResult;
                }
                else
                {
                    var redirect = new RedirectResult("/Error/index?msg=" + result.ErrorMessage);
                    filterContext.Result = redirect;
                }


                return;
            }
        }
        internal AuthenticationTicketDetailsModel GetCheckTicket(string token)
        {
            if (token.IsNullOrWhiteSpace())
            {
                return(null);
            }
            string key = TianYuConsts.GetTicketCacheKey(token);
            AuthenticationTicketDetailsModel model = Cache.CacheHelper.Get <AuthenticationTicketDetailsModel>(key);

            if (model.IsNull())
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("SELECT * FROM AuthenticationTicketDetails WHERE Ticket=@Ticket AND LastRefreshDate>@LastRefreshDate");
                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter()
                    {
                        ParameterName = "@Ticket", Value = token
                    },
                    new SqlParameter()
                    {
                        ParameterName = "@LastRefreshDate", Value = DateTime.Now.AddSeconds(-7200)
                    }
                };
                var dt = ExecuteQuery(builder.ToString(), parameters);
                if (!dt.IsNull() && dt.Rows.Count > 0)
                {
                    var row = dt.Rows[0];
                    model = new AuthenticationTicketDetailsModel
                    {
                        ClientType      = row["ClientType"].ToString(),
                        DeviceNo        = row["DeviceNo"].ToString(),
                        LastRefreshDate = row["LastRefreshDate"].ToDateTime(),
                        Ticket          = row["Ticket"].ToString(),
                        TicketId        = Guid.Parse(row["TicketId"].ToString()),
                        TicketAppID     = row["TicketAppID"].ToString(),
                        TicketSecond    = row["TicketSecond"].ToInt(),
                    };
                    builder.Clear();
                    builder.Append("SELECT * FROM ApplocationAuthor WHERE AppId=@AppId");
                    parameters = new SqlParameter[]
                    {
                        new SqlParameter()
                        {
                            ParameterName = "@AppId", Value = model.TicketAppID
                        }
                    };
                    dt = ExecuteQuery(builder.ToString(), parameters);
                    if (!dt.IsNull() && dt.Rows.Count > 0)
                    {
                        model.AppSecret = dt.Rows[0]["AppSecret"].ToString();
                    }
                    Cache.CacheHelper.Insert(key, model, 7200);
                }
                else
                {
                    return(null);
                }
            }
            RefreshCache(token);
            return(model);
        }
Пример #10
0
        /// <summary>
        /// 登录后台
        /// </summary>
        /// <param name="loginName">用户名</param>
        /// <param name="loginPwd">密码</param>
        /// <returns>登录凭据</returns>
        public BusinessBaseViewModel <string> Login(string loginName, string loginPwd)
        {
            var response = new BusinessBaseViewModel <string>()
            {
                Status = ResponseStatus.Fail
            };

            if (loginName.IsNullOrWhiteSpace() || loginPwd.IsNullOrWhiteSpace())
            {
                response.ErrorMessage = "请输入用户名或密码";
                return(response);
            }

            var Staff = _staffRepostory.FirstOrDefault(t => t.LoginName == loginName && t.Status != (int)SystemStaffStatus.Del);

            if (Staff.IsNull())
            {
                response.ErrorMessage = "请输入用户名不存在或密码错误";
                return(response);
            }

            if (Staff.Status == (int)SystemStaffStatus.Stop)
            {
                response.ErrorMessage = "该用户已经被禁用";
                return(response);
            }

            if (Staff.LoginPwd.Equals((loginPwd + Staff.MaskCode).ToMd5(), StringComparison.InvariantCultureIgnoreCase))
            {
                //更新最近登录时间
                Staff.LastLoginTime = DateTime.Now;
                _staffRepostory.Update(Staff, "LastLoginTime");
                _staffRepostory.SaveChanges();

                //生成一个登录凭据
                var sessionIdString = $"admin:login:{loginName}:{Utils.NewGuid()}";
                var sessionId       = DESEncrypt.Encrypt(sessionIdString.ToBase64());

                string sessionKey = TianYuConsts.GetSessionIdCacheKey(sessionId);
                if (CacheHelper.Exists(sessionKey))
                {
                    CacheHelper.Remove(sessionKey);
                }
                //将用户菜单权限缓存到cache
                var menuList = _systemRoleService.FindStaffMenuRole(Staff.Id);

                CacheHelper.Insert(TianYuConsts.GetLoginUserMenuCacheKey(sessionId), menuList, true);

                var buttonList = _systemRoleService.FindStaffRoleNameByStaffId(Staff.Id);

                CacheHelper.Insert(TianYuConsts.GetLoginUserButtonCacheKey(sessionId), buttonList, true);

                var loginUserInfo = new SystemLoginUserInfo
                {
                    Id        = Staff.Id,
                    Eamil     = Staff.Eamil,
                    LoginName = Staff.LoginName,
                    Mobile    = Staff.Mobile,
                    NickName  = Staff.NickName,
                    SectionId = Staff.SectionId,
                    Status    = Staff.Status,
                    Tel       = Staff.Tel
                };
                //存储当前登录用户数据
                CacheHelper.Insert(TianYuConsts.GetLoginUserInfoCacheKey(sessionId), loginUserInfo, DateTime.Now.AddHours(1));

                response.BusinessData = sessionId;
                response.Status       = ResponseStatus.Success;
                return(response);
            }
            else
            {
                response.ErrorMessage = "请输入用户名不存在或密码错误";
                return(response);
            }
        }
Пример #11
0
        /// <summary>
        /// 获取登录用户按钮操作权限
        /// </summary>
        /// <returns></returns>
        public IEnumerable <SystemButtonRoleViewModel> GetLoginAccountButtonRole(int menuId)
        {
            IEnumerable <SystemButtonRoleViewModel> buttonList = null;
            var token = CookieHelper.GetCookieValue(TianYuConsts.SystemLoginCookieName);

            if (!token.IsNullOrWhiteSpace())
            {
                buttonList = CacheHelper.Get <IEnumerable <SystemButtonRoleViewModel> >(TianYuConsts.GetLoginUserButtonCacheKey(token));

                if (menuId != 0)
                {
                    buttonList = buttonList.Where(x => x.MenuId == menuId).ToList();
                }
            }
            return(buttonList);
        }