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:fi.hoski.web.forms.KeyInfoServlet.java

/**
 * Handles the HTTP//from w w  w. ja  v a  2 s .  com
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        response.setHeader("Cache-Control", "no-cache"); // input comes from referrer
        response.setContentType("application/json");
        boolean authenticated = request.isUserInRole("member");

        JSONObject json = new JSONObject();
        Key parent = getAncestor(request);
        if (parent != null) {
            KeyInfo keyInfo = new KeyInfo(entities, events, races, "", parent, authenticated);
            Map<String, Object> m = keyInfo.getMap();
            String clubDiscount = (String) m.get("RaceSeries.ClubDiscount");
            String club = (String) m.get("Club");
            if (Boolean.parseBoolean(clubDiscount) && "HSK".equalsIgnoreCase(club)) {
                m.put("isClubDiscountGranted", true);
            } else {
                m.put("isClubDiscountGranted", false);
            }
            for (Map.Entry<String, Object> e : m.entrySet()) {
                if (e.getValue() instanceof List) {
                    JSONArray a = new JSONArray();
                    json.put(e.getKey(), a);
                    List<String> l = (List<String>) e.getValue();
                    for (String s : l) {
                        a.put(s);
                    }
                } else {
                    if (e.getValue() instanceof char[]) {
                        JSONArray a = new JSONArray();
                        json.put(e.getKey(), a);
                        char[] ar = (char[]) e.getValue();
                        for (char c : ar) {
                            a.put((int) c);
                        }
                    } else {
                        json.put(e.getKey(), e.getValue());
                    }
                }
            }
            json.write(response.getWriter());
        }
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        throw new ServletException(ex);
    }
}

From source file:org.apache.axis2.jaxws.context.WebServiceContextImpl.java

public boolean isUserInRole(String user) {

    // Note that the MessageContext might not be set up yet, or it
    // may have been released because the lifetime of the WebServiceContext is completed.
    if (log.isDebugEnabled()) {
        if (soapMessageContext == null) {
            log.debug("The MessageContext is not available");
        }//from  w  w w .ja  v  a 2 s. co  m
    }

    if (soapMessageContext != null) {
        HttpServletRequest request = (HttpServletRequest) soapMessageContext
                .get(MessageContext.SERVLET_REQUEST);
        if (request != null) {
            if (log.isDebugEnabled()) {
                log.debug("Checking to see if the user in the role.");
            }
            return request.isUserInRole(user);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("No HttpServletRequest object was found, so no role check can be performed.");
            }
        }
    }

    return false;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.resource.UserResource.java

/**
 * Put an updated user to the system. Unless the user has the admin role,
 * s/he may only update their own user info.
 *
 * @param inUser Object containing all the information about the user to
 * add.//from  ww  w.j  a v a  2 s.com
 * @return A "Created" response with a link to the user page if successful.
 */
@RolesAllowed({ "researcher", "admin" })
@Path("/{id}")
@PUT
public Response putUser(@Context HttpServletRequest req, User inUser, @PathParam("id") Long inId) {
    String username = req.getUserPrincipal().getName();
    if (!req.isUserInRole("admin") && !username.equals(inUser.getUsername())) {
        throw new HttpStatusException(Response.Status.FORBIDDEN);
    }
    LOGGER.debug("Received updated user: {}", inUser);
    Response response;
    UserEntity currentUser = this.userDao.retrieve(inId);
    boolean activation = (!currentUser.isActive()) && (inUser.isActive());
    List<Role> updatedRoles = this.roleIdsToRoles(inUser.getRoles());

    currentUser.setRoles(updatedRoles);
    currentUser.setActive(inUser.isActive());
    currentUser.setLastLogin(inUser.getLastLogin());

    if (this.validateUpdatedUser(currentUser)) {
        LOGGER.debug("Saving updated user: {}", currentUser.getEmail());
        this.userDao.update(currentUser);

        if (activation) {
            try {
                this.emailSender.sendActivationMessage(currentUser);
            } catch (EmailException ee) {
                LOGGER.error(ee.getMessage(), ee);
            }
        }
        response = Response.ok().entity(currentUser).build();
    } else {
        response = Response.notModified(this.validationError).build();
    }
    return response;
}

From source file:org.lamsfoundation.lams.admin.web.UserAction.java

public ActionForward enable(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    initServices();/* w ww.  j  a va  2  s.  c  o  m*/

    if (!(request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin())) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
        return mapping.findForward("error");
    }

    Integer userId = WebUtil.readIntParam(request, "userId", true);
    User user = (User) service.findById(User.class, userId);

    UserAction.log.debug("enabling user: " + userId);
    user.setDisabledFlag(false);
    service.save(user);

    return mapping.findForward("disabledlist");
}

From source file:org.lamsfoundation.lams.admin.web.UserAction.java

public ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    initServices();/*from   w w w  .j ava 2s  .  co m*/

    if (!(request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin())) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
        return mapping.findForward("error");
    }

    Integer orgId = WebUtil.readIntParam(request, "orgId", true);
    Integer userId = WebUtil.readIntParam(request, "userId");
    User user = (User) service.findById(User.class, userId);

    Boolean hasData = service.userHasData(user);

    request.setAttribute("method", (hasData ? "disable" : "delete"));
    request.setAttribute("orgId", orgId);
    request.setAttribute("userId", userId);
    return mapping.findForward("remove");
}

From source file:de.atomspace.webapp.core.SpringController.java

@RequestMapping(value = "/content/{name}", method = RequestMethod.GET)
public String getContentPage(@PathVariable("name") String name, ModelMap model, HttpServletRequest request,
        HttpServletResponse response) {/*from ww  w .  ja v  a  2 s. c o  m*/
    ContentService contentService = (ContentService) context.getBean("contentService");
    Content content = contentService.findOneByName(name);
    if (content == null)
        response.setStatus(404);

    if (request.isUserInRole("ROLE_ADMIN")) {
        model.put("name", name);
        model.put("content", content);
        model.put("page", "content/content.zul");
        return "pages/index.jsp";
    } else {
        model.put("name", name);
        if (content == null)
            content = new Content(true, false, "404", "404", "HTTP ERROR 404", "NOT_FOUND");
        model.put("content", content);
        model.put("page", "content/content.jsp");
        return "pages/index.jsp";
    }
}

From source file:org.lamsfoundation.lams.admin.web.UserAction.java

public ActionForward disable(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    initServices();/*from  w  w  w. jav  a  2 s  . c o m*/

    if (!(request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin())) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
        return mapping.findForward("error");
    }

    Integer orgId = WebUtil.readIntParam(request, "orgId", true);
    Integer userId = WebUtil.readIntParam(request, "userId");
    service.disableUser(userId);
    String[] args = new String[1];
    args[0] = userId.toString();
    String message = messageService.getMessage("audit.user.disable", args);
    AdminServiceProxy.getAuditService(getServlet().getServletContext()).log(AdminConstants.MODULE_NAME,
            message);

    if (orgId == null || orgId == 0) {
        return mapping.findForward("usersearch");
    } else {
        request.setAttribute("org", orgId);
        return mapping.findForward("userlist");
    }
}

From source file:org.lamsfoundation.lams.admin.web.UserAction.java

public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    initServices();//from w ww . j  ava2  s  .c  om

    if (!(request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin())) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
        return mapping.findForward("error");
    }

    Integer orgId = WebUtil.readIntParam(request, "orgId", true);
    Integer userId = WebUtil.readIntParam(request, "userId");
    try {
        service.removeUser(userId);
    } catch (Exception e) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", e.getMessage());
        return mapping.findForward("error");
    }
    String[] args = new String[1];
    args[0] = userId.toString();
    String message = messageService.getMessage("audit.user.delete", args);
    AdminServiceProxy.getAuditService(getServlet().getServletContext()).log(AdminConstants.MODULE_NAME,
            message);

    if (orgId == null || orgId == 0) {
        return mapping.findForward("usersearch");
    } else {
        request.setAttribute("org", orgId);
        return mapping.findForward("userlist");
    }
}

From source file:org.eurekaclinical.user.service.resource.UserResource.java

/**
 * Put an updated user to the system. Unless the user has the admin role,
 * s/he may only update their own user info.
 *
 * @param req in request//from  w  w w .j  a v a2s.  co m
 * @param inUser Object containing all the information about the user to
 * add.
 * @param inId in Id
 * @return A "Created" response with a link to the user page if successful.
 */
@RolesAllowed({ "researcher", "admin" })
@Path("/{id}")
@PUT
public Response putUser(@Context HttpServletRequest req, User inUser, @PathParam("id") Long inId) {
    String username = req.getUserPrincipal().getName();
    if (!req.isUserInRole("admin") && !username.equals(inUser.getUsername())) {
        throw new HttpStatusException(Response.Status.FORBIDDEN);
    }
    LOGGER.debug("Received updated user: {}", inUser);
    Response response;

    UserEntity currentUser = this.userDao.retrieve(inId);
    User me = getMe(req);

    boolean activation = (!currentUser.isActive()) && (inUser.isActive());

    if (this.validateUpdatedUser(currentUser, inUser, me)) {

        currentUser.setFirstName(inUser.getFirstName());
        currentUser.setLastName(inUser.getLastName());
        currentUser.setEmail(inUser.getEmail());
        currentUser.setOrganization(inUser.getOrganization());
        currentUser.setTitle(inUser.getTitle());
        currentUser.setDepartment(inUser.getDepartment());
        currentUser.setFullName(inUser.getFullName());

        List<RoleEntity> updatedRoles = this.roleIdsToRoles(inUser.getRoles());
        currentUser.setRoles(updatedRoles);
        currentUser.setActive(inUser.isActive());
        currentUser.setLastLogin(inUser.getLastLogin());

        LOGGER.debug("Saving updated user: {}", currentUser.getEmail());
        this.userDao.update(currentUser);

        if (activation) {
            try {
                this.emailSender.sendActivationMessage(currentUser);
            } catch (EmailException ee) {
                LOGGER.error(ee.getMessage(), ee);
            }
        }

        response = Response.ok().entity(currentUser).build();
    } else {
        response = Response.notModified(this.validationError).build();
    }

    return response;
}

From source file:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    // Check if the user is logged in
    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;/*from w  ww  .  j a va  2s  .c  om*/
    }

    // Check that the user is an admin
    boolean isAdmin = servletRequest.isUserInRole("HOPS_ADMIN");
    if (!isAdmin) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this application");
        return;
    }

    // The path we will receive is [host]/llapmonitor/llaphost/
    // We need to extract the llaphost to redirect the request
    String[] pathInfoSplits = servletRequest.getPathInfo().split("/");
    String llapHost = pathInfoSplits[1];

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    if (matcher.find()) {
        matcher.appendReplacement(urlBuf, llapHost);
    }

    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    super.service(servletRequest, servletResponse);
}