Esempio n. 1
0
 /**
  * store data to shiro session
  *
  * @param key data's key
  * @param value data's value
  */
 public static void store(Object key, Object value) {
   Session session = getSession();
   session.setAttribute(key, value);
   if (logger.isDebugEnabled()) {
     logger.debug("session timeout default {} s", session.getTimeout() / 1000);
   }
 }
Esempio n. 2
0
  /** 去新增用户页面 */
  @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;
  }
  /**
   * Stores the Session's ID, usually as a Cookie, to associate with future requests.
   *
   * @param session the session that was just {@link #createSession created}.
   */
  @Override
  protected void onStart(Session session, SessionContext context) {
    super.onStart(session, context);

    if (!WebUtils.isHttp(context)) {
      log.debug(
          "SessionContext argument is not HTTP compatible or does not have an HTTP request/response "
              + "pair. No session ID cookie will be set.");
      return;
    }
    HttpServletRequest request = WebUtils.getHttpRequest(context);
    HttpServletResponse response = WebUtils.getHttpResponse(context);

    if (isSessionIdCookieEnabled()) {
      Serializable sessionId = session.getId();
      storeSessionId(sessionId, request, response);
    } else {
      log.debug(
          "Session ID cookie is disabled.  No cookie has been set for new session with id {}",
          session.getId());
    }

    request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
    request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
  }
Esempio n. 4
0
  /** 获取头部信息 */
  @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);
  }
  /** 显示用户列表(用户组) */
  @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;
  }
  @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);
  }
 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();
 }
Esempio n. 8
0
 @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);
       }
     }
   }
 }
Esempio n. 9
0
 @RequestMapping("/login")
 public ModelAndView login(
     HttpServletRequest request,
     HttpServletResponse response,
     @RequestParam String userName,
     @RequestParam String password,
     Boolean isRemeberMe)
     throws Exception {
   UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
   Subject subject = SecurityUtils.getSubject();
   subject.login(token);
   if (null != isRemeberMe && isRemeberMe) token.setRememberMe(true);
   if (subject.isAuthenticated()) {
     AuthenticationInfo info = new SimpleAuthenticationInfo(userName, password, userName);
     Subject currentUser = SecurityUtils.getSubject();
     Session session = currentUser.getSession();
     User user = new User();
     user.setUserName(userName);
     user.setPassword(password);
     Env env = new Env();
     env.setUser(user);
     session.setAttribute("env", env);
     GlobalConfigHolder.setEnv(env);
     ModelAndView view = createLayoutView("admin/index", request, response);
     return view;
   } else return createSingleView("login/login", request, response);
 }
 public void onStop(Session session) {
   // TODO Auto-generated method stub
   logger.debug(
       " ===onStop=== "
           + "sessionid:"
           + session.getId()
           + " sessiontimeout:"
           + session.getTimeout());
 }
Esempio n. 11
0
 /* ===============================权限================================== */
 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); // 菜单权限
 }
Esempio n. 12
0
 /**
  * 将一些数据放到ShiroSession中,以便于其它地方使用
  *
  * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
  */
 private void setSession(Object key, Object value) {
   Subject currentUser = SecurityUtils.getSubject();
   if (null != currentUser) {
     Session session = currentUser.getSession();
     System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
     if (null != session) {
       session.setAttribute(key, value);
     }
   }
 }
Esempio n. 13
0
  /**
   * 用户注销
   *
   * @param
   * @return
   */
  @RequestMapping(value = "/logout")
  public ModelAndView logout() {
    ModelAndView mv = this.getModelAndView();
    PageData pd = new PageData();

    // shiro管理的session
    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();

    session.removeAttribute(Const.SESSION_USER);
    session.removeAttribute(Const.SESSION_ROLE_RIGHTS);
    session.removeAttribute(Const.SESSION_allmenuList);
    session.removeAttribute(Const.SESSION_menuList);
    session.removeAttribute(Const.SESSION_QX);
    session.removeAttribute(Const.SESSION_userpds);
    session.removeAttribute(Const.SESSION_USERNAME);
    session.removeAttribute(Const.SESSION_USERROL);
    session.removeAttribute("changeMenu");

    // shiro销毁登录
    //		Subject subject = SecurityUtils.getSubject();
    currentUser.logout();

    pd = this.getPageData();
    String msg = pd.getString("msg");
    pd.put("msg", msg);

    pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
    mv.setViewName("system/admin/login");
    mv.addObject("pd", pd);
    return mv;
  }
Esempio n. 14
0
  /** 显示用户列表(用户组) */
  @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;
  }
  /** 重写父类方法,在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);
  }
Esempio n. 17
0
 @Override
 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
     throws AuthenticationException {
   UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
   User user = userService.findByUserName(token.getUsername());
   Session session = SecurityUtils.getSubject().getSession();
   if (user == null) {
     throw new AuthorizationException("用户不存在");
   }
   SimpleAuthenticationInfo info = null;
   if (user.getUsername().equals(token.getUsername())) {
     info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
     session.setAttribute("user", user);
   }
   return info;
 }
 public void validateSessions() {
   if (logger.isInfoEnabled()) logger.info("Validating all active sessions...");
   int invalidCount = 0;
   Collection<?> activeSessions = getActiveSessions();
   if (activeSessions != null && !activeSessions.isEmpty()) {
     for (Iterator<?> i$ = activeSessions.iterator(); i$.hasNext(); ) {
       Session session = (Session) i$.next();
       try {
         SessionKey key = new DefaultSessionKey(session.getId());
         validate(session, key);
       } catch (InvalidSessionException e) {
         if (cacheManager != null) {
           SimpleSession s = (SimpleSession) session;
           if (s.getAttribute(SysConstans.SESSION_USER) != null)
             cacheManager.getCache(null).remove(s.getAttribute(SysConstans.SESSION_USER));
         }
         if (logger.isDebugEnabled()) {
           boolean expired = e instanceof ExpiredSessionException;
           String msg =
               (new StringBuilder())
                   .append("Invalidated session with id [")
                   .append(session.getId())
                   .append("]")
                   .append(expired ? " (expired)" : " (stopped)")
                   .toString();
           logger.debug(msg);
         }
         invalidCount++;
       }
     }
   }
   if (logger.isInfoEnabled()) {
     String msg = "Finished session validation.";
     if (invalidCount > 0)
       msg =
           (new StringBuilder())
               .append(msg)
               .append("  [")
               .append(invalidCount)
               .append("] sessions were stopped.")
               .toString();
     else msg = (new StringBuilder()).append(msg).append("  No sessions were stopped.").toString();
     logger.info(msg);
   }
 }
Esempio n. 19
0
  /**
   * @方法名: 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;
  }
 protected Session createExposedSession(Session session, SessionContext context) {
   if (!WebUtils.isWeb(context)) {
     return super.createExposedSession(session, context);
   }
   ServletRequest request = WebUtils.getRequest(context);
   ServletResponse response = WebUtils.getResponse(context);
   SessionKey key = new WebSessionKey(session.getId(), request, response);
   return new DelegatingSession(this, key);
 }
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    SessionIdToken sessionIdToken = (SessionIdToken) token;
    final Subject subject =
        new Subject.Builder().sessionId(sessionIdToken.getSessionId()).buildSubject();
    final Session session = subject.getSession(false);
    if (session == null) {
      LOG.debug(
          "Invalid session {}. Either it has expired or did not exist.",
          sessionIdToken.getSessionId());
      return null;
    }

    final Object username = subject.getPrincipal();
    final User user = userService.load(String.valueOf(username));
    if (user == null) {
      LOG.debug("No user named {} found for session {}", username, sessionIdToken.getSessionId());
      return null;
    }
    if (user.isExternalUser() && !ldapAuthenticator.isEnabled()) {
      throw new LockedAccountException("LDAP authentication is currently disabled.");
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("Found session {} for user name {}", session.getId(), username);
    }

    @SuppressWarnings("unchecked")
    final MultivaluedMap<String, String> requestHeaders =
        (MultivaluedMap<String, String>) ThreadContext.get("REQUEST_HEADERS");
    // extend session unless the relevant header was passed.
    if (requestHeaders == null
        || !"true".equalsIgnoreCase(requestHeaders.getFirst("X-Graylog-No-Session-Extension"))) {
      session.touch();
    } else {
      LOG.debug("Not extending session because the request indicated not to.");
    }
    ThreadContext.bind(subject);

    return new SimpleAccount(user.getName(), null, "session authenticator");
  }
Esempio n. 22
0
  @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());
  }
Esempio n. 23
0
  /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    ShiroEmp shiroEmp = (ShiroEmp) principals.getPrimaryPrincipal();
    EosEmp eosEmp = eosEmpService.findByEno(shiroEmp.loginName);

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    /* 系统不使用角色 */
    /*
     * List<String> resourceList =
     * eosEmpService.getAllRoleAction(eosEmp.getRoleId());
     * info.addStringPermissions(resourceList); String roleName =
     * eosRoleService.getRoleName(eosEmp.getRoleId());
     * info.addRole(roleName);
     */

    Session session = SecurityUtils.getSubject().getSession();
    session.setAttribute("eosEmp", eosEmp);
    return info;
  }
Esempio n. 24
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setContentType("image/png");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    try {
      Session session = SecurityUtils.getSubject().getSession();

      String token =
          EncoderHelper.getChallangeAndWriteImage(captchaService, "png", res.getOutputStream());
      session.removeAttribute(KEY_CAPTCHA);
      session.setAttribute(KEY_CAPTCHA, token);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void run() {
    if (log.isDebugEnabled()) {
      log.debug("Executing session validation...");
    }
    long startTime = System.currentTimeMillis();

    String sql = "select session from sessions limit ?,?";
    int start = 0;
    int size = 20;
    List<String> sessionList =
        this.jdbcTemplate.queryForList(
            sql, String.class, new Object[] {Integer.valueOf(start), Integer.valueOf(size)});
    while (sessionList.size() > 0) {
      for (String sessionStr : sessionList)
        try {
          Session session = null;
          Method validateMethod =
              ReflectionUtils.findMethod(
                  AbstractValidatingSessionManager.class,
                  "validate",
                  new Class[] {Session.class, SessionKey.class});
          validateMethod.setAccessible(true);
          ReflectionUtils.invokeMethod(
              validateMethod,
              this.sessionManager,
              new Object[] {session, new DefaultSessionKey(session.getId())});
        } catch (Exception e) {
        }
      start += size;
      sessionList =
          this.jdbcTemplate.queryForList(
              sql, String.class, new Object[] {Integer.valueOf(start), Integer.valueOf(size)});
    }

    long stopTime = System.currentTimeMillis();
    if (log.isDebugEnabled())
      log.debug(
          "Session validation completed successfully in "
              + (stopTime - startTime)
              + " milliseconds.");
  }
Esempio n. 26
0
  /** 保存皮肤 */
  @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);
    }
  }
Esempio n. 27
0
 // 获得当前角色下的指定菜单下的所有操作
 @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();
 }
  @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;
  }
Esempio n. 29
0
  @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";
  }
Esempio n. 30
0
  /** 获取用户权限 */
  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;
  }