Ejemplo n.º 1
0
        /// <summary>
        /// 检查用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool CheckLogin(string userName, string password)
        {
            bool validate = false;

            //防止注入
            userName = StringHelp.FilterSql(userName);
            password = StringHelp.FilterSql(password);
            var user = userBll.FirstOrDefault <Sys_User>(x => x.UserNickName.Equals(userName) && x.Password.Equals(password));

            if (user != null)
            {
                //登录成功,添加Session
                SessionManager.Add(ConstString.UserLoginId, user.UserId);
                //验证ip,浏览器
                string IP      = NetworkHelper.GetIp();
                string Browser = NetworkHelper.GetBrowser();
                //查询站内未读消息条数,并加入缓存
                //添加登录日志表,记录登录日志

                int m_guid = (user.UserId + Guid.NewGuid().ToString()).GetHashCode();
                //添加cookie消息
                CookiesManager.Add(ConstString.SysUserLoginGuid, user.UserId, DateTime.Now.AddDays(1));

                validate = true;
            }
            return(validate);
        }
Ejemplo n.º 2
0
        public List <Operation> GetUserOperations()
        {
            SecurityManager.ThrowIfUserContextNull();
            string key = "Operations" + SecurityManager.CurrentUserToken;

            if (SessionManager.Contains(key))
            {
                return(SessionManager.GetData(key) as List <Operation>);
            }
            List <Operation> operationList;

            if (!ConfigurationController.EnableSecurityCheck)
            {
                operationList = this.GetAllOperations();
            }
            else if (this.UserInRole("administrator"))
            {
                operationList = this.GetAllOperations().Where <Operation>((Func <Operation, bool>)(opr => !opr.IsSystem)).ToList <Operation>();
            }
            else
            {
                SecurityManager.ThrowIfUserContextNull();
                using (SecurityDbContext securityDbContext = new SecurityDbContext())
                    operationList = securityDbContext.GetOperationsByUserID(SecurityManager.CurrentUserContext.UserId);
            }
            SessionManager.Add(key, (object)operationList);
            return(operationList);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //过滤验证
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }
            var token = filterContext.HttpContext.Request.Headers["token"];

            if (!string.IsNullOrWhiteSpace(token))
            {
                string userId = token.Decrypt();
                if (CheckToken(userId))
                {
                    SessionManager.Add(ConstString.SysUserLoginId, userId);
                    return;
                }
            }
            filterContext.HttpContext.Response.ContentType = "application/json";
            var    result = ResMessage.CreatMessage(ResultTypeEnum.Error, "无Token用户权限,请登录获取token");
            string json   = JsonConvert.SerializeObject(result);

            filterContext.HttpContext.Response.Write(json);
            filterContext.HttpContext.Response.End();
        }
Ejemplo n.º 4
0
        public bool HasPageAccess(string operationCode)
        {
            if (!ConfigurationController.EnableSecurityCheck)
            {
                return(true);
            }
            if (string.IsNullOrWhiteSpace(operationCode))
            {
                return(false);
            }
            string        key = "PageAccess" + SecurityManager.CurrentUserToken;
            List <string> stringList;

            if (SessionManager.Contains(key))
            {
                stringList = SessionManager.GetData(key) as List <string>;
            }
            else
            {
                List <Operation> userOperations = this.GetUserOperations();
                stringList = userOperations.Select <Operation, string>((Func <Operation, string>)(opr => opr.Code.ToLower())).ToList <string>();
                stringList.AddRange(userOperations.Where <Operation>((Func <Operation, bool>)(opr => !string.IsNullOrWhiteSpace(opr.Tag1))).Select <Operation, string>((Func <Operation, string>)(opr =>
                {
                    if (!opr.Tag1.Contains(";;"))
                    {
                        return(opr.Tag1.Replace("~/", "").ToLower());
                    }
                    return(opr.Tag1.Split(new string[1] {
                        ";;"
                    }, StringSplitOptions.None)[0].Replace("~/", "").ToLower());
                })));
                SessionManager.Add(key, (object)stringList);
            }
            return(stringList.Contains(operationCode.Replace("~/", "").ToLower()));
        }
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //过滤验证
            if (filterContext.ActionDescriptor.IsDefined(typeof(NoTokenCheckAttribute), true) ||
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoTokenCheckAttribute), true))
            {
                return;
            }
            var token = filterContext.HttpContext.Request.Headers["token"];

            if (!string.IsNullOrWhiteSpace(token))
            {
                var userId = int.Parse(token.Decrypt());
                if (CheckToken(userId))
                {
                    SessionManager.Add(ConstString.UserLoginId, userId);
                    return;
                }
            }
            filterContext.HttpContext.Response.ContentType = "application/json";
            var result = ResMessage.CreatMessage(ResultMessageEnum.Error, "无Token用户权限,请登录获取token");

            filterContext.Result = new JsonResult()
            {
                Data = result,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            //string json = JsonConvert.SerializeObject(result);
            //filterContext.HttpContext.Response.Write(json);
            filterContext.HttpContext.Response.End();
            filterContext.HttpContext.Response.Close();
        }
Ejemplo n.º 6
0
            public override void OnEvent()
            {
                Session serverSession = session as Session;

                SessionManager.Add(serverSession);
                serverSession.BeginReceive();
            }
Ejemplo n.º 7
0
        public virtual async Task <OperationAccess> CreateOperationAccessAsync()
        {
            if (this.UseForAnonymousUser)
            {
                return new OperationAccess()
                       {
                           CanDelete = true,
                           CanExport = true,
                           CanImport = true,
                           CanInsert = true,
                           CanPrint  = true,
                           CanUpdate = true,
                           CanView   = true
                       }
            }
            ;
            SecurityManager.ThrowIfUserContextNull();
            if (!ConfigurationController.EnableSecurityCheck)
            {
                return new OperationAccess()
                       {
                           CanDelete = true,
                           CanExport = true,
                           CanImport = true,
                           CanInsert = true,
                           CanPrint  = true,
                           CanUpdate = true,
                           CanView   = true
                       }
            }
            ;
            OperationAccess oprAccess = SessionManager.GetData(this.OprAccessSessionKey) as OperationAccess;

            if (oprAccess == null)
            {
                oprAccess = new OperationAccess();

                oprAccess.CanImport = false;
                OperationAccess operationAccess1 = oprAccess;
                bool            flag1            = await this.HasAccessAsync(this.ViewKey);

                operationAccess1.CanView = flag1;
                operationAccess1         = (OperationAccess)null;
                oprAccess.CanInsert      = false;
                oprAccess.CanDelete      = false;
                oprAccess.CanUpdate      = false;
                OperationAccess operationAccess2 = oprAccess;
                bool            flag2            = await this.HasAccessAsync(this.ExportKey);

                operationAccess2.CanExport = flag2;
                operationAccess2           = (OperationAccess)null;
                OperationAccess operationAccess3 = oprAccess;
                bool            flag3            = await this.HasAccessAsync(this.PrintKey);

                operationAccess3.CanPrint = flag3;
                operationAccess3          = (OperationAccess)null;
                SessionManager.Add(this.OprAccessSessionKey, (object)oprAccess);
            }
            return(oprAccess);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 检查用户登录
        /// </summary>
        /// <param name="userInfo">用户名</param>
        /// <returns></returns>
        public bool CheckLogin(ViewUserLogin userInfo)
        {
            bool validate = false;

            userInfo.UserPwd = userInfo.UserPwd.GetMD5FromString();
            var userName = StringHelp.FilterSql(userInfo.UserName);
            var userPwd  = StringHelp.FilterSql(userInfo.UserPwd);
            var user     = userBll.FirstOrDefault <Sys_User>(x => x.UserNickName.Equals(userName) && x.Password.Equals(userPwd));

            if (user != null)
            {
                //var session = HttpContext.Session[ConstString.SysUserLoginId];
                //if (session == null)
                //{
                SessionManager.Add(ConstString.SysUserLoginId, user.UserId);
                string browser  = NetworkHelper.GetBrowser();
                string hostIP   = NetworkHelper.GetIp() != "0.0.0.0" ? NetworkHelper.GetIp() : ZHttp.ClientIP;
                string hostName = ZHttp.IsLanIP(ZHttp.ClientIP) ? ZHttp.ClientHostName : string.Empty; //如果是内网就获取,否则出错获取不到,且影响效率
                loginHistoryBLL.AddEntity(Sys_LoginHistory.CreateInstance(user.UserId, hostName, hostIP, userInfo.City, browser));
                SetUserCache(user);
                SetCookie(user.UserId);
                //}
                validate = true;
            }
            return(validate);
        }
Ejemplo n.º 9
0
        public ActionResult Login(UserModel model)
        {
            User user = model.Get(model);

            if (user != null)
            {
                SessionManager sessionManager  = new SessionManager();
                bool           passwordCorrect = CheckPassword(user.Password, model.Password);

                if (passwordCorrect)
                {
                    if (!user.IsActive)
                    {
                        user.IsActive = true;
                        model.UpdateUser(user);
                    }

                    sessionManager.Add <User>(user, PageConstant.USER_ID_I_SESSION);
                    ViewBag.Name = user.Name;

                    BudgetModel bmodel = new BudgetModel();
                    Budget      budget = bmodel.GetCurrentBudget(user.Id);

                    if (budget == null)
                    {
                        return(RedirectToAction("FirstLaunch", "FirstLaunch"));
                    }

                    sessionManager.Add <Budget>(budget, PageConstant.BUDGET_ID_IN_SESSION);

                    bmodel.CurrentBudget = budget.CurrentBudget;
                    bmodel.StartBudget   = budget.StartBudget;
                    return(View("MainPanel", bmodel));
                }
            }
            else
            {
                ModelState.AddModelError("", "Error");
            }

            ModelState.Clear();
            return(View("UserLoginView"));
        }
Ejemplo n.º 10
0
        public ActionResult Add(SesionVM sessionVM)
        {
            Sesion session = Mapper.Map <Sesion>(sessionVM);

            if (_sessionManager.Add(session))
            {
                TempData["saved"] = "Saved Successfully!";
                return(RedirectToAction("Add"));
            }
            return(View());
        }
Ejemplo n.º 11
0
        public bool Login(SystemUser user)
        {
            bool           flag    = false;
            DBPlayer       db      = new DBPlayer();
            SessionManager session = new SessionManager();

            try
            {
                db.cmdText = "SELECT * FROM Users WHERE Email = @Email AND Password = @Password";

                db.command.Parameters.Add("Email", SqlDbType.NVarChar);
                db.command.Parameters["Email"].Value = user.Email;

                db.command.Parameters.Add("Password", SqlDbType.NVarChar);
                db.command.Parameters["Password"].Value = user.Password;

                db.Open();
                SqlDataReader reader = db.command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        SystemUser userInfo = new SystemUser();
                        userInfo.UserId   = int.Parse(reader["Id"].ToString());
                        userInfo.FullName = reader["FullName"].ToString();
                        userInfo.Email    = reader["Email"].ToString();
                        userInfo.Status   = Convert.ToBoolean(reader["Status"]);

                        session.ActiveUserId = userInfo.UserId;
                        session.Add("ActiveUser", userInfo);
                        break;
                    }

                    flag = true;
                }
                else
                {
                    flag = false;
                }

                reader.Close();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                db.Close();
            }

            return(flag);
        }
Ejemplo n.º 12
0
        public static Image GetCaptchaImage(
            int length = 5,
            CaptchaFormat captchaFormat = CaptchaFormat.Numeric,
            int width  = 120,
            int height = 50)
        {
            CaptchaImage captchaImage = new CaptchaImage(length, captchaFormat, Color.Transparent, width, height);


            SessionManager.Add("__Captcha__", (object)captchaImage);
            return((Image)captchaImage.Image);
        }
Ejemplo n.º 13
0
        public override OperationAccess CreateOperationAccess()
        {
            if (this.UseForAnonymousUser)
            {
                return new OperationAccess()
                       {
                           CanDelete = true,
                           CanExport = true,
                           CanImport = true,
                           CanInsert = true,
                           CanPrint  = true,
                           CanUpdate = true,
                           CanView   = true
                       }
            }
            ;
            SecurityManager.ThrowIfUserContextNull();
            if (!ConfigurationController.EnableSecurityCheck)
            {
                return new OperationAccess()
                       {
                           CanDelete = true,
                           CanExport = true,
                           CanImport = true,
                           CanInsert = true,
                           CanPrint  = true,
                           CanUpdate = true,
                           CanView   = true
                       }
            }
            ;
            OperationAccess operationAccess = SessionManager.GetData(this.OprAccessSessionKey) as OperationAccess;

            if (operationAccess == null)
            {
                operationAccess = new OperationAccess();

                operationAccess.CanImport = this.HasAccess(this.ImportKey);
                operationAccess.CanView   = this.HasAccess(this.ViewKey);
                operationAccess.CanInsert = this.HasAccess(this.InsertKey);
                operationAccess.CanDelete = this.HasAccess(this.DeleteKey);
                operationAccess.CanUpdate = this.HasAccess(this.UpdateKey);
                operationAccess.CanExport = this.HasAccess(this.ExportKey);
                operationAccess.CanPrint  = this.HasAccess(this.PrintKey);
                SessionManager.Add(this.OprAccessSessionKey, (object)operationAccess);
            }
            return(operationAccess);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// 添加登陆记录
 /// </summary>
 /// <param name="userInfo"></param>
 /// <returns></returns>
 public void LoginHistory(string UserId, string City)
 {
     try
     {
         SessionManager.Add(ConstString.SysUserLoginId, UserId);
         string browser      = NetworkHelper.GetBrowser();
         string hostIP       = NetworkHelper.GetIp() != "0.0.0.0" ? NetworkHelper.GetIp() : ZHttp.ClientIP;
         string hostName     = ZHttp.IsLanIP(ZHttp.ClientIP) ? ZHttp.ClientHostName : string.Empty; //如果是内网就获取,否则出错获取不到,且影响效率
         var    loginHistory = Sys_LoginHistory.CreateInstance(UserId, hostName, hostIP, City, browser);
         loginHistoryBLL.AddEntity(loginHistory);
     }
     catch (Exception ex)
     {
         Log.Write(LogLevel.Error, "添加登陆记录日志表出错", ex);
     }
 }
Ejemplo n.º 15
0
        public ActionResult LoginIn(ReqUserLogin userLogin)
        {
            var chekUser = user.CheckLogin(userLogin);

            if (!chekUser.Item1)
            {
                return(Json(ResMessage.CreatMessage(ResultMessageEnum.AuthorityCheck, "用户或密码错误")));
            }
            int userId = chekUser.Item2;

            SessionManager.Add(ConstString.UserLoginId, userId);
            var token = userId.ToString().Encrypt();
            var obj   = new { token };

            return(Json(ResMessage.CreatMessage(ResultMessageEnum.Success, "登录成功", obj)));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Liefert die Session
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        private void SetSession(Session session)
        {
            if (SessionManager == null)
            {
                SessionManager = new Dictionary <Guid, Session>();
            }

            if (!SessionManager.ContainsKey(session.ID))
            {
                SessionManager.Add(session.ID, session);

                return;
            }

            SessionManager[session.ID] = session;
        }
Ejemplo n.º 17
0
        public ActionResult LogIn(SystemUser user)
        {
            try
            {
                session.ClearAll();

                if (string.IsNullOrEmpty(user.Email))
                {
                    ViewBag.ExErrorMessage = "Email must be provided.";
                    return(View());
                }
                else if (string.IsNullOrEmpty(user.Password))
                {
                    ViewBag.ExErrorMessage = "Password must be provided.";
                    return(View());
                }
                else
                {
                    if (userManager.IsUserExist(user.Email))
                    {
                        if (userManager.Login(user))
                        {
                            ViewBag.SaveMessage = "Logged In successfully.";
                            session.LoginFlag   = true;
                            session.Add("PageLoadCount", 0);
                            Response.Redirect("~/");
                        }
                        else
                        {
                            session.ClearAll();
                            ViewBag.ExErrorMessage = "Failed to Login.";
                        }
                    }
                    else
                    {
                        session.ClearAll();
                        ViewBag.ExErrorMessage = "User not exist.";
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(View());
        }
Ejemplo n.º 18
0
        public async Task <List <Operation> > GetUserOperationsAsync()
        {
            SecurityManager.ThrowIfUserContextNull();
            string key = "Operations" + SecurityManager.CurrentUserToken;

            if (SessionManager.Contains(key))
            {
                return(SessionManager.GetData(key) as List <Operation>);
            }
            List <Operation> accessList;

            if (!ConfigurationController.EnableSecurityCheck)
            {
                accessList = await this.GetAllOperationsAsync();
            }
            else if (this.UserInRole("administrator"))
            {
                accessList = await this.GetAllOperationsAsync();

                accessList = accessList.Where <Operation>((Func <Operation, bool>)(opr => !opr.IsSystem)).ToList <Operation>();
            }
            else
            {
                SecurityManager.ThrowIfUserContextNull();
                using (SecurityDbContext db = new SecurityDbContext())
                {
                    accessList = await db.GetOperationsByUserIDAsync(SecurityManager.CurrentUserContext.UserId);

                    if (ConfigurationController.ApplicationID.HasValue)
                    {
                        accessList = accessList.Where <Operation>((Func <Operation, bool>)(opr =>
                        {
                            int applicationId1 = opr.ApplicationId;
                            int?applicationId2 = ConfigurationController.ApplicationID;
                            int valueOrDefault = applicationId2.GetValueOrDefault();
                            if (applicationId1 != valueOrDefault)
                            {
                                return(false);
                            }
                            return(applicationId2.HasValue);
                        })).ToList <Operation>();
                    }
                }
            }
            SessionManager.Add(key, (object)accessList);
            return(accessList ?? new List <Operation>());
        }
Ejemplo n.º 19
0
        public ActionResult Save(FirstLaunchModel model)
        {
            BudgetModel    budgetModel    = new BudgetModel();
            SettingsModel  settingModel   = new SettingsModel();
            SessionManager sessionManager = new SessionManager();
            int            userid         = sessionManager.Get <User>(PageConstant.USER_ID_I_SESSION).Id;

            budgetModel        = model.Budget;
            settingModel       = model.Settings;
            budgetModel.UserId = settingModel.UserId = userid;
            budgetModel.AddBudget(budgetModel);
            settingModel.AddSettings(settingModel);

            Budget budget = budgetModel.GetCurrentBudget(userid);

            sessionManager.Add <Budget>(budget, PageConstant.BUDGET_ID_IN_SESSION);
            budgetModel.CurrentBudget = budget.CurrentBudget;
            budgetModel.StartBudget   = budget.StartBudget;

            return(View("MainPanel", budgetModel));
        }
Ejemplo n.º 20
0
        private async Task AddSid(string sid)
        {
            Tabs.SelectedTab = TabLoading;

            // wait tab switch
            await Task.Delay(1000);

            var result = await _sessionManager.Add(sid);

            if (!result.GetSuccess())
            {
                result.ShowError();
                Tabs.SelectedTab = TabInput;
                return;
            }

            Tabs.SelectedTab = TabSuccess;

            await Task.Delay(5000);

            DialogResult = DialogResult.OK;
            Close();
        }
Ejemplo n.º 21
0
 public void SetUrl([FromBody] ParameterUrl url)
 {
     SessionManager.Add("authenticateUrl", url);
 }
Ejemplo n.º 22
0
 public void Connect(string name)
 {
     _manager.Add(ConnectionId, name);
 }