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:com.egt.core.util.Utils.java

public void trace(String objeto, String metodo, String contexto) {
    System.out.println(objeto + "." + metodo + "(" + contexto + ")");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println(objeto + "." + metodo + "(" + facesContext + ")");
    if (facesContext == null) {
        return;//w  w w . j a  v a  2 s.  c o m
    }
    traceContext();
    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    System.out.println("request ..................... " + request);
    System.out.println("request.getAuthType ......... " + request.getAuthType());
    System.out.println("request.getUserPrincipal .... " + request.getUserPrincipal());
    Principal principal = facesContext.getExternalContext().getUserPrincipal();
    System.out.println("principal ................... " + principal);
    if (principal != null) {
        System.out.println("principal.getName ........... " + principal.getName());
        System.out.println("isSuperUsuario .............. " + request.isUserInRole("SuperUsuario"));
        System.out.println("isUsuarioEstandar ........... " + request.isUserInRole("UsuarioEstandar"));
        System.out.println("isUsuarioBasico.. ........... " + request.isUserInRole("UsuarioBasico"));
    }
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    HttpSession session = request.getSession(false);
    System.out.println("session ..................... " + facesContext.getExternalContext().getSession(false));
    System.out.println("session.getId ............... " + session.getId());
    String key;
    Object object;
    Set sessionKeys = facesContext.getExternalContext().getSessionMap().keySet();
    if (sessionKeys.isEmpty()) {
    } else {
        Iterator iterator = sessionKeys.iterator();
        while (iterator.hasNext()) {
            object = iterator.next();
            if (object instanceof String) {
                key = (String) object;
                object = facesContext.getExternalContext().getSessionMap().get(key);
                if (object != null) {
                    System.out.println(key + " = (" + object.getClass().getName() + ") " + object);
                }
            }
        }
    }
    System.out.println("request.getContextPath ...... " + request.getContextPath());
    System.out.println("request.getServletPath ...... " + request.getServletPath());
    System.out.println("request.getPathInfo ......... " + request.getPathInfo());
    System.out.println("request.getRequestURI ....... " + request.getRequestURI());
    System.out.println("request.getContextPathURL ... " + request.getRequestURL().toString());
    String clave;
    System.out.println("*** parametros ***");
    Iterator iterator = request.getParameterMap().keySet().iterator();
    while (iterator.hasNext()) {
        clave = (String) iterator.next();
        System.out.println(clave + " = " + request.getParameter(clave));
    }
    String cookieName;
    System.out.println("**** cookies  ****");
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookieName = cookies[i].getName();
            System.out.println(cookieName + " = " + cookies[i].getValue());
        }
    }
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@Transactional
@RequestMapping("deleteFireFighter")
public String deleteFireFighter(Model model, @RequestParam int id, HttpServletRequest request) {
    //Error check? 
    // Error message wie oben ausgeben andi
    FireFighterModel deletedFireFighter = fireFighterRepository.findById(id);
    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        fireFighterRepository.delete(id);
    } else {/*from  w  w  w . j a v a2s.co m*/
        fireFighterRepository.deleteByFireBrigadeAndId(getSessionFireBrigade(), id);
    }
    model.addAttribute("message", "Mitglied " + " " + deletedFireFighter.getName() + " "
            + deletedFireFighter.getSurname() + " " + "wurde gelscht");
    return "forward:mitglieder";
}

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

private Collection<ReportDTO> listReportByUsernameAndScope(HttpServletRequest request, String scopeName,
        String roleName, String existent, Integer numberOfReport)
        throws ServiceException, ReportingServiceException {
    final String username = request.getRemoteUser();
    log.debug("{} is requesting listReports(...), with a scopeName={}", username, scopeName);
    Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
            scopeName);//from   ww  w .  jav  a  2  s  . c om
    String defaultId = usmService.getUserPreference(DEFAULT_REPORT_ID, username, getApplicationName(request),
            roleName, scopeName);
    Long defaultReportId = StringUtils.isNotBlank(defaultId) ? Long.valueOf(defaultId) : null;
    ReportFeatureEnum requiredFeature = AuthorizationCheckUtil.getRequiredFeatureToListReports();

    if (username != null && features != null
            && (requiredFeature == null || request.isUserInRole(requiredFeature.toString()))) {
        return reportService.listByUsernameAndScope(features, username, scopeName, "Y".equals(existent),
                defaultReportId, numberOfReport);
    } else {
        throw new ReportingServiceException(ErrorCodes.NOT_AUTHORIZED);
    }
}

From source file:org.openmrs.contrib.metadatarepository.webapp.filter.LocaleFilter.java

/**
 * This method looks for a "locale" request parameter. If it finds one, it sets it as the preferred locale
 * and also configures it to work with JSTL.
 * //from   w w  w .  j a  v a 2  s .  co  m
 * @param request the current request
 * @param response the current response
 * @param chain the chain
 * @throws IOException when something goes wrong
 * @throws ServletException when a communication failure happens
 */
@SuppressWarnings("unchecked")
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
        int indexOfUnderscore = locale.indexOf('_');
        if (indexOfUnderscore != -1) {
            String language = locale.substring(0, indexOfUnderscore);
            String country = locale.substring(indexOfUnderscore + 1);
            preferredLocale = new Locale(language, country);
        } else {
            preferredLocale = new Locale(locale);
        }
    }

    HttpSession session = request.getSession(false);

    if (session != null) {
        if (preferredLocale == null) {
            preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
        } else {
            session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
            Config.set(session, Config.FMT_LOCALE, preferredLocale);
        }

        if (preferredLocale != null && !(request instanceof LocaleRequestWrapper)) {
            request = new LocaleRequestWrapper(request, preferredLocale);
            LocaleContextHolder.setLocale(preferredLocale);
        }
    }

    String theme = request.getParameter("theme");
    if (theme != null && request.isUserInRole(Constants.ADMIN_ROLE)) {
        Map<String, Object> config = (Map) getServletContext().getAttribute(Constants.CONFIG);
        config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
}

From source file:org.apache.struts.action.RequestProcessor.java

/**
 * <p>If this action is protected by security roles, make sure that the
 * current user possesses at least one of them.  Return <code>true</code>
 * to continue normal processing, or <code>false</code> if an appropriate
 * response has been created and processing should terminate.</p>
 *
 * @param request  The servlet request we are processing
 * @param response The servlet response we are creating
 * @param mapping  The mapping we are using
 * @return <code>true</code> to continue normal processing;
 *         <code>false</code> if a response has been created.
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet exception occurs
 *//* www.  j a v  a2s.c o m*/
protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
        throws IOException, ServletException {
    // Is this action protected by role requirements?
    String[] roles = mapping.getRoleNames();

    if ((roles == null) || (roles.length < 1)) {
        return (true);
    }

    // Check the current user against the list of required roles
    for (int i = 0; i < roles.length; i++) {
        if (request.isUserInRole(roles[i])) {
            if (log.isDebugEnabled()) {
                log.debug(
                        " User '" + request.getRemoteUser() + "' has role '" + roles[i] + "', granting access");
            }

            return (true);
        }
    }

    // The current user is not authorized for this action
    if (log.isDebugEnabled()) {
        log.debug(" User '" + request.getRemoteUser() + "' does not have any required role, denying access");
    }

    response.sendError(HttpServletResponse.SC_FORBIDDEN,
            getInternal().getMessage("notAuthorized", mapping.getPath()));

    return (false);
}

From source file:org.lamsfoundation.lams.admin.web.action.UserSearchSingleTermAction.java

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

    service = AdminServiceProxy.getService(getServlet().getServletContext());
    String term = WebUtil.readStrParam(request, "term", true);
    Integer orgId = WebUtil.readIntParam(request, "orgId", true);

    if (StringUtils.isNotBlank(term)) {
        List users = new ArrayList();
        if (orgId != null) {
            // filter results according to user's roles
            Organisation org = (Organisation) service.findById(Organisation.class, orgId);
            Organisation group;/*from  w  w  w. jav a 2  s  . c o m*/
            if (org != null) {
                HttpSession session = SessionManager.getSession();
                if (session != null) {
                    UserDTO userDto = (UserDTO) session.getAttribute(AttributeNames.USER);
                    if (userDto != null) {
                        Integer userId = userDto.getUserID();
                        if (org.getOrganisationType().getOrganisationTypeId()
                                .equals(OrganisationType.CLASS_TYPE)) {
                            group = org.getParentOrganisation();
                        } else {
                            group = org;
                        }
                        // get search results, filtered according to orgId
                        if (request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin()) {
                            users = service.searchUserSingleTerm(term, orgId);
                        } else if (service.isUserInRole(userId, group.getOrganisationId(), Role.GROUP_ADMIN)
                                || service.isUserInRole(userId, group.getOrganisationId(),
                                        Role.GROUP_MANAGER)) {
                            if (group.getCourseAdminCanBrowseAllUsers()) {
                                users = service.searchUserSingleTerm(term, orgId);
                            } else if (org.getOrganisationType().getOrganisationTypeId()
                                    .equals(OrganisationType.CLASS_TYPE)) {
                                users = service.searchUserSingleTerm(term, group.getOrganisationId(), orgId);
                            }
                        }
                    }
                }
            }
        } else {
            // if there's no orgId param, search all users
            users = service.searchUserSingleTerm(term);
        }
        request.setAttribute("users", users);
    }

    return mapping.findForward("basiclist");
}

From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java

@RequestMapping("/channel/{channelId}/help/api")
@Secured(false)/*  www  .  ja va2  s  . co  m*/
@HttpConstraint(PERMIT)
public ModelAndView helpApi(@PathVariable("channelId") final String channelId,
        final HttpServletRequest request) {
    return withChannel(channelId, ReadableChannel.class, channel -> {
        final Map<String, Object> model = new HashMap<>();

        model.put("channel", channel.getInformation());
        model.put("sitePrefix", this.sitePrefix.getSitePrefix());

        final String exampleKey;
        if (request.isUserInRole("MANAGER")) {
            final Collection<DeployKey> keys = this.channelService
                    .getChannelDeployKeys(By.id(channel.getId().getId())).orElse(emptyList());
            exampleKey = keys.stream().map(DeployKey::getKey).findFirst().orElse(DEFAULT_EXAMPLE_KEY);
        } else {
            exampleKey = DEFAULT_EXAMPLE_KEY;
        }

        model.put("hasExampleKey", !DEFAULT_EXAMPLE_KEY.equals(exampleKey));

        model.put("exampleKey", exampleKey);
        model.put("exampleSitePrefix",
                makeCredentialsPrefix(this.sitePrefix.getSitePrefix(), "deploy", exampleKey));

        return new ModelAndView("channel/help/api", model);
    });
}

From source file:alpha.portal.webapp.filter.LocaleFilter.java

/**
 * This method looks for a "locale" request parameter. If it finds one, it
 * sets it as the preferred locale and also configures it to work with JSTL.
 * //from w  ww.  ja  va2 s  .c o  m
 * @param request
 *            the current request
 * @param response
 *            the current response
 * @param chain
 *            the chain
 * @throws IOException
 *             when something goes wrong
 * @throws ServletException
 *             when a communication failure happens
 */
@Override
@SuppressWarnings("unchecked")
public void doFilterInternal(HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    final String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
        final int indexOfUnderscore = locale.indexOf('_');
        if (indexOfUnderscore != -1) {
            final String language = locale.substring(0, indexOfUnderscore);
            final String country = locale.substring(indexOfUnderscore + 1);
            preferredLocale = new Locale(language, country);
        } else {
            preferredLocale = new Locale(locale);
        }
    }

    final HttpSession session = request.getSession(false);

    if (session != null) {
        if (preferredLocale == null) {
            preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
        } else {
            session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
            Config.set(session, Config.FMT_LOCALE, preferredLocale);
        }

        if ((preferredLocale != null) && !(request instanceof LocaleRequestWrapper)) {
            request = new LocaleRequestWrapper(request, preferredLocale);
            LocaleContextHolder.setLocale(preferredLocale);
        }
    }

    final String theme = request.getParameter("theme");
    if ((theme != null) && request.isUserInRole(Constants.ADMIN_ROLE)) {
        final Map<String, Object> config = (Map) this.getServletContext().getAttribute(Constants.CONFIG);
        config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
}

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

@PUT
@Path("/share/{id}/{visibility}")
@Produces(APPLICATION_JSON)/*from   w ww  .  j a v  a 2  s .com*/
@Consumes(APPLICATION_JSON)
public Response shareReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @PathParam("visibility") String visibility, @HeaderParam("scopeName") String scopeName,
        @HeaderParam("roleName") String roleName) {

    String username = request.getRemoteUser();
    VisibilityEnum newVisibility = VisibilityEnum.getByName(visibility);

    boolean isAdmin;

    log.debug("{} is requesting shareReport(...), with a ID={} with isShared={}", username, id, visibility);

    ReportFeatureEnum requiredFeature = null;

    switch (newVisibility) {
    case SCOPE:
        requiredFeature = ReportFeatureEnum.SHARE_REPORT_SCOPE;
        break;
    case PUBLIC:
        requiredFeature = ReportFeatureEnum.SHARE_REPORT_PUBLIC;
        break;
    default: // it is private scope which does not require any feature
        break;
    }

    Response restResponse;

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

        try {
            Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                    scopeName);
            isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());

            // it's just a visibility update, therefore the permitted service layers don't
            // matter much and we pass null
            ReportDTO reportToUpdate = reportService.findById(features, id, username, scopeName, isAdmin, null);

            if (reportToUpdate != null) {
                reportToUpdate.setVisibility(newVisibility);

                reportService.share(id, reportToUpdate.getCreatedBy(), reportToUpdate.getScopeName(), isAdmin,
                        newVisibility);

                restResponse = createSuccessResponse(AuthorizationCheckUtil
                        .listAllowedVisibilityOptions(reportToUpdate.getCreatedBy(), username, features));
            } else {
                restResponse = createErrorResponse(ErrorCodes.ENTRY_NOT_FOUND);
            }
        } catch (Exception e) {

            log.error("Sharing report failed.", e);

            return createErrorResponse(e.getMessage());

        }
    }

    return restResponse;
}

From source file:nl.nn.adapterframework.util.FileUtils.java

public static boolean readAllowed(String rules, HttpServletRequest request, String fileName)
        throws IOException {
    List<String> rulesList = Arrays.asList(rules.split("\\|"));
    for (String rule : rulesList) {
        List<String> parts = Arrays.asList(rule.trim().split("\\s+"));
        if (parts.size() != 3) {
            log.debug("invalid rule '" + rule + "' contains " + parts.size() + " part(s): " + parts);
        } else {/*  w  w  w.  j av a2 s  . c o m*/
            String canonicalFileName = null;
            try {
                canonicalFileName = new File(fileName).getCanonicalPath();
            } catch (Exception e) {
                log.error("cannot determine canonical path for file name '" + fileName + "'", e);
            }
            String canonicalPath = null;
            if ("*".equals(parts.get(0))) {
                canonicalPath = parts.get(0);
            } else {
                try {
                    canonicalPath = new File(parts.get(0)).getCanonicalPath();
                } catch (Exception e) {
                    log.error("cannot determine canonical path for first part '" + parts.get(0) + "' of rule",
                            e);
                }
            }
            if (canonicalFileName != null && canonicalPath != null) {
                String role = parts.get(1);
                String type = parts.get(2);
                log.debug("check allow read file '" + canonicalFileName + "' with rule path '" + canonicalPath
                        + "', role '" + role + "' and type '" + type + "'");
                if ("*".equals(canonicalPath) || canonicalFileName.startsWith(canonicalPath)) {
                    log.debug("path match");
                    if ("*".equals(role) || request.isUserInRole(role)) {
                        log.debug("role match");
                        if ("allow".equals(type)) {
                            log.debug("allow");
                            return true;
                        } else if ("deny".equals(type)) {
                            log.debug("deny");
                            return false;
                        } else {
                            log.error("invalid rule type");
                        }
                    }
                }
            }
        }
    }
    log.debug("deny");
    return false;
}