Exemple #1
0
        /// <summary>
        /// 设置管理员信息,如果当前用户是管理员的话,则给session的adminId设置为管理员ID,否则不设置session
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static void SetAdmindId(HttpContext context)
        {
            if (context.Session["adminId"] != null)
            {
                return;
            }
            HttpCookie recordCookie = context.Request.Cookies["sh"];//said history=>Said登录历史

            string recordId = recordCookie == null ? null : recordCookie.Value;

            if (!string.IsNullOrEmpty(recordId))
            {                                                                       //管理员访问历史cookie存在
                AdminRecord record = CacheHelper.GetCache(recordId) as AdminRecord; //检测cache是否有
                if (record == null)
                {
                    record = new AdminRecordApplication().FindById(recordId); //从数据库查询
                    if (record != null)                                       //从cookie中查出来了,放入cache
                    {
                        CacheHelper.SetCache(recordId, record.Admin);
                        //更新到Session
                        context.Session["adminId"] = record.AdminId;
                        //return record.AdminId;
                    }
                }
                else
                {
                    //return record.AdminId;
                    context.Session["adminId"] = record.AdminId;
                }
            }
            //return null;
        }
Exemple #2
0
        /// <summary>
        /// 获取当前登录管理员的管理员信息
        /// </summary>
        /// <returns></returns>
        protected Admin GetAdmin()
        {
            HttpCookie recordCookie = Request.Cookies["sh"];
            Admin      admin        = CacheHelper.GetCache(recordCookie.Value) as Admin;

            if (admin == null)
            {
                //从数据库中查询
                AdminRecord record = adminRecordApplication.Get(recordCookie.Value);
                if (record == null)
                {
                    return(null);
                }
                admin = record.Admin;
                CacheHelper.SetCache(recordCookie.Value, admin);
            }
            return(admin);
        }
Exemple #3
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoFilter), false).Length > 0)
            {
                //登录页不使用过滤器
                //TODO 检测一下有木有登录记录,有登录记录的话直接登录,否则放行
                return;
            }

            HttpContext context      = HttpContext.Current;
            HttpCookie  recordCookie = context.Request.Cookies["sh"];//said history=>Said登录历史
            string      recordId     = recordCookie == null ? null : recordCookie.Value;

            //System.Diagnostics.Debug.Write();
            //从缓存读,读不到再从数据库读

            if (string.IsNullOrEmpty(recordId))
            {
                //跳转到登录页
                filterContext.Result = new RedirectResult(string.Format("/Back/Home/Login?re={0}", System.Web.HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri)));
                return;
            }
            //没有记录 && 从数据库读不到记录
            if (CacheHelper.GetCache(recordId) == null)
            {
                AdminRecord record = adminRecordApplication.Get(recordId);
                if (record != null)
                {
                    CacheHelper.SetCache(recordId, record.Admin);
                }
                else
                {
                    /*
                     *  跳转到登录页,RedirectResult参考这篇:http://www.cnblogs.com/artech/archive/2012/08/16/action-result-04.html
                     *  RedirectResult是暂时重定向,搜索引擎不会收录
                     */
                    filterContext.Result = new RedirectResult(string.Format("/Back/Home/Login?re={0}", System.Web.HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri)));
                }
            }
        }
Exemple #4
0
        public ActionResult SetAdminRecord(SetAdminRecordModel model)
        {
            if (ModelState.IsValid)
            {
                using (UWCContext db = new UWCContext())
                {
                    string roleName = model.RoleName == "Преподаватель"
                                    ? UserRoles.TEACHER_ROLE_NAME
                                    : UserRoles.STUDENT_ROLE_NAME;

                    AdminRecord record = db.AdminRecords.FirstOrDefault(r => r.RoleName == roleName);
                    Guid        salt   = Guid.NewGuid();
                    if (record != null)
                    {
                        record.Salt            = salt;
                        record.Password        = Rfc2898Encoder.Encode(model.AccessPassword, salt.ToString());
                        db.Entry(record).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        AdminRecord newRecord = new AdminRecord()
                        {
                            Salt     = salt,
                            RoleName = roleName,
                            Password = Rfc2898Encoder.Encode(model.AccessPassword, salt.ToString())
                        };


                        db.AdminRecords.Add(newRecord);
                        db.SaveChanges();
                    }
                    return(RedirectToAction("AdminRecordAddedMessage", "Administration"));
                }
            }
            ViewBag.AllowedRoles = new SelectList(new string[] { "Преподаватель", "Студент" });
            return(View(model));
        }
Exemple #5
0
        public JsonResult Login(string name, string pwd)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(ResponseResult(1, "没有输入用户名"));
            }
            if (string.IsNullOrWhiteSpace(pwd))
            {
                return(ResponseResult(2, "没有输入用户密码"));
            }
            string newPwd = Encrypt.MD5Encrypt(pwd);
            //登录记录
            AdminRecord record = new AdminRecord
            {
                Date = DateTime.Now,
                //AdminId = admin.AdminId,
                //Description = string.Format("管理员【{0}】登录", admin.Name),
                IP            = HttpHelper.GetIP(System.Web.HttpContext.Current),
                OperationType = OperationType.Login,
                Rollback      = string.Empty,
                Url           = Request.Url.AbsoluteUri,
                Address       = string.Empty,
                UserAgent     = HttpContext.Request.UserAgent,
                AdminRecordId = SaidCommon.GUID
            };

            if (HttpContext.Request.UrlReferrer != null)
            {
                record.UrlReferrer       = HttpContext.Request.UrlReferrer.AbsoluteUri;
                record.ReferrerAuthority = HttpContext.Request.UrlReferrer.Authority;
            }
            record.Address = GetAddressToString(record.IP);

            //判断白名单
            //if (!IPRange.Check(record.IP))
            //{
            //    //将这次记录打入数据库
            //    record.Description = string.Format("异常IP(白名单约束)正在登录,输入的用户名:{0},密码:{1}", name, pwd);
            //    record.OperationType = OperationType.Warning;
            //    AdminRecordApplication.Add(record);
            //    return ResponseResult(6, "登录异常");
            //}
            Admin admin = adminApplication.Get(name, newPwd);

            if (admin == null)
            {
                record.Description   = string.Format("请求登录失败,输入的用户名:{0},密码:{1}", name, pwd);
                record.OperationType = OperationType.Warning;
                adminRecordApplication.Add(record);
                adminRecordApplication.Commit();
                return(ResponseResult(3, "用户名或密码不正确"));
            }
            //record.AdminId = admin.AdminId;
            record.AdminId     = admin.AdminId;
            record.Description = string.Format("管理员【{0}】登录", admin.Name);

            adminRecordApplication.Add(record);
            if (adminRecordApplication.Commit())
            {
                //放到缓存池
                CacheHelper.SetCache(record.AdminRecordId, admin);
                return(ResponseResult(record.AdminRecordId));//成功返回登录记录
            }
            return(ResponseResult(5, "添加登录记录异常"));
        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = null;
                using (UWCContext db = new UWCContext())
                {
                    user = db.Users.FirstOrDefault(u => u.Email == model.Email);
                }

                if (user == null)
                {
                    using (UWCContext db = new UWCContext())
                    {
                        string roleName = model.RoleName == "Преподаватель"
                                   ? UserRoles.TEACHER_ROLE_NAME
                                   : UserRoles.STUDENT_ROLE_NAME;

                        AdminRecord adminRecord = db.AdminRecords.FirstOrDefault(r => r.RoleName == roleName);
                        if (adminRecord != null)
                        {
                            Guid   uid             = Guid.NewGuid();
                            string userSalt        = uid.ToString();
                            string encodedPassword = Rfc2898Encoder.Encode(model.Password, userSalt);

                            if (Rfc2898Encoder.Validate(model.RoleAccessPassword, adminRecord.Password, adminRecord.Salt.ToString()))
                            {
                                User newUser = new User()
                                {
                                    Id         = uid,
                                    Surname    = model.Surname,
                                    Name       = model.Name,
                                    Patronymic = model.Patronymic,
                                    Age        = model.Age,
                                    Email      = model.Email,
                                    Password   = encodedPassword,
                                    RoleId     = model.RoleName == "Преподаватель"
                                             ? UserRoles.TEACHER_ROLE_ID
                                             : UserRoles.STUDENT_ROLE_ID
                                };

                                db.Users.Add(newUser);
                                db.SaveChanges();
                            }
                            else
                            {
                                ModelState.AddModelError("", "Неверный пользовательский или преподавательский пароль");
                            }

                            user = db.Users.Where(u => u.Email == model.Email && u.Password == encodedPassword).FirstOrDefault();
                        }
                        else
                        {
                            ModelState.AddModelError("", "Пароль для регистрации с ролью \"" + roleName + "\" еще не задан администратором, попробуйте позже.");
                        }
                    }
                    if (user != null)
                    {
                        FormsAuthentication.SetAuthCookie(model.Email, true);
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Пользоваетль с таким адресом Email уже существует");
                }
            }

            ViewBag.AllowedRoles = new SelectList(new string[] { "Преподаватель", "Студент" });
            return(View(model));
        }