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:io.hops.hopsworks.api.user.AuthService.java

private void logUserLogin(HttpServletRequest req) {
    StringBuilder roles = new StringBuilder();
    roles.append(req.isUserInRole("HOPS_USER") ? "{user" : "{");
    roles.append(req.isUserInRole("HOPS_ADMIN") ? " admin" : "");
    roles.append(req.isUserInRole("AGENT") ? " agent" : "");
    roles.append(req.isUserInRole("CLUSTER_AGENT") ? " cluster-agent}" : "}");
    LOGGER.log(Level.INFO, "[/hopsworks-api] login:\n email: {0}\n session: {1}\n in roles: {2}",
            new Object[] { req.getUserPrincipal(), req.getSession().getId(), roles });
}

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

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

    // check permission
    if (!(request.isUserInRole(Role.SYSADMIN) || request.isUserInRole(Role.AUTHOR_ADMIN))) {
        request.setAttribute(ToolContentListAction.ATTRIBUTE_ERROR_NAME, "ToolContentListAction");
        request.setAttribute(ToolContentListAction.ATTRIBUTE_ERROR_MESSAGE, AdminServiceProxy
                .getMessageService(getServlet().getServletContext()).getMessage("error.authorisation"));
        return mapping.findForward(ToolContentListAction.FORWARD_ERROR);
    }//w w w .  j  ava  2s  .  c o  m

    // not just display, but enable/disable a learning library
    String param = request.getParameter(ToolContentListAction.PARAM_ACTION);
    if (StringUtils.equals(param, ToolContentListAction.ACTION_ENABLE)) {
        if (checkPriviledge(request)) {
            enableLibrary(mapping, form, request, response);
        } else {
            return mapping.findForward(ToolContentListAction.FORWARD_ERROR);
        }
    } else {
        if (StringUtils.equals(param, ToolContentListAction.ACTION_DISABLE)) {
            if (checkPriviledge(request)) {
                disableLibrary(mapping, form, request, response);
            } else {
                return mapping.findForward(ToolContentListAction.FORWARD_ERROR);
            }
        }
    }

    // get learning library dtos and their validity
    List<LearningLibraryDTO> learningLibraryDTOs = getLearningDesignService()
            .getAllLearningLibraryDetails(false, getUserLanguage());
    // this is filled when executing following method, for efficiency purposes
    HashMap<Long, Boolean> learningLibraryValidity = new HashMap<Long, Boolean>(learningLibraryDTOs.size());
    ArrayList<LibraryActivityDTO> toolLibrary = filterMultipleToolEntries(learningLibraryDTOs,
            learningLibraryValidity);
    request.setAttribute(ToolContentListAction.ATTRIBUTE_LIBRARY, toolLibrary);
    request.setAttribute(ToolContentListAction.ATTRIBUTE_VALIDITY, learningLibraryValidity);

    // get tool versions
    HashMap<Long, String> toolVersions = new HashMap<Long, String>();
    List<Tool> tools = getUserManagementService().findAll(Tool.class);
    for (Tool tool : tools) {
        toolVersions.put(tool.getToolId(), tool.getToolVersion());
    }
    request.setAttribute(ToolContentListAction.ATTRIBUTE_TOOL_VERSIONS, toolVersions);

    // get tool database versions
    HashMap<String, Integer> dbVersions = new HashMap<String, Integer>();
    Connection conn = getDataSource().getConnection();
    PreparedStatement query = conn.prepareStatement(ToolContentListAction.QUERY_DATABASE_VERSIONS);
    ResultSet results = query.executeQuery();
    while (results.next()) {
        dbVersions.put(results.getString("system_name"), results.getInt("patch_level"));
    }
    request.setAttribute(ToolContentListAction.ATTRIBUTE_DATABASE_VERSIONS, dbVersions);

    return mapping.findForward(ToolContentListAction.FORWARD_SUCCESS);
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

private synchronized void verifyUserRole(@NotNull HttpServletRequest servletRequest) {
    if (!servletRequest.isUserInRole(roleName))
        throw unauthorized("User not in required role");
}

From source file:eu.europa.ec.fisheries.uvms.spatial.rest.resources.secured.AreaResource.java

@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Path("/datasets/{areaType}/{areaGid}/{datasetName}")
@Interceptors(value = { ExceptionInterceptor.class })
public Response createDataset(@PathParam("areaType") String areaType, @PathParam("areaGid") String areaGid,
        @PathParam("datasetName") String dataSetName, @Context HttpServletRequest request)
        throws ServiceException {
    if (!request.isUserInRole("CREATE_USER_AREA_DATASET")) {
        return createErrorResponse("user_area_dataset_creation_not_allowed");
    }/*from  ww  w . j  a v  a  2 s .c o m*/
    if (StringUtils.isNotBlank(dataSetName)) {
        usmService.createDataset(USMSpatial.APPLICATION_NAME, dataSetName,
                areaType + USMSpatial.DELIMITER + areaGid, USMSpatial.USM_DATASET_CATEGORY,
                USMSpatial.USM_DATASET_DESCRIPTION);
    } else {
        throw new IllegalArgumentException("datasetName is missing");
    }
    return createSuccessResponse();
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // If not an administrator, make sure user is not trying to add or edit another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) {
        if (isAdd(request) || request.getParameter("id") != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }//ww  w .  j  a v  a  2 s . c om
    }

    if (!isFormSubmission(request)) {
        String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they can't change passwords
        log.debug("checking for remember me login...");

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                saveMessage(request, getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        User user;
        if (userId == null && !isAdd(request)) {
            user = getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        return user;
    } else {
        // populate user object from database, so all fields don't need to be hidden fields in form
        return getUserManager().getUser(request.getParameter("id"));
    }
}

From source file:com.gisnet.cancelacion.web.controller.HomeController.java

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model, HttpServletRequest request, Principal principal) {

    List<String> mensajes = Utils.getMensajes(model);
    //mensajes.add("danger::prueba mensaje");
    //mensajes.add("success::prueba mensaje");
    //mensajes.add("info::prueba mensaje");
    //mensajes.add("warning::prueba mensaje");
    model.addAttribute("mensajes", mensajes);

    if (request.isUserInRole("ROLE_JURIDICO")) {
        return juridico.index(model, principal);
    } else if (request.isUserInRole("ROLE_NOTARIO")) {
        return notario.index(model, principal);
    } else if (request.isUserInRole("ROLE_JEFE_COBRANZA")) {
        return cobranza.index(model, principal);
    } else {//from w  w  w.java 2 s .c  om
        return "/norol";
    }
}

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

public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    service = AdminServiceProxy.getService(getServlet().getServletContext());
    initLocalesAndStatus();//from w ww . jav  a2s. c o  m
    DynaActionForm orgForm = (DynaActionForm) form;

    if (!(request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin())) {
        // only sysadmins and global group admins can create groups
        if (orgForm.get("typeId") != null && orgForm.get("typeId").equals(OrganisationType.COURSE_TYPE)
                || orgForm.get("typeId") == null) {
            return error(mapping, request);
        }
    }

    // creating new organisation
    orgForm.set("orgId", null);
    Integer parentId = WebUtil.readIntParam(request, "parentId", true);
    if (parentId != null) {
        Organisation parentOrg = (Organisation) service.findById(Organisation.class, parentId);
        orgForm.set("parentName", parentOrg.getName());
    }
    request.getSession().setAttribute("locales", locales);
    request.getSession().setAttribute("status", status);
    return mapping.findForward("organisation");
}

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

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

    // check permission
    if (!request.isUserInRole(Role.SYSADMIN)) {
        request.setAttribute("errorName", "RegisterAction");
        request.setAttribute("errorMessage", AdminServiceProxy
                .getMessageService(getServlet().getServletContext()).getMessage("error.authorisation"));
        return mapping.findForward("error");
    }//from   w ww .  j ava  2s .c  o m

    userManagementService = AdminServiceProxy.getService(getServlet().getServletContext());

    RegisterForm registerForm = (RegisterForm) form;

    configurationService = getConfiguration();

    Registration reg = configurationService.getRegistration();
    if (reg == null) {
        reg = new Registration();
        reg.setPublicDirectory(true);
    }
    updateForm(registerForm, reg);

    RegisterDTO registerDTO = new RegisterDTO();

    // Get Server statistics for registration 
    List groups = userManagementService.findByProperty(Organisation.class,
            "organisationType.organisationTypeId", OrganisationType.COURSE_TYPE);
    List subgroups = userManagementService.findByProperty(Organisation.class,
            "organisationType.organisationTypeId", OrganisationType.CLASS_TYPE);

    registerDTO.setGroupNumber(Integer.valueOf(groups.size()));
    registerDTO.setSubgroupNumber(Integer.valueOf(subgroups.size()));
    registerDTO.setSysadminNumber(userManagementService.getCountRoleForSystem(Role.ROLE_SYSADMIN));
    registerDTO.setAdminNumber(userManagementService.getCountRoleForSystem(Role.ROLE_GROUP_ADMIN));
    registerDTO.setAuthorNumber(userManagementService.getCountRoleForSystem(Role.ROLE_AUTHOR));
    registerDTO.setMonitorNumber(userManagementService.getCountRoleForSystem(Role.ROLE_MONITOR));
    registerDTO.setManagerNumber(userManagementService.getCountRoleForSystem(Role.ROLE_GROUP_MANAGER));
    registerDTO.setLearnerNumber(userManagementService.getCountRoleForSystem(Role.ROLE_LEARNER));
    registerDTO.setAuthorAdminNumber(userManagementService.getCountRoleForSystem(Role.ROLE_AUTHOR_ADMIN));
    registerDTO.setUserNumber(Integer.valueOf(userManagementService.findAll(User.class).size()));
    registerDTO.setServerUrl(Configuration.get(ConfigurationKeys.SERVER_URL));
    registerDTO.setServerVersion(Configuration.get(ConfigurationKeys.VERSION));
    registerDTO.setServerBuild(Configuration.get(ConfigurationKeys.SERVER_VERSION_NUMBER));
    registerDTO.setServerLocale(Configuration.get(ConfigurationKeys.SERVER_LANGUAGE));
    registerDTO.setServerLanguageDate(Configuration.get(ConfigurationKeys.DICTIONARY_DATE_CREATED));

    request.setAttribute("registerDTO", registerDTO);

    return mapping.findForward("register");
}

From source file:be.fedict.hsm.admin.webapp.security.SecurityInterceptor.java

@AroundInvoke
public Object securityVerification(InvocationContext invocationContext) throws Exception {
    Method method = invocationContext.getMethod();
    Class<?> clazz = invocationContext.getMethod().getDeclaringClass();
    LOG.trace("security verification: " + clazz.getSimpleName() + "." + method.getName());
    RolesAllowed rolesAllowedAnnotation = method.getAnnotation(RolesAllowed.class);
    if (null == rolesAllowedAnnotation) {
        rolesAllowedAnnotation = clazz.getAnnotation(RolesAllowed.class);
    }//  w  w  w . java  2s .co  m
    String[] allowedRoles = rolesAllowedAnnotation.value();

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        throw new SecurityException("user not logged in");
    }

    boolean userInRole = false;
    for (String allowedRole : allowedRoles) {
        if (httpServletRequest.isUserInRole(allowedRole)) {
            LOG.trace("user in role: " + allowedRole);
            userInRole = true;
            break;
        }
    }
    if (false == userInRole) {
        throw new SecurityException("user not in allowed roles");
    }

    return invocationContext.proceed();
}

From source file:dk.dma.msinm.user.security.SecurityConf.java

/**
 * If the request does not have the required role for one of the matching
 * checked resources, then this checked resource is returned.
 * <p></p>/*w w w.j  av a2s  . c  o m*/
 * If the user does have the required role for all matching checked resources
 * then {@code null} is returned.
 *
 * @param request the request
 * @return the failing checked resource, or {@code null} if the user has the required role
 */
public CheckedResource lacksRequiredRole(HttpServletRequest request) {
    for (CheckedResource resource : getMatchingResources(request)) {
        for (String role : resource.requiredRoles) {
            if (!request.isUserInRole(role)) {
                return resource;
            }
        }
    }
    return null;
}