Example #1
0
 /** @return */
 public static DBObject getLoggedUser() {
   Subject currentUser = SecurityUtils.getSubject();
   if (currentUser != null && currentUser.getPrincipal() != null) {
     DBObject user = (DBObject) currentUser.getPrincipal();
     return user;
   }
   return null;
 }
 public UserDTO getSessionUser() {
   Subject subject = SecurityUtils.getSubject();
   if (subject != null
       && subject.getPrincipal() != null
       && subject.getPrincipal() instanceof UserDTO) {
     return (UserDTO) subject.getPrincipal();
   }
   return null;
 }
 protected String getCurrentUserId() {
   Subject subject =
       ThreadContext.getSubject(); // Use ThreadContext directly, SecurityUtils will associate a
   // new Subject with the thread.
   if (subject != null && subject.getPrincipal() != null) {
     return subject.getPrincipal().toString();
   } else {
     return null;
   }
 }
  @Override
  @Nullable
  public User currentUser() throws UserNotFoundException {
    Subject subject = getSubject();
    if (subject.getPrincipal() == null) {
      return null;
    }

    return getUser(subject.getPrincipal().toString());
  }
 public Long getSessionUserId() {
   Subject subject = SecurityUtils.getSubject();
   UserDTO user = null;
   if (subject != null
       && subject.getPrincipal() != null
       && subject.getPrincipal() instanceof UserDTO) {
     user = (UserDTO) subject.getPrincipal();
     if (user != null) {
       return user.getId();
     }
   }
   return null;
 }
 /**
  * @Title: editParClientLevel @Description: TODO(修改客户等级信息)
  *
  * @param @param parClientLevel
  * @param @return 设定文件
  * @return Object 返回类型
  * @throws
  */
 @Transactional(readOnly = false)
 @MethodLog(opera = "ClientLevelList_edit")
 public Object editParClientLevel(ParClientLevel parClientLevel) {
   Subject pricipalSubject = SecurityUtils.getSubject();
   User pricipalUser = (User) pricipalSubject.getPrincipal();
   JqReturnJson returnResult = new JqReturnJson(); // 构建返回结果,默认结果为false
   ParClientLevelExample parClientLevelExample = new ParClientLevelExample();
   int count = 0;
   // 防止客户等级名称重复
   parClientLevelExample
       .createCriteria()
       .andClientLevelNameEqualTo(parClientLevel.getClientLevelName())
       .andClientLevelIdNotEqualTo(parClientLevel.getClientLevelId());
   count = parClientLevelMapper.countByExample(parClientLevelExample);
   if (count > 0) {
     returnResult.setMsg("客户等级名称重复");
     return returnResult;
   }
   // 更新更新人和更新时间
   parClientLevel.setUpdater(pricipalUser.getUserCnName());
   parClientLevel.setUpdateTime(new Date());
   count = parClientLevelMapper.updateByPrimaryKeySelective(parClientLevel);
   if (count == 1) {
     returnResult.setSuccess(true);
     returnResult.setMsg("[" + parClientLevel.getClientLevelName() + "] 客户等级信息已保存");
   } else {
     returnResult.setMsg("发生未知错误,客户等级信息保存失败");
   }
   return returnResult;
 }
Example #7
0
 @RequestMapping(value = "/approveRequests", method = RequestMethod.GET)
 @ResponseBody
 public List<AuthorizationApplications> listAreqs() {
   Subject subject = SecurityUtils.getSubject();
   String username = (String) subject.getPrincipal();
   return oauthorizationApplicationsService.findWaitForApproveByResourceOwner(username);
 }
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
      throws IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Subject subject = getSubject(request, response);
    if (subject.getPrincipal() == null) {
      if ("XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
        httpResponse.setStatus(401);
        JsonUtil.toJson(new Jo(Jo.CODE_UNLOGIN, "登录超时,请重新登录"), httpResponse);
      } else {
        if (httpRequest.getRequestURI().indexOf("/admin") >= 0) {
          saveRequestAndRedirectToLogin(request, response);
        } else {
          httpResponse.sendRedirect(
              httpRequest.getContextPath()
                  + "/index/loginredirect?redirect="
                  + httpRequest.getRequestURL());
        }
      }
    } else {
      if ("XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
        JsonUtil.toJson(new Jo(Jo.CODE_NOPERMISSION, "未授权的操作"), httpResponse);
      } else {
        String unauthorizedUrl = getUnauthorizedUrl();
        if (StringUtils.isEmpty(unauthorizedUrl)) {
          WebUtils.redirectToSavedRequest(request, response, unauthorizedUrl);
        } else {
          WebUtils.toHttp(response).sendError(401);
        }
      }
    }
    return false;
  }
  @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);
  }
Example #10
0
  /** 头部栏目 */
  @RequestMapping(value = "/headbar", method = RequestMethod.GET)
  public String headbar(HttpServletRequest request, HttpSession session, Model model) {

    String backurl = request.getParameter("backurl");
    //        System.out.println(backurl);

    Subject subject = SecurityUtils.getSubject();
    // 已登陆则 获取信息
    if (subject.isAuthenticated()) {

      String username = String.valueOf(subject.getPrincipal());
      //            System.out.println("登录用户"+username);

      List<Role> roleInfos = roleService.selectRolesByUsername(username);
      //            request.getSession().setAttribute("roleInfos", roleInfos);

      String ticket = UUID.randomUUID().toString();
      cache.set(ticket, gson.toJson(roleInfos), 60);
      //            System.out.println(ticket);
      //            logger.info(ticket);
      //            logger.info(cache.get(ticket));
      model.addAttribute("ticket", ticket);

    } else {
      session.removeAttribute("userInfo");
      //            System.out.println("未登录");
    }

    model.addAttribute("backurl", (backurl == null || "".equals(backurl)) ? successUrl : backurl);

    return "authmanager/headbar";
  }
Example #11
0
  public Object getPrincipalProperty(String property) {
    Subject subject = SecurityUtils.getSubject();

    if (subject != null) {
      Object principal = subject.getPrincipal();

      try {
        BeanInfo bi = Introspector.getBeanInfo(principal.getClass());

        for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
          if (pd.getName().equals(property) == true) {
            return pd.getReadMethod().invoke(principal, (Object[]) null);
          }
        }

        logger.trace(
            "Property [{}] not found in principal of type [{}]",
            property,
            principal.getClass().getName());
      } catch (Exception e) {
        logger.trace(
            "Error reading property [{}] from principal of type [{}]",
            property,
            principal.getClass().getName());
      }
    }

    return null;
  }
 /**
  * @Title: editSuppliers @Description: TODO(这修改供应商来源信息信息)
  *
  * @param @param Suppliers
  * @param @return 设定文件
  * @return Object 返回类型
  * @throws
  */
 @Transactional(readOnly = false)
 @MethodLog(opera = "SuppliersSourceList_edit")
 public Object editSuppliersSource(ParSuppliersSource suppliersSource) {
   Subject pricipalSubject = SecurityUtils.getSubject();
   User pricipalUser = (User) pricipalSubject.getPrincipal();
   JqReturnJson returnResult = new JqReturnJson(); // 构建返回结果,默认结果为false
   ParSuppliersSourceExample suppliersSourceExample = new ParSuppliersSourceExample();
   int count = 0;
   // 防止名称重复
   suppliersSourceExample
       .createCriteria()
       .andSourceNameEqualTo(suppliersSource.getSourceName())
       .andSourceIdNotEqualTo(suppliersSource.getSourceId());
   count = suppliersSourceMapper.countByExample(suppliersSourceExample);
   if (count > 0) {
     returnResult.setMsg("供应商来源信息名称重复");
     returnResult.setSuccess(false);
     return returnResult;
   }
   suppliersSource.setUpdater(pricipalUser.getUserCnName());
   suppliersSource.setUpdateTime(new Date());
   count = suppliersSourceMapper.updateByPrimaryKeySelective(suppliersSource);
   if (count == 1) {
     returnResult.setSuccess(true);
     returnResult.setMsg("信息已保存");
   } else {
     returnResult.setMsg("发生未知错误,信息保存失败");
   }
   return returnResult;
 }
  /**
   * 覆盖默认实现,用sendRedirect直接跳出框架,以免造成js框架重复加载js出错。
   *
   * @param token
   * @param subject
   * @param request
   * @param response
   * @return
   * @throws Exception
   * @see
   *     org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken,
   *     org.apache.shiro.subject.Subject, javax.servlet.ServletRequest,
   *     javax.servlet.ServletResponse)
   */
  @Override
  protected boolean onLoginSuccess(
      AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
      throws Exception {
    // issueSuccessRedirect(request, response);
    // we handled the success redirect directly, prevent the chain from continuing:
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal();
    // 加入ipAddress
    shiroUser.setIpAddress(request.getRemoteAddr());

    // 这个是放入user还是shiroUser呢?
    httpServletRequest.getSession().setAttribute(SecurityConstants.LOGIN_USER, shiroUser.getUser());

    if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))
        || request.getParameter("ajax") == null) { // 不是ajax请求
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
    } else {
      httpServletResponse.sendRedirect(
          httpServletRequest.getContextPath() + "/login/timeout/success");
    }

    return false;
  }
  @SuppressWarnings("unchecked")
  @Test
  public void test() {

    // 因为Realm里没有进行验证,所以相当于每个Realm都身份验证成功了
    login("classpath:shiro-multirealm.ini", "zhang", "123");
    Subject subject = subject();
    // 获取Primary Principal(即第一个)
    Object primaryPrincipal1 = subject.getPrincipal();
    PrincipalCollection princialCollection = subject.getPrincipals();
    Object primaryPrincipal2 = princialCollection.getPrimaryPrincipal();

    // 但是因为多个Realm都返回了Principal,所以此处到底是哪个是不确定的
    Assert.assertEquals(primaryPrincipal1, primaryPrincipal2);

    // 返回 a b c
    Set<String> realmNames = princialCollection.getRealmNames();
    System.out.println(realmNames);

    // 因为MyRealm1和MyRealm2返回的凭据都是zhang,所以排重了
    Set<Object> principals = princialCollection.asSet(); // asList和asSet的结果一样
    System.out.println(principals);

    // 根据Realm名字获取
    Collection<User> users = princialCollection.fromRealm("c");
    System.out.println(users);
  }
  @Override
  protected void onInitialize() {
    super.onInitialize();

    final Subject subject = SecurityUtils.getSubject();
    if (subject.getPrincipal() != null) {
      final Class<? extends Page> homePage = getApplication().getHomePage();
      log.info(
          "User '{}' is already logged in, redirecting to {}",
          subject.getPrincipal(),
          homePage.getName());
      getRequestCycle().setResponsePage(homePage);
    }

    add(new FormSignIn("formSignIn", getModel(), this));
  }
Example #16
0
  /** 用Mockito快速創建一個已認證的用户. */
  public static void mockSubject(Object principal) {
    Subject subject = Mockito.mock(Subject.class);
    Mockito.when(subject.isAuthenticated()).thenReturn(true);
    Mockito.when(subject.getPrincipal()).thenReturn(principal);

    bindSubject(subject);
  }
Example #17
0
  // 采购单受理列表json
  public String disposelist_result() throws Exception {
    YycgdQueryVo yycgdQueryVo = getModel();

    // 获取当前用户身份
    Subject subject = SecurityUtils.getSubject();
    ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
    // 从用户身份中获取供货商id
    String usergysid = activeUser.getSysid();
    // 列表的总数
    Long total = serviceFacade.getCgdService().findYycgdDisposeListCount(usergysid, yycgdQueryVo);
    // 计算分页参数
    PageParameter pageParameter =
        new PageParameter(yycgdQueryVo.getPage(), yycgdQueryVo.getRows(), total);

    // 查询采购药品明细列表
    List<Yycgd> yycgdList =
        serviceFacade
            .getCgdService()
            .findYycgdDisposeList(
                usergysid,
                yycgdQueryVo,
                pageParameter.getPageQuery_star(),
                pageParameter.getPageQuery_pageSize());

    // 创建datagridResultInfo
    this.setProcessResult(
        ResultUtil.createDataGridResultInfo(yycgdQueryVo.getPage(), total, yycgdList));

    return "disposelist_result";
  }
  public boolean isPerfilAdminstrador() {
    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser == null) {
      return false;
    } else {

      if (currentUser.getPrincipal() != null) {

        User user = new UserDao().getUser(currentUser.getPrincipal().toString());
        return user.getPerfil().toString().equals("ADMINISTRADOR");

      } else {

        return false;
      }
    }
  }
 /**
  * Get the user name of the current user
  *
  * @return user name of the current user
  */
 public String getUserName() {
   Subject currentUser = SecurityUtils.getSubject();
   if (currentUser == null) {
     return null;
   } else {
     return (String) currentUser.getPrincipal();
   }
 }
  @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 SessionUser getSessionUser() {
   Subject subject = SecurityUtils.getSubject();
   SessionUser sessionUser = (SessionUser) subject.getSession().getAttribute("SESSION_USER");
   if (sessionUser == null) {
     sessionUser = (SessionUser) subject.getPrincipal();
     subject.getSession().setAttribute("SESSION_USER", sessionUser);
   }
   return sessionUser;
 }
Example #22
0
 @RequestMapping(value = "/")
 public String success(Model model) {
   log.info("访问成功");
   Subject subject = SecurityUtils.getSubject();
   Set<String> permissions = userService.findPermissions(subject.getPrincipal().toString());
   List<Resource> menus = resourceService.findMenus(permissions);
   model.addAttribute("menus", menus);
   return "success";
 }
Example #23
0
 @RequestMapping(value = "/{id}/deal", method = RequestMethod.GET)
 public String listAreqs(
     @PathVariable("id") Long id, Model model, @RequestParam(value = "result") int result) {
   Subject subject = SecurityUtils.getSubject();
   String username = (String) subject.getPrincipal();
   oauthorizationApplicationsService.updateStatusById(
       id, username, AuthorizationStatus.fromElem(result));
   return "redirect:/client/approveRequests";
 }
Example #24
0
  @Test
  public void testLoginSuccess() {
    createUser(username, password);

    UsernamePasswordToken upToken = new UsernamePasswordToken(username, password);
    Subject subject = SecurityUtils.getSubject();
    subject.login(upToken);
    Assert.assertEquals(username, subject.getPrincipal());
  }
  @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());
  }
Example #26
0
 @Transactional(readOnly = true)
 public Admin getCurrent() {
   Subject subject = SecurityUtils.getSubject();
   if (subject != null) {
     Principal principal = (Principal) subject.getPrincipal();
     if (principal != null) {
       return adminDao.find(principal.getId());
     }
   }
   return null;
 }
Example #27
0
 @Transactional(readOnly = true)
 public String getCurrentUsername() {
   Subject subject = SecurityUtils.getSubject();
   if (subject != null) {
     Principal principal = (Principal) subject.getPrincipal();
     if (principal != null) {
       return principal.getUsername();
     }
   }
   return null;
 }
Example #28
0
 // Return the name of the loggedin user on this session, for test purposes
 @Path("/username")
 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String getUsername() {
   Subject subject = SecurityUtils.getSubject();
   if (subject.isAuthenticated()) {
     return ((UserInfo) subject.getPrincipal()).getName();
   } else {
     throw new WebApiException(Response.Status.UNAUTHORIZED, "No logged in user in this session");
   }
 }
  @Override
  public void deleteUser(String userId, String source)
      throws UserNotFoundException, NoSuchUserManagerException {
    checkNotNull(userId, "User ID may not be null");

    Subject subject = getSubject();
    if (subject.getPrincipal() != null && userId.equals(subject.getPrincipal().toString())) {
      throw new IllegalArgumentException("Can not delete currently signed in user");
    }

    AnonymousConfiguration anonymousConfiguration = anonymousManager.getConfiguration();
    if (anonymousConfiguration.isEnabled() && userId.equals(anonymousConfiguration.getUserId())) {
      throw new IllegalArgumentException("Can not delete anonymous user");
    }

    UserManager userManager = getUserManager(source);
    userManager.deleteUser(userId);

    // flush authc
    eventBus.post(new UserPrincipalsExpired(userId, source));
  }
Example #30
0
  private static Map<String, Object> getUserCache() {
    Map<String, Object> map = Maps.newHashMap();
    try {
      Subject subject = SecurityUtils.getSubject();
      ShiroPrincipal principal = (ShiroPrincipal) subject.getPrincipal();
      return principal != null ? principal.getCache() : map;
    } catch (UnavailableSecurityManagerException e) {

    } catch (InvalidSessionException e) {

    }
    return map;
  }