List of usage examples for javax.servlet.http HttpServletRequest isUserInRole
public boolean isUserInRole(String role);
From source file:de.whs.poodle.controllers.LoginController.java
@RequestMapping(method = RequestMethod.GET) public String login(HttpServletRequest request, RedirectAttributes redirectAttributes, Model model, @RequestParam(defaultValue = "0") boolean switchUserFailed) { if (switchUserFailed) redirectAttributes.addFlashAttribute("errorMessageCode", "userDoesntExist"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); boolean isLoggedIn = !(auth instanceof AnonymousAuthenticationToken); if (!isLoggedIn) // not logged in yet, show login page return "login"; else if (request.isUserInRole("ROLE_STUDENT")) // user is logged in, redirect to start page return "redirect:/student"; else if (request.isUserInRole("ROLE_INSTRUCTOR")) return "redirect:/instructor"; else { // user is logged in, but he is neither student nor instructor (no matching group in LDAP?) model.addAttribute("errorMessageCode", "noValidRole"); return "login"; }/* ww w. j av a2 s. c o m*/ }
From source file:edu.emory.cci.aiw.cvrg.eureka.services.resource.UserResource.java
/** * Get a user by the user's identification number. * * @param inId The identification number for the user to fetch. * @return The user referenced by the identification number. *//*from ww w . j ava 2 s . co m*/ @RolesAllowed({ "researcher", "admin" }) @Path("/{id}") @GET public User getUserById(@Context HttpServletRequest req, @PathParam("id") Long inId) { UserEntity userEntity = this.userDao.retrieve(inId); if (userEntity == null) { throw new HttpStatusException(Response.Status.NOT_FOUND); } if (!req.isUserInRole("admin") && !this.authenticationSupport.isSameUser(req, userEntity)) { throw new HttpStatusException(Response.Status.FORBIDDEN); } this.userDao.refresh(userEntity); LOGGER.debug("Returning user for ID {}", inId); UserEntityToUserVisitor visitor = new UserEntityToUserVisitor(); userEntity.accept(visitor); return visitor.getUser(); }
From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java
@Test public void testSuccessfulAuthorisation() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletContext context = mock(ServletContext.class); Principal p = mock(Principal.class); when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")) .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms()); when(request.getUserPrincipal()).thenReturn(p); when(request.isUserInRole("jmxadmin")).thenReturn(true); Auth auth = AuthUtils.checkAuthorised(request, response, context); assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED)); }
From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java
@Test public void testNotAuthorised() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletContext context = mock(ServletContext.class); Principal p = mock(Principal.class); when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")) .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms()); when(request.getUserPrincipal()).thenReturn(p); when(request.isUserInRole("jmxadmin")).thenReturn(false); Auth auth = AuthUtils.checkAuthorised(request, response, context); assertThat("User should not be authorised", auth, nullValue()); verify(response, times(1)).sendError(HttpServletResponse.SC_FORBIDDEN); verifyNoMoreInteractions(response);// w w w . j a v a 2s. co m }
From source file:org.eurekaclinical.user.service.resource.UserResource.java
/** * Get a user by the user's identification number. * * @param req in request/*from ww w . j ava2 s .c o m*/ * @param inId The identification number for the user to fetch. * @return The user referenced by the identification number. */ @RolesAllowed({ "researcher", "admin" }) @Path("/{id}") @GET public User getUserById(@Context HttpServletRequest req, @PathParam("id") Long inId) { UserEntity userEntity = this.userDao.retrieve(inId); if (userEntity == null) { throw new HttpStatusException(Response.Status.NOT_FOUND); } if (!req.isUserInRole("admin") && !req.getRemoteUser().equals(userEntity.getUsername())) { throw new HttpStatusException(Response.Status.FORBIDDEN); } this.userDao.refresh(userEntity); LOGGER.debug("Returning user for ID {}", inId); UserEntityToUserVisitor visitor = new UserEntityToUserVisitor(); userEntity.accept(visitor); return visitor.getUser(); }
From source file:AuthenticationSnoop.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><BODY>"); out.println("<H1>This is a password protected resource</H1>"); out.println("<PRE>"); out.println("User Name: " + req.getRemoteUser()); String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName(); out.println("Principal Name: " + name); out.println("Authentication Type: " + req.getAuthType()); out.println("Is a Manager: " + req.isUserInRole("manager")); out.println("</PRE>"); out.println("</BODY></HTML>"); }
From source file:co.bluepass.web.rest.ClubResource.java
/** * Delete./*from w ww . j a v a 2 s.c om*/ * * @param id the id * @param request the request */ @RequestMapping(value = "/clubs/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public void delete(@PathVariable Long id, HttpServletRequest request) { log.debug("REST request to delete Club : {}", id); if (id == null || id <= 0) { return; } Club club = clubRepository.findOne(id); if (!request.isUserInRole("ROLE_ADMIN") && !club.getCreator().getEmail().equals(SecurityUtils.getCurrentLogin())) { return; } clubRepository.delete(id); }
From source file:com.pkrete.locationservice.admin.controller.mvc.UserOwnerController.java
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception, ServletException, IOException { /* Model that is returned together with the view */ java.util.Map<String, Object> model = new HashMap<String, Object>(); String userId = request.getParameter("select_user"); String ownerId = request.getParameter("select_owner"); /**//from www . j a va 2 s . com * If user is administrator and index parameter is present in the URL, * recreate search index. */ if (request.isUserInRole(UserGroup.ADMIN.toString()) && request.getParameter("index") != null) { ownersService.recreateSearchIndex(); } if (request.getParameter("btn_add_owner") != null) { return new ModelAndView("redirect:addowner.htm"); } else if (request.getParameter("btn_edit_owner") != null && ownerId != null) { return new ModelAndView("redirect:editowner.htm?select_owner=" + ownerId); } else if (request.getParameter("btn_delete_owner") != null && ownerId != null) { Owner temp = ownersService.getOwner(this.converterService.strToInt(ownerId)); if (ownersService.canBeDeleted(temp)) { if (!ownersService.delete(temp)) { model.put("errorMsg", this.messageSource.getMessage("error.owner.delete", null, null)); } } else { model.put("errorMsg", this.messageSource.getMessage("error.owner.delete", null, null)); } } else if (request.getParameter("btn_add_user") != null) { return new ModelAndView("redirect:adduser.htm"); } else if (request.getParameter("btn_edit_user") != null && userId != null) { return new ModelAndView("redirect:edituser.htm?select_user=" + userId); } else if (request.getParameter("btn_delete_user") != null && userId != null) { UserInfo tempInfo = usersService.getUserInfoByUsername(userId); if (!usersService.delete(tempInfo)) { throw new Exception("Deleting user failed."); } tempInfo = null; userId = null; } model.put("users", usersService.getUsers()); model.put("owners", ownersService.getOwners()); return new ModelAndView("user_owner", "model", model); }
From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;/*w w w. j a v a 2s. c o m*/ } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not // sure it would truly be compatible String proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); String method = servletRequest.getMethod(); HttpMethod m; if (method.equalsIgnoreCase("PUT")) { m = new PutMethod(proxyRequestUri); RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(), servletRequest.getContentType()); ((PutMethod) m).setRequestEntity(requestEntity); } else { m = new GetMethod(proxyRequestUri); } Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //yarn does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // Pass the response code. This method with the "reason phrase" is //deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:com.pkrete.locationservice.admin.controller.mvc.LanguageController.java
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception, ServletException, IOException { /* Get the current user. */ Owner owner = UsersUtil.getUser(request, usersService).getOwner(); /* Model that is returned together with the view */ Map<String, Object> model = new HashMap<String, Object>(); String idLanguage = request.getParameter("select_language"); /**//from ww w .ja v a2 s. com * If user is administrator and index parameter is present in the URL, * recreate search index. */ if (request.isUserInRole(UserGroup.ADMIN.toString()) && request.getParameter("index") != null) { this.languagesService.recreateSearchIndex(); } if (request.getParameter("btn_add_language") != null) { return new ModelAndView("redirect:addlanguage.htm"); } else if (request.getParameter("btn_edit_language") != null && idLanguage != null) { return new ModelAndView("redirect:editlanguage.htm?select_language=" + idLanguage); } else if (request.getParameter("btn_delete_language") != null) { Language lang = languagesService.getLanguageById(this.converterService.strToInt(idLanguage), owner); if (languagesService.canBeDeleted(lang)) { if (!languagesService.delete(lang)) { throw new Exception("Deleting language failed."); } lang = null; updateUser(request); owner = UsersUtil.getUser(request, usersService).getOwner(); } else { model.put("errorMsg", this.messageSource.getMessage("error.language.delete", null, null)); } } if (request.isUserInRole(UserGroup.ADMIN.toString())) { model.put("isAdmin", ""); } model.put("languages", owner.getLanguages()); return new ModelAndView("language", "model", model); }