Example usage for javax.servlet.http HttpServletRequest isUserInRole

List of usage examples for javax.servlet.http HttpServletRequest isUserInRole

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isUserInRole.

Prototype

public boolean isUserInRole(String role);

Source Link

Document

Returns a boolean indicating whether the authenticated user is included in the specified logical "role".

Usage

From source file:org.jboss.bpm.console.server.UserMgmtFacade.java

@GET
@Path("user/roles")
@Produces("application/json")
public Response getRolesForJAASPrincipal(@Context HttpServletRequest request,
        @QueryParam("roleCheck") String roleCheck) {
    // TODO: Why not use the identity DB right away?
    // These roles are security roles
    if (null == roleCheck)
        throw new WebApplicationException(new IllegalArgumentException("Missing parameter 'roleCheck'"));

    log.debug("Role check user: " + request.getUserPrincipal().getName() + ", actualRoles requested: "
            + roleCheck);/*from w  ww. j a  v a  2 s.  c  o m*/

    List<RoleAssignmentRef> actualRoles = new ArrayList<RoleAssignmentRef>();

    StringTokenizer tok = new StringTokenizer(roleCheck, ",");
    while (tok.hasMoreTokens()) {
        String possibleRole = tok.nextToken();
        actualRoles.add(new RoleAssignmentRef(possibleRole, request.isUserInRole(possibleRole)));
    }
    return createJsonResponse(new RoleAssignmentRefWrapper(actualRoles));
}

From source file:org.opennms.web.map.OpenMapController.java

/** {@inheritDoc} */
@Override//  w ww .java  2s  .  c  o  m
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    LOG.debug(request.getQueryString());
    String mapIdStr = request.getParameter("MapId");
    LOG.debug("MapId={}", mapIdStr);
    String mapWidthStr = request.getParameter("MapWidth");
    LOG.debug("MapWidth={}", mapWidthStr);
    String mapHeightStr = request.getParameter("MapHeight");
    LOG.debug("MapHeight={}", mapHeightStr);
    String adminModeStr = request.getParameter("adminMode");
    LOG.debug("adminMode={}", adminModeStr);

    String user = request.getRemoteUser();

    if ((request.isUserInRole(org.opennms.web.api.Authentication.ROLE_ADMIN))) {
        LOG.info("{} has Admin admin Role", user);
    }

    float widthFactor = 1;
    float heightFactor = 1;

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));

    try {
        int mapWidth = WebSecurityUtils.safeParseInt(mapWidthStr);
        int mapHeight = WebSecurityUtils.safeParseInt(mapHeightStr);

        LOG.debug("Current mapWidth={} and MapHeight={}", mapWidth, mapHeight);
        VMap map = null;
        if (mapIdStr != null) {
            int mapid = WebSecurityUtils.safeParseInt(mapIdStr);
            LOG.debug("Opening map {} for user {}", mapid, user);
            map = manager.openMap(mapid, user, !(adminModeStr.equals("true")));
        } else {
            LOG.debug("Try to Opening default map");
            VMapInfo defaultmapinfo = manager.getDefaultMapsMenu(user);
            if (defaultmapinfo != null) {
                map = manager.openMap(defaultmapinfo.getId(), user, !(adminModeStr.equals("true")));
            } else {
                map = manager.openMap();
            }
        }

        if (map != null) {
            int dbMapWidth = map.getWidth();
            int dbMapHeight = map.getHeight();
            widthFactor = (float) mapWidth / dbMapWidth;
            heightFactor = (float) mapHeight / dbMapHeight;

            LOG.debug("Old saved mapWidth={} and MapHeight={}", dbMapWidth, dbMapHeight);
            LOG.debug("widthFactor={}", widthFactor);
            LOG.debug("heightFactor={}", heightFactor);
            LOG.debug("Setting new width and height to the session map");

            map.setHeight(mapHeight);
            map.setWidth(mapWidth);

            for (VElement ve : map.getElements().values()) {
                ve.setX((int) (ve.getX() * widthFactor));
                ve.setY((int) (ve.getY() * heightFactor));
            }

            SparseGraph<VElement, VLink> jungGraph = new SparseGraph<VElement, VLink>();

            for (VElement ve : map.getElements().values()) {
                jungGraph.addVertex(ve);
            }
            for (VLink vl : map.getLinks()) {
                jungGraph.addEdge(vl, map.getElement(vl.getFirst()), map.getElement(vl.getSecond()));
            }

            KKLayout<VElement, VLink> layout = new KKLayout<VElement, VLink>(jungGraph);
            layout.setInitializer(initializer(map));
            layout.setSize(selectLayoutSize(map));

            while (!layout.done()) {
                layout.step();
            }

            int vertexCount = map.getElements().size();
            for (VElement ve : map.getElements().values()) {
                LOG.debug("---------Element {}---------", ve.getLabel());
                LOG.debug("dbcoor: X={} Y={}", ve.getX(), ve.getY());
                LOG.debug("kkcoor: X={} Y={}", layout.getX(ve), layout.getY(ve));
                LOG.debug("kkcoor: X={} Y={}", (int) layout.getX(ve), (int) layout.getY(ve));
                LOG.debug("");
                if (vertexCount >= 10) {
                    ve.setX((int) layout.getX(ve) - 100);
                    ve.setY((int) layout.getY(ve) - 100);
                } else {
                    ve.setX((int) layout.getX(ve));
                    ve.setY((int) layout.getY(ve));
                }
                LOG.debug("vmspcoor: X={} Y={}", ve.getX(), ve.getY());
            }
        }

        bw.write(ResponseAssembler.getMapResponse(map));

    } catch (Throwable e) {
        LOG.error("Error while opening map with id:{}, for user:{}", mapIdStr, user, e);
        bw.write(ResponseAssembler.getMapErrorResponse(MapsConstants.OPENMAP_ACTION));
    } finally {
        bw.close();
    }

    return null;
}

From source file:org.rti.zcore.dar.struts.action.PatientHomeAction.java

/**
 * Negotiate whether the user has a current pregnancy or needs to view history.
 * <p/>/*from   www  .j  a va 2 s .c  o m*/
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Long patientId = null;
    Long eventId = null;
    Long flowId = null;
    BaseSessionSubject sessionPatient = null;
    HttpSession session = request.getSession();

    try {
        sessionPatient = SessionUtil.getInstance(session).getSessionPatient();
    } catch (SessionUtil.AttributeNotFoundException e1) {
        //log.debug("No session - SessionUtil.AttributeNotFoundException" + e1);
        return mapping.findForward("home");
    }
    patientId = sessionPatient.getId();
    eventId = sessionPatient.getCurrentEventId();
    String forward;
    String params = null;

    forward = "PatientItem/new";

    // if user is data clerk, send to home page.
    if (request.isUserInRole("CREATE_NEW_PATIENTS_AND_SEARCH")) {
        request.setAttribute("patientId", patientId);
        ActionForward forwardForm = null;
        String forwardString = "/demographics.do?patientId=" + patientId;
        forwardForm = new ActionForward(forwardString);
        return forwardForm;
    } else {
        request.setAttribute("patientId", patientId);
        ActionForward forwardForm = null;
        String forwardString = null;
        if (params != null) {
            forwardString = "/" + forward + ".do?patientId=" + patientId + "&" + params;
        } else {
            forwardString = "/" + forward + ".do?patientId=" + patientId;
        }
        forwardForm = new ActionForward(forwardString);
        forwardForm.setRedirect(true);
        return forwardForm;
    }
}

From source file:com.orchestra.portale.controller.UserInfoController.java

@RequestMapping(value = "/userInfo")
@Secured("ROLE_USER")
public ModelAndView getUserInfo(HttpServletRequest request) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ModelAndView model = new ModelAndView("userInfo");
    ModelAndView model2 = new ModelAndView("index");
    if (auth != null) {
        User user = pm.findUserByUsername(auth.getName());
        HttpSession session = request.getSession();
        ServletContext sc = session.getServletContext();
        File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
                + File.separator + user.getId() + File.separator + "avatar.jpg");
        if (dir.exists()) {
            model.addObject("avatar", "./dist/user/img/" + user.getId() + "/avatar.jpg");
        } else {// w w  w .jav  a  2  s  . com
            model.addObject("avatar", "./dist/img/default_avatar.png");
        }

        model.addObject("user", user);

        if (request.isUserInRole("ROLE_FB")) {
            Object categories = fbprofiler.getFBCategories();
            if (categories != null) {
                model.addObject("categories", categories);
            }
        }
    } else {
        return model2;
    }
    return model;
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@DELETE
@Path("/{id}")
@Produces(APPLICATION_JSON)/*  ww  w  .j  a v a 2  s  . co m*/
public Response deleteReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName) {

    String username = request.getRemoteUser();

    log.debug("{} is requesting deleteReport(...), with a ID={} and scopeName={}", username, id, scopeName);
    ReportDTO originalReport;
    boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());

    try {
        Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                scopeName);
        // for delete operation, we don't really nead the permitted service layers,
        // therefore we pass null
        originalReport = reportService.findById(features, id, username, scopeName, isAdmin, null); // we need the
        // original
        // report
        // because of
        // the
        // 'owner/createdBy'
        // attribute,
        // which is not
        // contained in
        // the JSON
    } catch (Exception e) {
        String errorMsg = "Failed to get report.";
        log.error(errorMsg, e);
        return createErrorResponse(errorMsg);
    }

    if (originalReport == null) {
        createScNotFoundErrorResponse(ErrorCodes.ENTRY_NOT_FOUND);
    }

    ReportFeatureEnum requiredFeature = AuthorizationCheckUtil.getRequiredFeatureToDeleteReport(originalReport,
            username);

    if (requiredFeature != null && !request.isUserInRole(requiredFeature.toString())) {
        createScNotFoundErrorResponse(ErrorCodes.NOT_AUTHORIZED);
    }

    try {
        reportService.delete(id, username, scopeName, isAdmin);
    } catch (Exception exc) {
        log.error("Report deletion failed.", exc);
        createErrorResponse(ErrorCodes.DELETE_FAILED);
    }

    return createSuccessResponse();
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testCreateRolePerms() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);
    ApplicationContext appContext = mock(ApplicationContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")).thenReturn(null);
    when(context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
            .thenReturn(appContext);/*w  w  w  .j  av  a2 s  .  c  om*/
    when(context.getInitParameter("contextAuthConfigLocation")).thenReturn("somewhere");
    when(appContext.getResource("somewhere")).thenReturn(
            new DefaultResourceLoader().getResource("com/betfair/tornjak/monitor/overlay/auth.properties"));

    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(true);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);

    assertThat(auth, notNullValue());
    assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED));
}

From source file:com.mycompany.projetsportmanager.spring.rest.controllers.UserController.java

/**
 * Retrieve user by id/*from  w ww. j a v  a2s.  c  om*/
 * 
 * @param userId
 *            the user identifier
 * @return the user corresponding to the specified user identifier
 */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}")
public UserResource userGet(@PathVariable("userId") Long userId, HttpServletRequest httpServletRequest) {

    User requestBo = null;
    try {
        requestBo = userRepo.findOne(userId);
    } catch (DataAccessException e) {

        String msg = "Can't retrieve asked users from DB";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("db error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    }

    if (requestBo == null) {
        String msg = "User with id " + userId + " not found";
        throw new DefaultSportManagerException(new ErrorResource("not found", msg, HttpStatus.NOT_FOUND));
    }

    UserResource resource = userResourceAssembler.toResource(requestBo);
    if (httpServletRequest.isUserInRole("AK_ADMIN")) {
        resource.add(linkTo(methodOn(UserController.class).userGet(userId, null))
                .withRel(ActionsConstants.UPDATE_VIA_PUT));
        resource.add(linkTo(methodOn(UserController.class).userGet(userId, null))
                .withRel(ActionsConstants.DELETE_VIA_DELETE));
    }
    return resource;
}

From source file:org.apache.taglib.tiles.InsertTag.java

/**
 * Process the start tag by checking tag's attributes and creating appropriate handler.
 * Possible handlers :/*  w w w.java 2  s .c o  m*/
 * <ul>
 * <li> URL
 * <li> definition
 * <li> direct String
 * </ul>
 * Handlers also contain sub-component context.
 */
public int doStartTag() throws JspException {
    // Check role immediatly to avoid useless stuff.
    // In case of insertion of a "definition", definition's role still checked later.
    // This lead to a double check of "role" ;-(
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    if (role != null && !request.isUserInRole(role)) {
        processEndTag = false;
        return SKIP_BODY;
    }

    try {
        tagHandler = createTagHandler();

    } catch (JspException e) {
        if (isErrorIgnored) {
            processEndTag = false;
            return SKIP_BODY;
        } else {
            throw e;
        }
    }

    return tagHandler.doStartTag();
}

From source file:org.apache.struts.taglib.tiles.InsertTag.java

/**
 * Process the start tag by checking tag's attributes and creating appropriate handler.
 * Possible handlers :/* www  .ja  v  a 2s .co  m*/
 * <ul>
 * <li> URL
 * <li> definition
 * <li> direct String
 * </ul>
 * Handlers also contain sub-component context.
 */
public int doStartTag() throws JspException {

    // Additional fix for Bug 20034 (2005-04-28)
    cachedCurrentContext = null;

    // Check role immediatly to avoid useless stuff.
    // In case of insertion of a "definition", definition's role still checked later.
    // This lead to a double check of "role" ;-(
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    if (role != null && !request.isUserInRole(role)) {
        processEndTag = false;
        return SKIP_BODY;
    }

    try {
        tagHandler = createTagHandler();

    } catch (JspException e) {
        if (isErrorIgnored) {
            processEndTag = false;
            return SKIP_BODY;
        } else {
            throw e;
        }
    }

    return tagHandler.doStartTag();
}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

protected User getUser(DynaValidatorForm dynaForm, HttpServletRequest request, boolean createNew)
        throws Exception {

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();

    User sessUser = (User) request.getUserPrincipal();
    // Alleen beheeders mogen iemand anders bewerken
    if (!request.isUserInRole(Roles.ADMIN) && !createNew) {
        if (sessUser == null) {
            return null;
        }// www  .  j a v  a  2  s .  c om
        return (User) em.createQuery("from User u where u.id = :id").setParameter("id", sessUser.getId())
                .getSingleResult();
    }

    User user = null;
    Integer id = getID(dynaForm);
    if (null == id && createNew) {
        user = new User();
    } else if (null != id) {
        user = (User) em.find(User.class, new Integer(id.intValue()));
    }

    if (user == null) {
        return sessUser;
    }
    return user;
}