/** 获取头部信息 */ @RequestMapping(value = "/getUname") @ResponseBody public Object getList() { PageData pd = new PageData(); Map<String, Object> map = new HashMap<String, Object>(); try { pd = this.getPageData(); List<PageData> pdList = new ArrayList<PageData>(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); PageData pds = new PageData(); pds = (PageData) session.getAttribute(Const.SESSION_userpds); if (null == pds) { String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString(); // 获取当前登录者loginname pd.put("USERNAME", USERNAME); pds = userService.findByUId(pd); session.setAttribute(Const.SESSION_userpds, pds); } pdList.add(pds); map.put("list", pdList); } catch (Exception e) { logger.error(e.toString(), e); } finally { logAfter(logger); } return AppUtil.returnObject(pd, map); }
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); if (!subject.isAuthenticated() && !subject.isRemembered()) { // 如果没有登录,直接进行之后的流程 return true; } Session session = subject.getSession(); // String username = (String) subject.getPrincipal(); String account = ((ShiroUser) subject.getPrincipal()).getAccount(); Serializable sessionId = session.getId(); // TODO 同步控制 Deque<Serializable> deque = cache.get(account); if (deque == null) { deque = new LinkedList<Serializable>(); cache.put(account, deque); } // 如果队列里没有此sessionId,且用户没有被踢出;放入队列 if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) { deque.push(sessionId); } // 如果队列里的sessionId数超出最大会话数,开始踢人 while (deque.size() > maxSession) { Serializable kickoutSessionId = null; if (kickoutAfter) { // 如果踢出后者 kickoutSessionId = deque.removeFirst(); } else { // 否则踢出前者 kickoutSessionId = deque.removeLast(); } try { Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId)); if (kickoutSession != null) { // 设置会话的kickout属性表示踢出了 kickoutSession.setAttribute("kickout", true); } } catch (Exception e) { // ignore exception } } // 如果被踢出了,直接退出,重定向到踢出后的地址 if (session.getAttribute("kickout") != null) { // 会话被踢出了 try { subject.logout(); } catch (Exception e) { // ignore } saveRequest(request); WebUtils.issueRedirect(request, response, kickoutUrl); return false; } return true; }
/* ===============================权限================================== */ public void getHC() { ModelAndView mv = this.getModelAndView(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Map<String, String> map = (Map<String, String>) session.getAttribute(Const.SESSION_QX); mv.addObject(Const.SESSION_QX, map); // 按钮权限 List<Menu> menuList = (List) session.getAttribute(Const.SESSION_menuList); mv.addObject(Const.SESSION_menuList, menuList); // 菜单权限 }
/** 去新增用户页面 */ @RequestMapping(value = "/goAddU") public ModelAndView goAddU() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); // 从session获取用户信息 Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); pd.put("USERID", user.getUSER_ID()); pd.put("ROLEID", user.getROLE_ID()); logger.info("pd:" + gson.toJson(pd)); List<Role> roleList = null; if (userService.isAdmin(user.getROLE_ID())) { roleList = roleService.listAllERRoles(); // 列出所有角色 } else if (userService.isCooper(user.getROLE_ID())) { roleList = roleService.listSubUserRole(userService.SUBUSER_CODE); // 列出所有二级角色 } mv.setViewName("system/user/user_edit"); mv.addObject("msg", "saveU"); mv.addObject("pd", pd); mv.addObject("roleList", roleList); return mv; }
/** 显示用户列表(用户组) */ @RequestMapping(value = "/list") public ModelAndView listappactivitys(Page page) throws Exception { logBefore(logger, "WxBindCustomerController_listusers"); ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); // 按照条件检索 try { Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Sys_User user = (Sys_User) session.getAttribute(Const.SESSION_USER); String factoryid = user.getDoc_factory().getId(); // 分页查询 String currentPage = ""; if (pd.toString().contains("currentPage")) currentPage = pd.getString("currentPage"); else currentPage = "1"; PageBean pageappactivity = appbookService.findpageappbook(factoryid, currentPage); page.setPd(pd); mv.setViewName("system/appbook/appbook_list"); mv.addObject("varList", pageappactivity.getRecordList()); pd.put("pagepicture", pageappactivity); mv.addObject("pd", pd); } catch (Exception e) { e.printStackTrace(); logger.error(e.toString(), e); } return mv; }
public static String randomUUID(HttpServletRequest request) { Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Object uuid = session.getAttribute("UUID"); session.setAttribute("UUID", UUID.randomUUID().toString()); return uuid == null ? "" : uuid.toString(); }
@Override public boolean isAccessAllowed( ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); // 如果 isAuthenticated 为 false 证明不是登录过的,同时 isRememberd 为true // 证明是没登陆直接通过记住我功能进来的 if (!subject.isAuthenticated() && subject.isRemembered()) { // 获取session看看是不是空的 Session session = subject.getSession(true); // 随便拿session的一个属性来看session当前是否是空的,我用userId,你们的项目可以自行发挥 if (session.getAttribute(SessionObject.SESSION_KEY) == null) { // 如果是空的才初始化,否则每次都要初始化,项目得慢死 // 这边根据前面的前提假设,拿到的是username String username = subject.getPrincipal().toString(); // 在这个方法里面做初始化用户上下文的事情,比如通过查询数据库来设置session值,你们自己发挥 User user = userService.get(Long.parseLong(username)); UsernamePasswordToken token = new UsernamePasswordToken(user.getId().toString(), user.getPassword(), true); SecurityUtils.getSubject().login(token); SessionObject so = new SessionObject(); so.setUser(user); session.setAttribute(SessionObject.SESSION_KEY, so); } } // 这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() // 让它同时也兼容remember这种情况 return super.isAccessAllowed(request, response, mappedValue); }
@Override public void onRemoval(RemovalNotification<Serializable, Session> notification) { Serializable key = notification.getKey(); Session session = notification.getValue(); if (notification.getCause() == RemovalCause.EXPIRED) { // time out cause session expired. logger.info("session for {} expired.", session.getId()); } else { // logout cause session be removed. logger.info("session for {} stoped.", session.getId()); } Object attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); if (attribute instanceof PrincipalCollection) { PrincipalCollection collection = (PrincipalCollection) attribute; for (Object object : collection) { if (object instanceof ShiroPrincipal) { ShiroPrincipal shiroPrincipal = (ShiroPrincipal) object; UsrSession userSession = shiroPrincipal.getSession(); userSession.setLastAccessTime(new Timestamp(session.getLastAccessTime().getTime())); userSession.setStopTime(new Timestamp(System.currentTimeMillis())); UsrSession merge = userSessionDao.update(userSession); shiroPrincipal.setSession(merge); } } } }
/** * @方法名: getAllMenu @功能描述: 获取所有菜单 * * @param userId * @return @作者 zlt @日期 2016年7月18日 */ @RequestMapping(value = "/getAllMenu", method = RequestMethod.POST) @ResponseBody public String getAllMenu(SysMenu sysMenu) { log.debug("获取所有菜单"); List<SysMenu> rows; JSONObject obj = new JSONObject(); String result = ""; try { // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); List<SysMenu> allmenuList = new ArrayList<SysMenu>(); String roleRights = ""; if (null == session.getAttribute(Const.SESSION_allmenuList)) { allmenuList = sysMenuService.selectAllMenu(sysMenu); if (StringUtil.isNullOrEmpty(roleRights)) { for (SysMenu menu : allmenuList) { // menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMenuId())); menu.setHasMenu(true); if (menu.isHasMenu()) { List<SysMenu> subMenuList = menu.getSubMenu(); for (SysMenu sub : subMenuList) { // sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMenuId())); sub.setHasMenu(true); } } } } session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中 } else { allmenuList = (List<SysMenu>) session.getAttribute(Const.SESSION_allmenuList); } result = JSONObject.toJSONString( allmenuList, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty); } catch (Exception e) { log.error("获取所有菜单出错", e); } System.out.println(result); return result; }
/** 显示用户列表(用户组) */ @RequestMapping(value = "/listUsers") public ModelAndView listUsers(Page page) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); String USERNAME = pd.getString("USERNAME"); if (null != USERNAME && !"".equals(USERNAME)) { USERNAME = USERNAME.trim(); pd.put("USERNAME", USERNAME); } String lastLoginStart = pd.getString("lastLoginStart"); String lastLoginEnd = pd.getString("lastLoginEnd"); if (lastLoginStart != null && !"".equals(lastLoginStart)) { lastLoginStart = lastLoginStart + " 00:00:00"; pd.put("lastLoginStart", lastLoginStart); } if (lastLoginEnd != null && !"".equals(lastLoginEnd)) { lastLoginEnd = lastLoginEnd + " 00:00:00"; pd.put("lastLoginEnd", lastLoginEnd); } // 从session获取用户信息 Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); pd.put("USERID", user.getUSER_ID()); pd.put("ROLEID", user.getROLE_ID()); logger.info("pd:" + gson.toJson(pd)); page.setPd(pd); List<PageData> userList = null; List<Role> roleList = null; if (userService.isAdmin(user.getROLE_ID())) { userList = userService.listPdPageUser(page); // 列出用户列表 roleList = roleService.listAllERRoles(); // 列出所有角色 } else if (userService.isCooper(user.getROLE_ID())) { userList = userService.listSubUser(page); // 列出用户列表 roleList = roleService.listSubUserRole(userService.SUBUSER_CODE); // 列出所有二级角色 } mv.setViewName("system/user/user_list"); mv.addObject("userList", userList); mv.addObject("roleList", roleList); mv.addObject("pd", pd); mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限 return mv; }
/** 获取用户权限 */ public Map<String, String> getUQX(Session session) { PageData pd = new PageData(); Map<String, String> map = new HashMap<String, String>(); try { String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString(); pd.put(Const.SESSION_USERNAME, USERNAME); String ROLE_ID = userService.findByUId(pd).get("ROLE_ID").toString(); pd.put("ROLE_ID", ROLE_ID); PageData pd2 = new PageData(); pd2.put(Const.SESSION_USERNAME, USERNAME); pd2.put("ROLE_ID", ROLE_ID); pd = roleService.findObjectById(pd); pd2 = roleService.findGLbyrid(pd2); if (null != pd2) { map.put("FX_QX", pd2.get("FX_QX").toString()); map.put("FW_QX", pd2.get("FW_QX").toString()); map.put("QX1", pd2.get("QX1").toString()); map.put("QX2", pd2.get("QX2").toString()); map.put("QX3", pd2.get("QX3").toString()); map.put("QX4", pd2.get("QX4").toString()); pd2.put("ROLE_ID", ROLE_ID); pd2 = roleService.findYHbyrid(pd2); map.put("C1", pd2.get("C1").toString()); map.put("C2", pd2.get("C2").toString()); map.put("C3", pd2.get("C3").toString()); map.put("C4", pd2.get("C4").toString()); map.put("Q1", pd2.get("Q1").toString()); map.put("Q2", pd2.get("Q2").toString()); map.put("Q3", pd2.get("Q3").toString()); map.put("Q4", pd2.get("Q4").toString()); } map.put("adds", pd.getString("ADD_QX")); map.put("dels", pd.getString("DEL_QX")); map.put("edits", pd.getString("EDIT_QX")); map.put("chas", pd.getString("CHA_QX")); // System.out.println(map); this.getRemortIP(USERNAME); } catch (Exception e) { logger.error(e.toString(), e); } return map; }
/** 重写父类方法,在shiro执行登录时先对比验证码,正确后在登录,否则直接登录失败 */ @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { Session session = getSubject(request, response).getSession(false); String code = (String) session.getAttribute(getSessionValidateCodeKey()); String submitCode = getValidateCode(request); if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code, submitCode.toLowerCase())) { return onLoginFailure( this.createToken(request, response), new AccountException("验证码不正确"), request, response); } return super.executeLogin(request, response); }
protected static Member getLoginUser(boolean returnRemembered) { Subject subject = SecurityUtils.getSubject(); if (subject == null) { return null; } Session session = subject.getSession(); if (session == null) { if (subject.isRemembered() == true) { return (Member) subject.getPrincipal(); } return null; } return (Member) session.getAttribute(Constants.CURRENT_USER); }
@Test public void testDefaultConfig() { Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("guest", "guest"); subject.login(token); assertTrue(subject.isAuthenticated()); assertTrue("guest".equals(subject.getPrincipal())); assertTrue(subject.hasRole("guest")); Session session = subject.getSession(); session.setAttribute("key", "value"); assertEquals(session.getAttribute("key"), "value"); subject.logout(); assertNull(subject.getSession(false)); assertNull(subject.getPrincipal()); assertNull(subject.getPrincipals()); }
/** 保存皮肤 */ @RequestMapping(value = "/setSKIN") public void setSKIN(PrintWriter out) { PageData pd = new PageData(); try { pd = this.getPageData(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString(); // 获取当前登录者loginname pd.put("USERNAME", USERNAME); userService.setSKIN(pd); session.removeAttribute(Const.SESSION_userpds); session.removeAttribute(Const.SESSION_USERROL); out.write("success"); out.close(); } catch (Exception e) { logger.error(e.toString(), e); } }
// 获得当前角色下的指定菜单下的所有操作 @SuppressWarnings("unchecked") @GetMapping( value = "/getRoleModuleOperations/{moduleId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public String getRoleModuleOperations( HttpServletRequest request, HttpServletResponse response, @PathVariable String moduleId) { JSONObject jo = new JSONObject(); Session session = ShiroUtil.getSession(); List<Role> roleList = (List<Role>) session.getAttribute(Constant.SESSION_ROLE); int superAdminFlag = 0; for (int i = 0; i < roleList.size(); i++) { if (roleList.get(i).getRoleid().equals(Constant.ROLE_ADMIN_ID)) { superAdminFlag = 1; break; } } List<Module> operationList = moduleService.getRoleModuleOperations(moduleId, roleList, superAdminFlag); jo.put("operation", operationList); return jo.toString(); }
@RequestMapping( value = "/list/{p}", method = {RequestMethod.GET, RequestMethod.POST}) public String linkList( Link link, @PathVariable Integer p, HttpServletRequest request, ModelMap modelMap) { Session session = SystemUtils.getShiroSession(); if (StringUtils.isNotBlank(link.getLinkName())) { session.setAttribute("linkSearch", link); modelMap.addAttribute("searchLink", link); } else { session.setAttribute("linkSearch", null); } Object searchObj = session.getAttribute("linkSearch"); Page<Link> result = linkService.findLinkPageable((searchObj == null ? (new Link()) : ((Link) searchObj)), p); modelMap.addAttribute("links", result.getContent()); modelMap.addAttribute( "pagination", SystemUtils.pagination(result, HttpUtils.getContextPath(request) + "/manager/link/list")); return "link/link_list"; }
/** 认证回调函数, 登录时调用 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; int activeSessionSize = getSystemService().getSessionDao().getActiveSessions(false).size(); if (logger.isDebugEnabled()) { logger.debug( "login submit, active session size: {}, username: {}", activeSessionSize, token.getUsername()); } // 校验登录验证码 if (LoginController.isValidateCodeLogin(token.getUsername(), false, false)) { Session session = UserUtils.getSession(); String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE); if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)) { throw new AuthenticationException("msg:验证码错误, 请重试."); } } // 校验用户名密码 User user = getSystemService().getUserByLoginName(token.getUsername()); if (user != null) { if (Global.NO.equals(user.getLoginFlag())) { throw new AuthenticationException("msg:该帐号已禁止登录."); } byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16)); return new SimpleAuthenticationInfo( new Principal(user, token.isMobileLogin()), user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName()); } else { return null; } }
/** * Test that validates functionality for issue <a * href="https://issues.apache.org/jira/browse/JSEC-22">JSEC-22</a> */ @Test public void testSubjectReuseAfterLogout() { Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("guest", "guest"); subject.login(token); assertTrue(subject.isAuthenticated()); assertTrue("guest".equals(subject.getPrincipal())); assertTrue(subject.hasRole("guest")); Session session = subject.getSession(); Serializable firstSessionId = session.getId(); session.setAttribute("key", "value"); assertEquals(session.getAttribute("key"), "value"); subject.logout(); assertNull(subject.getSession(false)); assertNull(subject.getPrincipal()); assertNull(subject.getPrincipals()); subject.login(new UsernamePasswordToken("lonestarr", "vespa")); assertTrue(subject.isAuthenticated()); assertTrue("lonestarr".equals(subject.getPrincipal())); assertTrue(subject.hasRole("goodguy")); assertNotNull(subject.getSession()); assertFalse(firstSessionId.equals(subject.getSession().getId())); subject.logout(); assertNull(subject.getSession(false)); assertNull(subject.getPrincipal()); assertNull(subject.getPrincipals()); }
/** * Test that validates functionality for issue <a * href="https://issues.apache.org/jira/browse/JSEC-46">JSEC-46</a> */ @Test public void testAutoCreateSessionAfterInvalidation() { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); Serializable origSessionId = session.getId(); String key = "foo"; String value1 = "bar"; session.setAttribute(key, value1); assertEquals(value1, session.getAttribute(key)); // now test auto creation: session.setTimeout(50); try { Thread.sleep(150); } catch (InterruptedException e) { // ignored } try { session.setTimeout(AbstractValidatingSessionManager.DEFAULT_GLOBAL_SESSION_TIMEOUT); fail("Session should have expired."); } catch (ExpiredSessionException expected) { } }
/** 保存用户 */ @RequestMapping(value = "/saveU") public ModelAndView saveU(PrintWriter out) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); pd.put("USER_ID", this.get32UUID()); // ID pd.put("RIGHTS", ""); // 权限 pd.put("LAST_LOGIN", ""); // 最后登录时间 pd.put("IP", ""); // IP pd.put("STATUS", "0"); // 状态 pd.put("SKIN", "default"); // 默认皮肤 // 从session获取用户信息 Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); pd.put("CREATOR", user.getUSER_ID()); logger.info("pd:" + gson.toJson(pd)); pd.put( "PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString()); if (null == userService.findByUId(pd)) { if (Jurisdiction.buttonJurisdiction(menuUrl, "add")) { userService.saveU(pd); } // 判断新增权限 mv.addObject("msg", "success"); } else { mv.addObject("msg", "failed"); } mv.setViewName("save_result"); return mv; }
/** 请求登录,验证用户 */ @RequestMapping(value = "/login_login", produces = "application/json;charset=UTF-8") @ResponseBody public Object login() throws Exception { Map<String, String> map = new HashMap<String, String>(); PageData pd = new PageData(); pd = this.getPageData(); String errInfo = ""; String KEYDATA[] = pd.getString("KEYDATA").split(",fh,"); if (null != KEYDATA && KEYDATA.length == 3) { // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); String sessionCode = (String) session.getAttribute(Const.SESSION_SECURITY_CODE); // 获取session中的验证码 String code = KEYDATA[2]; if (null == code || "".equals(code)) { errInfo = "nullcode"; // 验证码为空 } else { String USERNAME = KEYDATA[0]; String PASSWORD = KEYDATA[1]; pd.put("USERNAME", USERNAME); if (Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(code)) { String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString(); // 密码加密 pd.put("PASSWORD", passwd); pd = userService.getUserByNameAndPwd(pd); if (pd != null) { pd.put("LAST_LOGIN", DateUtil.getTime().toString()); userService.updateLastLogin(pd); User user = new User(); user.setUSER_ID(pd.getString("USER_ID")); user.setUSERNAME(pd.getString("USERNAME")); user.setPASSWORD(pd.getString("PASSWORD")); user.setNAME(pd.getString("NAME")); user.setRIGHTS(pd.getString("RIGHTS")); user.setROLE_ID(pd.getString("ROLE_ID")); user.setLAST_LOGIN(pd.getString("LAST_LOGIN")); user.setIP(pd.getString("IP")); user.setSTATUS(pd.getString("STATUS")); session.setAttribute(Const.SESSION_USER, user); session.removeAttribute(Const.SESSION_SECURITY_CODE); // shiro加入身份验证 Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, PASSWORD); try { subject.login(token); } catch (AuthenticationException e) { errInfo = "身份验证失败!"; } } else { errInfo = "usererror"; // 用户名或密码有误 } } else { errInfo = "codeerror"; // 验证码输入有误 } if (Tools.isEmpty(errInfo)) { errInfo = "success"; // 验证成功 } } } else { errInfo = "error"; // 缺少参数 } map.put("result", errInfo); return AppUtil.returnObject(new PageData(), map); }
/** 访问系统首页 */ @RequestMapping(value = "/main/{changeMenu}") public ModelAndView login_index(@PathVariable("changeMenu") String changeMenu) { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); try { // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); if (user != null) { User userr = (User) session.getAttribute(Const.SESSION_USERROL); if (null == userr) { user = userService.getUserAndRoleById(user.getUSER_ID()); session.setAttribute(Const.SESSION_USERROL, user); } else { user = userr; } Role role = user.getRole(); String roleRights = role != null ? role.getRIGHTS() : ""; // 避免每次拦截用户操作时查询数据库,以下将用户所属角色权限、用户权限限都存入session session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); // 将角色权限存入session session.setAttribute(Const.SESSION_USERNAME, user.getUSERNAME()); // 放入用户名 List<Menu> allmenuList = new ArrayList<Menu>(); if (null == session.getAttribute(Const.SESSION_allmenuList)) { allmenuList = menuService.listAllMenu(); if (Tools.notEmpty(roleRights)) { for (Menu menu : allmenuList) { menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID())); if (menu.isHasMenu()) { List<Menu> subMenuList = menu.getSubMenu(); for (Menu sub : subMenuList) { sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID())); } } } } session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中 } else { allmenuList = (List<Menu>) session.getAttribute(Const.SESSION_allmenuList); } // 切换菜单===== List<Menu> menuList = new ArrayList<Menu>(); // if(null == session.getAttribute(Const.SESSION_menuList) || // ("yes".equals(pd.getString("changeMenu")))){ if (null == session.getAttribute(Const.SESSION_menuList) || ("yes".equals(changeMenu))) { List<Menu> menuList1 = new ArrayList<Menu>(); List<Menu> menuList2 = new ArrayList<Menu>(); // 拆分菜单 for (int i = 0; i < allmenuList.size(); i++) { Menu menu = allmenuList.get(i); if ("1".equals(menu.getMENU_TYPE())) { menuList1.add(menu); } else { menuList2.add(menu); } } session.removeAttribute(Const.SESSION_menuList); if ("2".equals(session.getAttribute("changeMenu"))) { session.setAttribute(Const.SESSION_menuList, menuList1); session.removeAttribute("changeMenu"); session.setAttribute("changeMenu", "1"); menuList = menuList1; } else { session.setAttribute(Const.SESSION_menuList, menuList2); session.removeAttribute("changeMenu"); session.setAttribute("changeMenu", "2"); menuList = menuList2; } } else { menuList = (List<Menu>) session.getAttribute(Const.SESSION_menuList); } // 切换菜单===== if (null == session.getAttribute(Const.SESSION_QX)) { session.setAttribute(Const.SESSION_QX, this.getUQX(session)); // 按钮权限放到session中 } // FusionCharts 报表 // String strXML = "<graph caption='前12个月订单销量柱状图' xAxisName='月份' yAxisName='值' // decimalPrecision='0' formatNumberScale='0'><set name='2013-05' value='4' // color='AFD8F8'/><set name='2013-04' value='0' color='AFD8F8'/><set name='2013-03' // value='0' color='AFD8F8'/><set name='2013-02' value='0' color='AFD8F8'/><set // name='2013-01' value='0' color='AFD8F8'/><set name='2012-01' value='0' // color='AFD8F8'/><set name='2012-11' value='0' color='AFD8F8'/><set name='2012-10' // value='0' color='AFD8F8'/><set name='2012-09' value='0' color='AFD8F8'/><set // name='2012-08' value='0' color='AFD8F8'/><set name='2012-07' value='0' // color='AFD8F8'/><set name='2012-06' value='0' color='AFD8F8'/></graph>" ; // mv.addObject("strXML", strXML); // FusionCharts 报表 // 读取websocket配置 String strWEBSOCKET = Tools.readTxtFile(Const.WEBSOCKET); // 读取WEBSOCKET配置 if (null != strWEBSOCKET && !"".equals(strWEBSOCKET)) { String strIW[] = strWEBSOCKET.split(",fh,"); if (strIW.length == 4) { pd.put("WIMIP", strIW[0]); pd.put("WIMPORT", strIW[1]); pd.put("OLIP", strIW[2]); pd.put("OLPORT", strIW[3]); } } // 读取websocket配置 mv.setViewName("system/admin/index"); mv.addObject("user", user); mv.addObject("menuList", menuList); } else { mv.setViewName("system/admin/login"); // session失效后跳转登录页面 } } catch (Exception e) { mv.setViewName("system/admin/login"); logger.error(e.getMessage(), e); } pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称 mv.addObject("pd", pd); return mv; }
/** * get data from shiro session * * @param key data's key * @return data's value */ public static Object get(Object key) { Session session = getSession(); return session.getAttribute(key); }
/* ===============================权限================================== */ public Map<String, String> getHC() { Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session Session session = currentUser.getSession(); return (Map<String, String>) session.getAttribute(Const.SESSION_QX); }