Java Code Examples for org.apache.shiro.session.Session#getAttribute()

The following examples show how to use org.apache.shiro.session.Session#getAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserNameRealm.java    From Shiro-Action with MIT License 6 votes vote down vote up
public void clearAuthCacheByUserId(Integer userId) {
    // 获取所有 session
    Collection<Session> sessions = sessionDAO.getActiveSessions();
    for (Session session : sessions) {
        // 获取 session 登录信息。
        Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (obj instanceof SimplePrincipalCollection) {
            // 强转
            SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
            User user = new User();
            BeanUtils.copyProperties(spc.getPrimaryPrincipal(), user);
            // 判断用户, 匹配用户ID.
            if (userId.equals(user.getUserId())) {
                this.doClearCache(spc);
            }
        }
    }
}
 
Example 2
Source File: UpmsSessionForceLogoutFilter.java    From zheng with MIT License 5 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    Session session = getSubject(request, response).getSession(false);
    if(session == null) {
        return true;
    }
    boolean forceout = session.getAttribute("FORCE_LOGOUT") == null;
    return  forceout;
}
 
Example 3
Source File: UserOnlineServiceImpl.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void kickoutByAccount(String account) {
	if (Strings.isNullOrEmpty(account)) return;
	Collection<Session> sessions = sessionDAO.getActiveSessions();
	if (sessions.size() <= 0) return;
	System.out.println("kickoutByAccount sessions size is :" + sessions.size());
	for(Session session : sessions){
		Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		if (obj != null) {
			String tempName = obj.toString();
			if (account.equals(tempName)) {
				// 会话已失效  但在线列表仍可获取Session会话对象
				session.setAttribute("kickout", true); // 标记为已下线
				session.setTimeout(0L); //设置session立即失效,即将其踢出系统break;
				// session.stop(); //销毁Shiro的会话
				
				// 记录日志
				LoginLog log = new LoginLog();
				log.setUserId(account);
				log.setLoginType((short) 1);
				log.setLoginDesc("账号异地登录,被迫强制下线");
				log.setIpInfoCountry(null);
				log.setIpInfoRegion(null);
				log.setIpInfoCity(null);
				log.setIpInfoIsp(null);
				log.setLoginIp(RequestUtil.getAddr(RequestUtil.getRequest()));
				log.setLoginTime(new Timestamp(new Date().getTime()));
				
				// 保存退出日志
				loginLogMapper.insert(log);
				break;
			}
		}
	}
}
 
Example 4
Source File: SubjectUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static UUID getOrganizationId() {
    Subject currentUser = getSubject();
    if ( currentUser == null ) {
        return null;
    }
    if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) {
        return null;
    }
    Session session = currentUser.getSession();
    OrganizationInfo organization = ( OrganizationInfo ) session.getAttribute( "organization" );
    if ( organization == null ) {
        return null;
    }
    return organization.getUuid();
}
 
Example 5
Source File: UserService.java    From Shiro-Action with MIT License 5 votes vote down vote up
/**
 * 删除所有此用户的在线用户
 */
public void offlineByUserId(Integer userId) {
    Collection<Session> activeSessions = sessionDAO.getActiveSessions();
    for (Session session : activeSessions) {
        SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (simplePrincipalCollection != null) {
            User user = (User) simplePrincipalCollection.getPrimaryPrincipal();
            if (user != null && userId.equals(user.getUserId())) {
                offlineBySessionId(String.valueOf(session.getId()));
            }
        }
    }
}
 
Example 6
Source File: UserOnlineServiceImpl.java    From belling-admin with Apache License 2.0 5 votes vote down vote up
/**
 * 从session中获取UserOnline对象
 * 
 * @param session
 * @return
 */
private UserOnlineDTO getSessionDTO(Session session){
	if (null == session) {
		return null;
	}
	Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
	if (null == obj) {
		return null;
	}
	//存储session
	UserOnlineDTO userDto = new UserOnlineDTO();
	// 登录账号
	userDto.setLoginAccount(obj.toString());
	//最后一次和系统交互的时间
	userDto.setLastAccess(session.getLastAccessTime());
	// 开始时间
	userDto.setStartTime(session.getStartTimestamp());
	//主机的ip地址
	userDto.setIp(session.getHost());
	//session ID
	userDto.setSessionId(session.getId().toString());
	//回话到期 ttl(ms)
	userDto.setTimeout(session.getTimeout());
	//session创建时间
	userDto.setStartTime(session.getStartTimestamp());
	return userDto;
}
 
Example 7
Source File: AllOpenController.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
@GetMapping(value="/checkSessionExist")
@ResponseBody
public String checkSessionExist(HttpServletRequest request, 
 			             	        HttpServletResponse response){
	Session session = ShiroUtil.getSession();
	Object object = session.getAttribute(Constant.SESSION_USER);
	JSONObject jsonObject = new JSONObject();
	if(object==null){
		jsonObject.put(Constant.STATUS, Constant.STATUS_FAIL);
	}else{
		jsonObject.put(Constant.STATUS, Constant.STATUS_SUCCESS);
	}
	return jsonObject.toString();
}
 
Example 8
Source File: SystemAuthorizingRealm.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 认证回调函数, 登录时调用
 */
@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;
	}
}
 
Example 9
Source File: SubjectUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static BiMap<UUID, String> getOrganizations() {
    Subject currentUser = getSubject();
    if ( !isOrganizationAdmin() ) {
        return null;
    }
    Session session = currentUser.getSession();
    BiMap<UUID, String> organizations = HashBiMap.create();
    Map map = (Map)session.getAttribute( "organizations" );
    organizations.putAll(map);
    return organizations;
}
 
Example 10
Source File: CacheSessionDAO.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
 * 获取活动会话
 * @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
 * @param principal 根据登录者对象获取活动会话
 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
	// 如果包括离线,并无登录者条件。
	if (includeLeave && principal == null){
		return getActiveSessions();
	}
	Set<Session> sessions = Sets.newHashSet();
	for (Session session : getActiveSessions()){
		boolean isActiveSession = false;
		// 不包括离线并符合最后访问时间小于等于3分钟条件。
		if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
			isActiveSession = true;
		}
		// 符合登陆者条件。
		if (principal != null){
			PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
				isActiveSession = true;
			}
		}
		// 过滤掉的SESSION
		if (filterSession != null && filterSession.getId().equals(session.getId())){
			isActiveSession = false;
		}
		if (isActiveSession){
			sessions.add(session);
		}
	}
	return sessions;
}
 
Example 11
Source File: ShiroUtil.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static boolean hasJurisdiction(String path){
	Session session = getSession(); 
	if(path.matches((String)session.getAttribute(Constant.AUTHORITY_CHAEK_PATH))){//关键请求检查
		//List<Role> roleList = (List<Role>) session.getAttribute(Constant.SESSION_ROLE);
		//List<Module> moduleList = (List<Module>) session.getAttribute(Constant.SESSION_MODULE);
		List<Module> operationList = (List<Module>) session.getAttribute(Constant.SESSION_OPERATION);
		return FunctionAndOperationHandler.checkHasOperation(path, operationList);
	}
	return true;
}
 
Example 12
Source File: OperatorRealm.java    From roncoo-pay with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String loginName = (String) principals.getPrimaryPrincipal();

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
    PmsOperator operator = (PmsOperator) session.getAttribute("PmsOperator");
    if (operator == null) {
        operator = pmsOperatorService.findOperatorByLoginName(loginName);
        session.setAttribute("PmsOperator", operator);
    }
    // 根据登录名查询操作员
    Long operatorId = operator.getId();

    Set<String> roles = (Set<String>) session.getAttribute("ROLES");
    if (roles == null || roles.isEmpty()) {
        roles = pmsOperatorRoleService.getRoleCodeByOperatorId(operatorId);
        session.setAttribute("ROLES", roles);
    }
    // 查询角色信息
    authorizationInfo.setRoles(roles);

    Set<String> permisstions = (Set<String>) session.getAttribute("PERMISSIONS");
    if (permisstions == null || permisstions.isEmpty()) {
        permisstions = pmsRolePermissionService.getPermissionsByOperatorId(operatorId);
        session.setAttribute("PERMISSIONS", permisstions);
    }
    // 根据用户名查询权限
    authorizationInfo.setStringPermissions(permisstions);
    return authorizationInfo;
}
 
Example 13
Source File: IamSubjectFactory.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
/**
 * Assertion request accessToken(signature) validity.
 * 
 * @param context
 * @throws UnauthenticatedException
 * @see {@link AbstractIamAuthenticationFilter#makeLoggedResponse}
 */
private final void assertRequestAccessTokenValidity(SubjectContext context) throws UnauthenticatedException {
	// Additional signature verification will only be performed on those
	// who have logged in successful.
	// e.g: Authentication requests or internal API requests does not
	// require signature verification.
	if (context.isAuthenticated() || isNull(context.getSession()))
		return;

	WebSubjectContext wsc = (WebSubjectContext) context;
	Session session = wsc.getSession();
	HttpServletRequest request = toHttp(wsc.resolveServletRequest());

	// Gets protocol configure info.
	String sessionId = valueOf(session.getId());
	String accessTokenSignKey = (String) session.getAttribute(KEY_ACCESSTOKEN_SIGN_NAME);
	IamAuthenticationToken authcToken = (IamAuthenticationToken) session.getAttribute(KEY_AUTHC_TOKEN);

	// Gets request accessToken.
	final String accessToken = getRequestAccessToken(request);
	log.debug("Asserting accessToken, sessionId:{}, accessTokenSignKey: {}, authcToken: {}, accessToken: {}", sessionId,
			accessTokenSignKey, authcToken, accessToken);

	// Only the account-password authentication is verified.
	// if (authcToken instanceof ClientSecretIamAuthenticationToken) {
	hasText(accessToken, UnauthenticatedException.class, "accessToken is required");
	hasText(sessionId, UnauthenticatedException.class, "sessionId is required");
	hasText(accessTokenSignKey, UnauthenticatedException.class, "No accessTokenSignKey"); // Shouldn't-here

	// Calculating accessToken(signature).
	final String validAccessToken = generateAccessToken(session, accessTokenSignKey);
	log.debug(
			"Asserted accessToken of sessionId: {}, accessTokenSignKey: {}, validAccessToken: {}, accessToken: {}, authcToken: {}",
			sessionId, accessTokenSignKey, validAccessToken, accessToken, authcToken);

	// Compare accessToken(signature)
	if (!accessToken.equals(validAccessToken)) {
		throw new InvalidAccessTokenAuthenticationException(
				format("Illegal authentication accessToken: %s, accessTokenSignKey: %s", accessToken, accessTokenSignKey));
	}
	// }

}
 
Example 14
Source File: LoginController.java    From dpCms with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @Title: loginDo 
 * @Description: 平台登录
 * @param @param username
 * @param @param password
 * @return Response 返回类型,如果成功返回跳转的URL
 * @throws
 */
@RequestMapping(value = "/login")
@ResponseBody
public Response login(String username, String password, String logincode , Response response ) {
	String msg = "";
	Subject currentUser = SecurityUtils.getSubject();
	Session session = currentUser.getSession();
	String codeSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
	if (StringUtils.isBlank(logincode) || StringUtils.isBlank(codeSession)
			|| !logincode.equals(codeSession)) {
		response.setStateCode(StateCode.LOGIN_FAIL);
		msg = "验证码不正确,朋友!";
	} else {
		AuthenticationToken token = new UsernamePasswordToken(username,password);
		Account account = accountService.findByLoginName(username);
		try {
			currentUser.login(token);
			account.setPassword("");
			// 获取当前登录用户的岗位信息。
			CurrentInfo currentInfo = currentUserInfoService.findCurrentUserInfo(account);
			Employee emplpyee = currentInfo.getEmployee();
			if (emplpyee == null || emplpyee.getDefaultPostId() == null) {
				throw new AccountNoActiceException();
			}
			long defaultPostId = emplpyee.getDefaultPostId();

			// 遍历岗位信息,如果有一个岗位不需要过滤权限,那么这个人不需要过滤权限
			Set<Post> postSet = currentInfo.getPostList();
			Iterator<Post> it = postSet.iterator();
			if (it.hasNext()) {
				Post post = it.next();
				if (post.getNeedFilter() == null) {// 当前登录的员工不需要过滤任何权限
					currentInfo.setNeedFilter(false);
				}
				if (post.getId() == defaultPostId) {// 该人的默认岗位
					currentInfo.setDefaultPostId(defaultPostId);// 保存到SESSION里,快速获取
					currentInfo.setIndexPage(post.getIndexPage());// 保存到SESSION里,快速获取
					currentUser.getSession().setAttribute("currentInfo", currentInfo);
					response.setStateCode(StateCode.OK);
					response.setData("index.html");// 把该人应该跳转的页面返回到客户端
				}
			}

			msg = "登录成功";
		} catch (UnknownAccountException uae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户不存在!";
		} catch (IncorrectCredentialsException ice) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户名或密码错误!";
		} catch (LockedAccountException lae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户为锁定状态!";
		} catch (AuthenticationException ae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			ae.printStackTrace();
			msg = "登录失败!";
		} catch (AccountNoActiceException ana) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "该帐号未激活!";
		} catch (Exception e) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			e.printStackTrace();
			msg = "平台繁忙!";
		}
	}
	response.setMessage(msg);
	currentUser.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
	return response;
}
 
Example 15
Source File: LoginBean.java    From init-spring with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, HttpServletRequest request)
{
	Subject subject=SecurityUtils.getSubject();
	if(subject.isAuthenticated()||subject.isRemembered()){
		return "redirect:/home";
	}
	
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String loginKaptchaCode = request.getParameter("code");

	Session shiroSession = subject.getSession();
	Object kaptchaCode = shiroSession.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

	if (kaptchaCode!=null && !StringUtils.equalsIgnoreCase(loginKaptchaCode, kaptchaCode.toString()))
	{
		model.addAttribute("message", "验证码错误!");
		return "/login";
	}

	UsernamePasswordToken token = new UsernamePasswordToken(username, password, false, request.getRemoteHost());
	try
	{
		subject.login(token);
		User user = jpaRealmRepository.findUserByName(username);
		user.setLastLogin(new Date());
		user = jpaRealmRepository.mergeUser(user);

		return "redirect:/home";
	} catch (UnknownAccountException uae)
	{
		model.addAttribute("message", "Unknown User!");
		log.info("Unknown User!");
	} catch (IncorrectCredentialsException ice)
	{
		model.addAttribute("message", "Incorrect Password!");
		log.info("Incorrect Password!");
	} catch (LockedAccountException lae)
	{
		model.addAttribute("message", "User Locked!");
		log.info("User Locked!");
	} catch (AuthenticationException ae)
	{
		model.addAttribute("message", "Authentication Failed!");
		log.info("Authentication Failed!");
	} 
	return "/login";
}
 
Example 16
Source File: JedisSessionDAO.java    From NutzSite with Apache License 2.0 4 votes vote down vote up
@Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            return;
        }

        HttpServletRequest request = Mvcs.getReq();
        if (request != null){
            String uri = request.getServletPath();
            // 如果是静态文件,则不更新SESSION
            if (isStaticFile(uri)){
                return;
            }

            // 手动控制不更新SESSION
//            if (Global.NO.equals(request.getParameter("updateSession"))){
//                return;
//            }
        }

        Jedis jedis = null;
        try {

            jedis = jedisAgent.getResource();

            // 获取登录者编号
            PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;

            jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
            jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));

            // 设置超期时间
            int timeoutSeconds = (int)(session.getTimeout() / 1000);
            jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);

            logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
        } catch (Exception e) {
            logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
        } finally {
           Streams.safeClose(jedis);
        }
    }
 
Example 17
Source File: ShiroKit.java    From SpringBootBucket with MIT License 4 votes vote down vote up
/**
 * 获取shiro指定的sessionKey
 */
@SuppressWarnings("unchecked")
public static <T> T getSessionAttr(String key) {
    Session session = getSession();
    return session != null ? (T) session.getAttribute(key) : null;
}
 
Example 18
Source File: Main.java    From java-course-ee with MIT License 4 votes vote down vote up
public static void main(String[] args) {


        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log("May the Schwartz be with you!");
        } else {
            log("Hello, mere mortal.");
        }

        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:weild")) {
            log("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //all done - log out!
        currentUser.logout();

        System.exit(0);

    }
 
Example 19
Source File: OnlineController.java    From frpMgr with MIT License 4 votes vote down vote up
/**
 * 在线用户列表数据
 * @param request
 * @param response
 * @author ThinkGem
 */
@RequiresPermissions("sys:online:view")
@RequestMapping(value = "listData")
@ResponseBody
public List<Map<String, Object>> listData(String isAllOnline, String isVisitor, String sessionId, 
		String userCode, String userName, String userType, String orderBy) {
	List<Map<String, Object>> list = Lists.newArrayList();
	boolean excludeLeave = isAllOnline==null || !Global.YES.equals(isAllOnline);
	boolean excludeVisitor = isVisitor==null || !Global.YES.equals(isVisitor);
		Collection<Session> sessions = sessionDAO.getActiveSessions(excludeLeave, 
			excludeVisitor, null, sessionId, userCode);
	long currentTime = System.currentTimeMillis();
	for (Session session : sessions){
		if (StringUtils.isNotBlank(userName) && ((String)session.getAttribute("userName")).contains(userName)){
			continue;
		}
		if (StringUtils.isNotBlank(userType) && ((String)session.getAttribute("userType")).equals(userType)){
			continue;
		}
		Map<String, Object> map = Maps.newLinkedHashMap();
		// 为了安全性,需要有权限的人才能看
		if (UserUtils.getSubject().isPermitted("sys:online:edit")){
			map.put("id", session.getId().toString()); 
		}
		map.put("startTimestamp", DateUtils.formatDateTime(session.getStartTimestamp()));
		map.put("lastAccessTime", DateUtils.formatDateTime(session.getLastAccessTime()));
		map.put("timeout", TimeUtils.formatDateAgo(session.getTimeout()-(currentTime-session.getLastAccessTime().getTime())));
		PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		LoginInfo principal = (pc != null ? (LoginInfo)pc.getPrimaryPrincipal() : null);
		if (principal != null){
			map.put("userCode", session.getAttribute("userCode"));// principal.getId());
			map.put("userName", session.getAttribute("userName"));// principal.getName());
			map.put("userType", session.getAttribute("userType"));// ObjectUtils.toString(principal.getParam("userType")));
			map.put("deviceType", ObjectUtils.toString(principal.getParam("deviceType")));
		}
		map.put("host", session.getHost());
		list.add(map);
	}
	// 本地排序
	if (StringUtils.isNotBlank(orderBy)){
		final String[] ss = orderBy.trim().split(" ");
		if (ss != null && ss.length == 2){
			Collections.sort(list, new Comparator<Map<String, Object>>() {
				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					String s1 = (String)o1.get(ss[0]);
					String s2 = (String)o2.get(ss[0]);
					if ("asc".equals(ss[1])){
						return s1.compareTo(s2);
					}else{
						return s2.compareTo(s1);
					}
				}});
		}
	}
	return list;
}
 
Example 20
Source File: ShiroUtil.java    From hdw-dubbo with Apache License 2.0 2 votes vote down vote up
/**
 * 获取shiro指定的sessionKey
 *
 * @param key
 * @param <T>
 * @return
 */
public static <T> T getSessionAttr(String key) {
    Session session = getSession();
    return session != null ? (T) session.getAttribute(key) : null;
}