/** 显示用户列表(用户组) */ @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; }
/** 头部栏目 */ @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"; }
@ValidateParams({ @ValidateParam(value = "user.name", minLen = 4, maxLen = 12), @ValidateParam(value = "user.password", minLen = 6, maxLen = 20), @ValidateParam(value = "captcha", defaultValue = "@@@@", maxLen = 4, minLen = 4), @ValidateParam(value = "rememberMe", type = Boolean.class) }) @RequestMethod(Method.POST) public void signin() { User user = getModel(User.class, "user"); Sys_Common_Variable captcha = ComVarService.service.getComVarByName(Key.CAPTCHA); if (captcha != null && captcha.getToBoolean(Sys_Common_Variable.S_VALUE) && !validateCaptcha(getPara("captcha"))) { renderJson(new Message(captcha.getStr(Sys_Common_Variable.S_ERROR))); return; } Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(user.getStr(User.S_NAME), user.getStr(User.S_PASSWORD)); token.setRememberMe(getParaToBoolean("rememberMe")); subject.login(token); if (subject.isAuthenticated()) { subject.getSession().setAttribute(Lc4eCaptchaRender.captcha_code, Const.DEFAULT_NONE); } else { renderJson(new Message("Login failed")); } } renderJson(new Message(true, "Login Success")); }
/** * Get an Annis Binary object identified by its id. * * @param id * @param rawOffset the part we want to start from, we start from 0 * @param rawLength how many bytes we take * @return AnnisBinary */ @GET @Path("corpora/{top}/{document}/binary/{offset}/{length}") @Produces("application/xml") public AnnisBinary binary( @PathParam("top") String toplevelCorpusName, @PathParam("document") String corpusName, @PathParam("offset") String rawOffset, @PathParam("length") String rawLength, @QueryParam("mime") String mimeType) { Subject user = SecurityUtils.getSubject(); user.checkPermission("query:binary:" + toplevelCorpusName); int offset = Integer.parseInt(rawOffset); int length = Integer.parseInt(rawLength); AnnisBinary bin; log.debug( "fetching " + (length / 1024) + "kb (" + offset + "-" + (offset + length) + ") from binary " + toplevelCorpusName + "/" + corpusName); bin = annisDao.getBinary(toplevelCorpusName, corpusName, mimeType, offset + 1, length); log.debug("fetch successfully"); return bin; }
@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); }
/** * 返回实现IModule接口的列表 * * @param applicationId * @return */ @Override public List<ModuleBean> getModuleByApplication(String applicationId) { Subject subject = shiroService.getSubject(); List<IModule> moduleList = ModuleManager.getInstall().getModuleList(applicationId); List<ModuleBean> moduleBeanList = new ArrayList<ModuleBean>(); if (moduleList == null) moduleList = new ArrayList<IModule>(); Mapper mapper = new DozerBeanMapper(); // 找出所有对应权限的功能模块 if (moduleList != null && !moduleList.isEmpty()) { for (IModule module : moduleList) { // 调用isPermitted不能传入空字符,故此默认值为KALIX_NOT_PERMISSION String modulePermission = StringUtils.isEmpty(module.getPermission()) ? Const.KALIX_NO_PERMISSION : module.getPermission(); // 具有权限或不进行权限验证,都通过 if (subject.hasRole(modulePermission) || modulePermission.equals(Const.KALIX_NO_PERMISSION)) { ModuleBean moduleBean = mapper.map(module, ModuleBean.class); moduleBean.setText(module.getText()); moduleBeanList.add(moduleBean); } } } if (moduleBeanList != null && !moduleBeanList.isEmpty()) { for (ModuleBean moduleBean : moduleBeanList) { moduleBean.setChildren(new ArrayList<MenuBean>()); List<IMenu> menuList = new ArrayList<IMenu>(); List<IMenu> allMenu = MenuManager.getInstall().getMenuList(moduleBean.getId()); // 去掉没有权限的菜单 if (allMenu != null && !allMenu.isEmpty()) { for (IMenu menu : allMenu) { // 调用hasRole不能传入空字符,故此默认值为KALIX_NOT_PERMISSION String menuPermission = StringUtils.isEmpty(menu.getPermission()) ? Const.KALIX_NO_PERMISSION : menu.getPermission(); // 具有权限或不进行权限验证,都通过 if (subject.hasRole(menuPermission) || menuPermission.equals(Const.KALIX_NO_PERMISSION)) { menuList.add(menu); } } } List<IMenu> rootMenus = getRootMenus(menuList); if (rootMenus != null && !rootMenus.isEmpty()) { for (IMenu rootMenu : rootMenus) { MenuBean menuBean = null; if (rootMenu != null) { menuBean = mapper.map(rootMenu, MenuBean.class); menuBean.setText(rootMenu.getText()); getMenuChildren(menuBean, menuList, mapper); } moduleBean.getChildren().add(menuBean); } } } } return moduleBeanList; }
@GET @Path("search/find") @Produces("application/xml") public List<Match> find( @QueryParam("q") String query, @QueryParam("corpora") String rawCorpusNames, @DefaultValue("0") @QueryParam("offset") String offsetRaw, @DefaultValue("10") @QueryParam("limit") String limitRaw) throws IOException { requiredParameter(query, "q", "AnnisQL query"); requiredParameter(rawCorpusNames, "corpora", "comma separated list of corpus names"); Subject user = SecurityUtils.getSubject(); List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames); for (String c : corpusNames) { user.checkPermission("query:find:" + c); } int offset = Integer.parseInt(offsetRaw); int limit = Integer.parseInt(limitRaw); QueryData data = queryDataFromParameters(query, rawCorpusNames); data.setCorpusConfiguration(annisDao.getCorpusConfiguration()); data.addExtension(new LimitOffsetQueryData(offset, limit)); long start = new Date().getTime(); List<Match> matches = annisDao.find(data); long end = new Date().getTime(); logQuery("FIND", query, splitCorpusNamesFromRaw(rawCorpusNames), end - start); return matches; }
@Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { SourceUsernamePasswordToken token = (SourceUsernamePasswordToken) createToken(request, response); try { String username = getUsername(request); // 写入登录账号名称用于回显 request.setAttribute(KEY_AUTH_USERNAME_VALUE, username); User authAccount = userService.findByAuthTypeAndAuthUid(User.AuthTypeEnum.SYS, username); if (authAccount != null) { // 失败LOGON_FAILURE_LIMIT次,强制要求验证码验证 if (authAccount.getLogonFailureTimes() > LOGON_FAILURE_LIMIT) { String captcha = request.getParameter(captchaParam); if (StringUtils.isBlank(captcha) || !ImageCaptchaServlet.validateResponse((HttpServletRequest) request, captcha)) { throw new CaptchaValidationException("验证码不正确"); } } Subject subject = getSubject(request, response); subject.login(token); return onLoginSuccess(token, subject, request, response); } else { return onLoginFailure(token, new UnknownAccountException("登录账号或密码不正确"), request, response); } } catch (AuthenticationException e) { return onLoginFailure(token, e, request, response); } }
public static void main(String[] args) { // Using the IniSecurityManagerFactory, which will use the an INI file // as the security file. Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("C:\\auth.ini"); // Setting up the SecurityManager... org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); // SecurityUtils 对象是一个 singleton,这意味着不同的对象可以使用它来获得对当前用户的访问 // 一旦成功地设置了这个 SecurityManager,就可以在应用程序不同部分调用 SecurityUtils.getSubject() 来获得当前用户的信息 SecurityUtils.setSecurityManager(securityManager); // 获得当前用户的信息 Subject user = SecurityUtils.getSubject(); logger.info("User is authenticated: " + user.isAuthenticated()); // false UsernamePasswordToken token = new UsernamePasswordToken("bjangles11", "dance"); // 如果 token 的验证密码不正确, login() 方法会抛出一个 IncorrectCredentialsException // 在生产代码内这个异常应被明确捕获以便应用程序在用户提供了不正确的代码时能够进行恰当的响应。 // 如果用户不正确,login() 方法就会抛出一个 UnknownAccountException。我们既要考虑如何处理这个异常,但又不应向用户提供太多信息。 // 一种常见的做法是不要向用户提示用户名有效、只有密码不正确。这是因为如果有人试图通过猜测获得访问,那么您绝对不会想要暗示此人他所猜测的用户名是正确的 user.login(token); logger.info("User is authenticated: " + user.isAuthenticated()); // true }
/** 去新增用户页面 */ @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; }
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; }
/** * 根据角色id获取角色菜单关系测试方法. * * @throws Exception 普通异常. */ @Test public final void testQueryRoleMenuItemMap() throws Exception { Subject currentUser = ShiroHelper.getSubject(this.request, this.response); UsernamePasswordToken token = new UsernamePasswordToken("user1", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); token.setRememberMe(true); try { currentUser.login(token); UserPo uPo = new UserPo(); uPo.setUserId(Long.valueOf("1")); uPo.setLoginName("user1"); uPo.setPassword("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-01-12 23:30:20"); uPo.setCreateTime(date); uPo.setCreatorId(Long.valueOf("1")); uPo.setIsDelete(false); uPo.setIsLockUp(false); uPo.setVersion(Long.valueOf("0")); currentUser.getSession().setAttribute("user", uPo); } catch (Exception se) { se.printStackTrace(); } request.setParameter("roleMenuItemMap", "{\"roleId\":\"2\"}"); String resultMessage = executeAction("/SuperW/queryRoleMenuItemMap.action"); boolean rs = -1 != resultMessage.indexOf( "{\"userToken\":true,\"serviceResult\":true," + "\"resultInfo\":\"查询角色菜单关系列表成功\""); assertTrue("返回服務信息錯誤失敗", rs); }
@DefaultHandler public Resolution execute() { logger.debug("Entrando a LogoutAction.execute"); Subject s = SecurityUtils.getSubject(); if (s != null) s.logout(); return new RedirectResolution(IndexAction.class); }
/* 无需做链接,这是OpenID的回调地址 */ @RequiresGuest @At("/login/?/callback") public View returnPoint(String providerId, HttpServletRequest request, HttpSession session) throws Exception { SocialAuthManager manager = (SocialAuthManager) session.getAttribute("openid.manager"); if (manager == null) throw new SocialAuthException("Not manager found!"); session.removeAttribute("openid.manager"); // 防止重复登录的可能性 Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request); AuthProvider provider = manager.connect(paramsMap); Profile p = provider.getUserProfile(); Subject currentUser = SecurityUtils.getSubject(); ThreadContext.bind(currentUser); OAuthToken token = new OAuthToken(p, request.getRemoteAddr()); try { currentUser.login(token); } catch (UnknownAccountException uae) { return new ViewWrapper(new ForwardView("/admin/index"), "帐号不存在"); } catch (IncorrectCredentialsException ice) { return new ViewWrapper(new ForwardView("/admin/index"), "证书验证失败"); } catch (LockedAccountException lae) { return new ViewWrapper(new ForwardView("/admin/index"), "帐号已被锁定"); } catch (ExcessiveAttemptsException eae) { return new ViewWrapper(new ForwardView("/admin/index"), "尝试的次数太多"); } catch (AuthenticationException ae) { return new ViewWrapper(new ForwardView("/admin/index"), ae.getMessage()); } return new ViewWrapper(new ServerRedirectView("/admin/main.rk"), null); }
@Test public void testGetUserStatusNonDefaultRealm() throws Exception { final List<String> realms = securitySystem.getRealms(); realms.add("TestPrincipalsRealm"); securitySystem.setRealms(realms); final Subject subject = login("tempUser", "tempPass"); try { final PrincipalCollection principals = subject.getPrincipals(); // check status is passed through assertThat(helper().getUserStatus(principals), is(UserStatus.active)); TestUserManager.status = UserStatus.disabled; assertThat(helper().getUserStatus(principals), is(UserStatus.disabled)); TestUserManager.status = UserStatus.locked; assertThat(helper().getUserStatus(principals), is(UserStatus.locked)); TestUserManager.status = UserStatus.active; assertThat(helper().getUserStatus(principals), is(UserStatus.active)); TestUserManager.userDeleted = true; try { helper().getUserStatus(principals); Assert.fail("Expected UserNotFoundException"); } catch (final UserNotFoundException e) { // expected... } } finally { subject.logout(); } }
/** * 为当前登录的Subject授予角色和权限 * * @see 经测试:本例中该方法的调用时机为需授权资源被访问时 * @see 经测试:并且每次访问需授权资源时,只有第一次需要执行该方法,这表明本例中默认启用AuthorizationCache * @see 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache * @see 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { logger.info("------------开始 SecurityRealm doGetAuthorizationInfo----------"); // String currentUsername = (String)super.getAvailablePrincipal(arg0); SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); Subject currentUser = SecurityUtils.getSubject(); Collection<String> con = (Collection) currentUser.getSession().getAttribute(IConstants.SHIRO_ROLE_INFO); for (String string : con) { // SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // System.out.println(string); simpleAuthorInfo.addStringPermission(string); // 需要访问需授权资源的时候调用该函数,且一个subject调用了该函数后,只要session还在有效期,再次访问需授权资源的时候 // 就不需要再次执行该函数了。所以产生的问题就是如果权限改变了,但是原session还有效。需要用户重新手动的执行一次登录 } return simpleAuthorInfo; // /* if(null!=currentUsername && "001".equals(currentUsername)){ // //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色 // simpleAuthorInfo.addRole("admin"); // //添加权限 // simpleAuthorInfo.addStringPermission("admin:manage111"); // logger.info("已为用户["+currentUsername+"]赋予了[admin]角色和[admin:manage]权限"); // return simpleAuthorInfo; // }*/ // // return null; }
/** * 获得授权的button * * @param permission * @return */ @Override public Map getButtonsByPermission(String permission) { if (permission == null || permission.isEmpty()) return null; Map resp = new HashMap(); List<Map> buttons = new ArrayList<Map>(); Subject subject = shiroService.getSubject(); if (permission.indexOf("_") != -1) { String[] permissions = permission.split("_"); for (String _permission : permissions) { Map button = new HashMap(); button.put("permission", _permission); if (subject.hasRole(_permission)) { button.put("status", true); } else { button.put("status", false); } buttons.add(button); } } else { Map button = new HashMap(); button.put("permission", permission); if (subject.hasRole(permission)) { button.put("status", true); } else { button.put("status", false); } buttons.add(button); } resp.put("buttons", buttons.toArray()); return resp; }
@RequestMapping(value = {"/{login:login;?.*}"}) // spring3.2.2 bug see http://jinnianshilongnian.iteye.com/blog/1831408 public String loginForm(HttpServletRequest request, ModelMap model) { // 表示退出 if (!StringUtils.isEmpty(request.getParameter("logout"))) { model.addAttribute( Constants.MESSAGE, messageSource.getMessage("user.logout.success", null, null)); } // 表示用户删除了 @see org.apache.shiro.web.filter.user.SysUserFilter if (!StringUtils.isEmpty(request.getParameter("notfound"))) { model.addAttribute(Constants.ERROR, messageSource.getMessage("user.notfound", null, null)); } // 表示用户被管理员强制退出 if (!StringUtils.isEmpty(request.getParameter("forcelogout"))) { model.addAttribute(Constants.ERROR, messageSource.getMessage("user.forcelogout", null, null)); } // 表示用户输入的验证码错误 if (!StringUtils.isEmpty(request.getParameter("jcaptchaError"))) { model.addAttribute( Constants.ERROR, messageSource.getMessage("jcaptcha.validate.error", null, null)); } // 表示用户锁定了 @see org.apache.shiro.web.filter.user.SysUserFilter if (!StringUtils.isEmpty(request.getParameter("blocked"))) { User user = (User) request.getAttribute(Constants.CURRENT_USER); String reason = userStatusHistoryService.getLastReason(user); model.addAttribute( Constants.ERROR, messageSource.getMessage("user.blocked", new Object[] {reason}, null)); } if (!StringUtils.isEmpty(request.getParameter("unknown"))) { model.addAttribute( Constants.ERROR, messageSource.getMessage("user.unknown.error", null, null)); } // 登录失败了 提取错误消息 Exception shiroLoginFailureEx = (Exception) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (shiroLoginFailureEx != null) { model.addAttribute(Constants.ERROR, shiroLoginFailureEx.getMessage()); } // 如果用户直接到登录页面 先退出一下 // 原因:isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问 // 这样会导致登录一直死循环 Subject subject = SecurityUtils.getSubject(); if ((subject != null) && subject.isAuthenticated()) { subject.logout(); } // 如果同时存在错误消息 和 普通消息 只保留错误消息 if (model.containsAttribute(Constants.ERROR)) { model.remove(Constants.MESSAGE); } return "front/login"; }
/** * 用户注销 * * @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; }
/** 用户登陆 */ @RequestMapping( path = "/login", produces = {"application/json;charset=UTF-8"}) public JsonResult login(String loginName, String password, Boolean rememberMe) { JsonResult result = new JsonResult(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(loginName, password); if (rememberMe != null && rememberMe) { token.setRememberMe(true); } try { subject.login(token); } catch (AuthenticationException e) { subject.logout(); log.info("登录失败"); result.setResult(false); return result; } if (subject.isAuthenticated()) { result.setResult(true); } else { result.setResult(false); } return result; }
/** Get result as matrix in WEKA (ARFF) format. */ @GET @Path("search/matrix") @Produces("text/plain") public String matrix( @QueryParam("q") String query, @QueryParam("corpora") String rawCorpusNames, @QueryParam("metakeys") String rawMetaKeys) { requiredParameter(query, "q", "AnnisQL query"); requiredParameter(rawCorpusNames, "corpora", "comma separated list of corpus names"); Subject user = SecurityUtils.getSubject(); List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames); for (String c : corpusNames) { user.checkPermission("query:matrix:" + c); } QueryData data = queryDataFromParameters(query, rawCorpusNames); MatrixQueryData ext = new MatrixQueryData(); if (rawMetaKeys != null) { ext.setMetaKeys(splitMatrixKeysFromRaw(rawMetaKeys)); } data.addExtension(ext); long start = new Date().getTime(); List<AnnotatedMatch> matches = annisDao.matrix(data); long end = new Date().getTime(); logQuery("MATRIX", query, splitCorpusNamesFromRaw(rawCorpusNames), end - start); if (matches.isEmpty()) { return "(empty)"; } else { return WekaHelper.exportAsArff(matches); } }
@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); }
/** 获取头部信息 */ @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); }
/** * @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; }
@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; }
@RequestMapping(value = "/approveRequests", method = RequestMethod.GET) @ResponseBody public List<AuthorizationApplications> listAreqs() { Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); return oauthorizationApplicationsService.findWaitForApproveByResourceOwner(username); }
/** 用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); }
@Override @Transactional public User createUser(User user) throws UserExistsException, DatabaseException { if (userRepository.findByEmailAddress(user.getEmailAddress()) != null) { throw new UserExistsException(); } if (user.isNew()) { String hash = new Sha512Hash(user.getPassword(), getSalt(), HASH_ITERATIONS).toBase64(); user.setDbPassword(hash); user.setActive(true); } try { userRepository.save(user); } catch (Exception e) { throw new DatabaseException(e); } Subject currentUserSubject = SecurityUtils.getSubject(); if (!currentUserSubject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(user.getEmailAddress(), user.getPassword()); token.setRememberMe(false); try { currentUserSubject.login(token); } catch (AuthenticationException ae) { throw new LoginException(); } } return currentUser = user; }
// 采购单受理列表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 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(); }