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:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "editStatus", method = RequestMethod.GET)
public String showEditStatus(Model model, @RequestParam int id, HttpServletRequest request) {
    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireFighterStatusModel status = statusRepository.findById(id);
        if (status != null) {
            model.addAttribute("status", status);
            return "editStatus";
        } else {/*from w  ww .ja  va 2 s. co m*/
            model.addAttribute("errorMessage",
                    "Mitgliederstatus mit der ID " + id + " konnte nicht gefunden werden.");
            return "forward:status";
        }
    } else {
        FireFighterStatusModel status = statusRepository.findById(id);

        if (status != null) {
            model.addAttribute("status", status);
            return "editStatus";
        } else {
            model.addAttribute("errorMessage",
                    "Mitgliederstatus mit der ID " + id + " konnte nicht gefunden werden.");
            return "forward:status";
        }
    }

}

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

@RequestMapping(value = "editFunction", method = RequestMethod.GET)
public String showEditFunction(Model model, @RequestParam int id, HttpServletRequest request) {
    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireEngineAbbreviationModel fireEngineAbbreviation = fireEngineAbbreviationRepository.findById(id);
        if (fireEngineAbbreviation != null) {
            model.addAttribute("fireEngineAbbreviation", fireEngineAbbreviation);
            return "editFunction";
        } else {//from www.  ja v  a2  s  . com
            model.addAttribute("errorMessage",
                    "Fahrzeugfunktion mit der ID " + id + " konnte nicht gefunden werden.");
            return "forward:funktionen";
        }
    } else {
        FireEngineAbbreviationModel fireEngineAbbreviation = fireEngineAbbreviationRepository.findById(id);

        if (fireEngineAbbreviation != null) {
            model.addAttribute("fireEngineAbbreviation", fireEngineAbbreviation);
            return "editFunction";
        } else {
            model.addAttribute("errorMessage",
                    "Fahrzeugfunktion mit der ID " + id + " konnte nicht gefunden werden.");
            return "forward:funktionen";
        }
    }

}

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

@RequestMapping(value = "editRank", method = RequestMethod.GET)
public String showEditRank(Model model, @RequestParam int id, HttpServletRequest request) {
    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        RankModel rank = rankRepository.findById(id);
        if (rank != null) {
            model.addAttribute("rank", rank);
            return "editRank";
        } else {//from   ww  w  .  j av a2 s  . c  o  m
            model.addAttribute("errorMessage",
                    "Dienstgrad mit der ID " + id + " konnte nicht gefunden werden.");
            return "forward:dienstgrade";
        }
    } else {
        RankModel rank = rankRepository.findById(id);

        if (rank != null) {
            model.addAttribute("rank", rank);
            return "editRank";
        } else {
            model.addAttribute("errorMessage",
                    "Dienstgrad mit der ID " + id + " konnte nicht gefunden werden.");
            return "forward:dienstgrade";
        }
    }

}

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

@RequestMapping(value = { "uploadImage" })
public String uploadImage(Model model, @RequestParam int id, HttpServletRequest request) {

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireFighterModel fireFighter = fireFighterRepository.findById(id);
        if (fireFighter != null) {
            model.addAttribute("fireFighter", fireFighter);
            return "uploadImage";
        } else {/*from w  ww . ja va  2s.c o  m*/
            model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
            return "forward:mitglieder";
        }
    } else {
        FireFighterModel fireFighter = fireFighterRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                id);

        if (fireFighter != null) {
            model.addAttribute("fireFighter", fireFighter);
            return "uploadImage";
        } else {
            model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
            return "forward:mitglieder";
        }
    }

}

From source file:org.seasar.struts.action.S2RequestProcessor.java

@Override
protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
        throws IOException, ServletException {
    S2ExecuteConfig executeConfig = S2ExecuteConfigUtil.getExecuteConfig();
    if (executeConfig == null) {
        return true;
    }//www  .ja  va  2 s.  c  o  m
    String roles[] = executeConfig.getRoles();
    if (roles == null || roles.length == 0) {
        return true;
    }
    for (int i = 0; i < roles.length; i++) {
        if (request.isUserInRole(roles[i])) {
            return true;
        }
    }
    ActionForward forward = processException(request, response,
            new NoRoleRuntimeException(request.getRemoteUser()), null, mapping);
    if (forward != null) {
        processForwardConfig(request, response, forward);
    }
    return false;
}

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

@RequestMapping(value = { "/", "index" })
public String index(Model model, HttpServletRequest request) {

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        float males = fireFighterRepository.countByGender("m");
        float females = fireFighterRepository.countByGender("w");
        float sumFighters = males + females;
        float percentFem = females / sumFighters * 100;
        float percentMal = males / sumFighters * 100;
        percentFem = BigDecimal.valueOf(percentFem).setScale(2, RoundingMode.HALF_UP).floatValue();
        percentMal = BigDecimal.valueOf(percentMal).setScale(2, RoundingMode.HALF_UP).floatValue();
        model.addAttribute("males", percentMal);
        model.addAttribute("females", percentFem);
        model.addAttribute("sumFighters", sumFighters);
        List<Object[]> topFireBrigades = fireFighterRepository.groupByFireBrigade();
        Map<String, BigInteger> topFireBrigadesMap = topFireBrigades.stream().collect(Collectors.toMap(
                a -> (String) fireBrigadeRepository.findById((int) a[1]).getName(), a -> (BigInteger) a[0]));
        Map<String, BigInteger> sortedTopFireBrigadesMap = MapUtil.sortByValue(topFireBrigadesMap);
        model.addAttribute("sortedTopFireBrigades", sortedTopFireBrigadesMap);

    } else if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")
            && (request.isUserInRole("ROLE_ADMIN") || request.isUserInRole("ROLE_USER"))) {
        List<FireFighterModel> fireFighters = fireFighterRepository.findByFireBrigade(getSessionFireBrigade());
        model.addAttribute("fireFighters", fireFighters);
    }//from w ww .  j ava2s  . c  om
    return "index";
}

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

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            return getCancelView();
        } else {/*w w  w . ja va 2  s.co m*/
            return getSuccessView();
        }
    }

    if (validator != null) { // validator is null during testing
        validator.validate(user, errors);

        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return "userform";
        }
    }

    log.debug("entering 'onSubmit' method...");

    Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        getUserManager().removeUser(user.getId().toString());
        saveMessage(request, getText("user.deleted", user.getFullName(), locale));

        return getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE) || request.isUserInRole(Constants.USER_ROLE)) {
            String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (String roleName : userRoles) {
                    user.addRole(roleManager.getRole(roleName));
                }
            }
        }

        Integer originalVersion = user.getVersion();

        try {
            getUserManager().saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            saveMessage(request, getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                saveMessage(request, getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                message.setSubject(getText("signup.email.subject", locale));

                try {
                    sendUserMessage(user, getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (MailException me) {
                    saveError(request, me.getCause().getLocalizedMessage());
                }

                return getSuccessView();
            } else {
                saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "userform";
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@Override
public List<MenuEntry> getActions(final HttpServletRequest request, final Object object) {
    if (object instanceof ChannelInformation) {
        final ChannelInformation channel = (ChannelInformation) object;

        final Map<String, Object> model = new HashMap<>(1);
        model.put("channelId", channel.getId());

        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            if (!channel.getState().isLocked()) {
                result.add(new MenuEntry("Add Artifact", 100,
                        LinkTarget.createFromController(ChannelController.class, "add").expand(model),
                        Modifier.PRIMARY, null));
                result.add(new MenuEntry("Delete Channel", 400,
                        LinkTarget.createFromController(ChannelController.class, "delete").expand(model),
                        Modifier.DANGER, "trash").makeModalMessage("Delete channel",
                                "Are you sure you want to delete the whole channel?"));
                result.add(new MenuEntry("Clear Channel", 500,
                        LinkTarget.createFromController(ChannelController.class, "clear").expand(model),
                        Modifier.WARNING, null).makeModalMessage("Clear channel",
                                "Are you sure you want to delete all artifacts from this channel?"));

                result.add(new MenuEntry("Lock Channel", 600,
                        LinkTarget.createFromController(ChannelController.class, "lock").expand(model),
                        Modifier.DEFAULT, null));
            } else {
                result.add(new MenuEntry("Unlock Channel", 600,
                        LinkTarget.createFromController(ChannelController.class, "unlock").expand(model),
                        Modifier.DEFAULT, null));
            }//from  ww w  . j  ava2  s  . c  o  m

            result.add(new MenuEntry("Edit", 150, "Edit Channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "edit").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry("Maintenance", 160, "Refresh aspects", 100,
                    LinkTarget.createFromController(ChannelController.class, "refreshAllAspects").expand(model),
                    Modifier.SUCCESS, "refresh"));
        }

        if (request.getRemoteUser() != null) {
            result.add(new MenuEntry("Edit", 150, "Configure Aspects", 300,
                    LinkTarget.createFromController(ChannelController.class, "aspects").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry("Maintenance", 160, "Export channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "exportChannel").expand(model),
                    Modifier.DEFAULT, "export"));
        }

        return result;
    } else if (Tags.ACTION_TAG_CHANNELS.equals(object)) {
        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            // result.add ( new MenuEntry ( "Create Channel", 100, LinkTarget.createFromController ( ChannelController.class, "createDetailed" ), Modifier.PRIMARY, null ) );
            result.add(new MenuEntry("Create Channel", 120,
                    LinkTarget.createFromController(ChannelController.class, "createWithRecipe"),
                    Modifier.PRIMARY, null));
            result.add(new MenuEntry("Maintenance", 160, "Import channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "importChannel"), Modifier.DEFAULT,
                    "import"));
            result.add(new MenuEntry("Maintenance", 160, "Export all channels", 300,
                    LinkTarget.createFromController(ChannelController.class, "exportAll"), Modifier.DEFAULT,
                    "export"));
        }

        return result;
    }
    return null;
}

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

@RequestMapping(method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public PagedResources<UserResource> collectionList(Pageable pageable, PagedResourcesAssembler<User> assembler,
        @RequestParam(value = "firstName", required = false) String firstName,
        @RequestParam(value = "lastName", required = false) String lastName,
        @RequestParam(value = "mail", required = false) String mail, HttpServletRequest httpServletRequest) {

    Page<User> users = null;//from w  w w.j ava 2  s. c  o m

    try {
        if (firstName != null || lastName != null || mail != null) {

            if (firstName == null)
                firstName = "";
            if (lastName == null)
                lastName = "";
            if (mail == null)
                mail = "";

            users = userRepo.findByLastNameLikeIgnoreCaseAndFirstNameLikeIgnoreCaseAndMailLikeIgnoreCase(
                    "%" + lastName + "%", "%" + firstName + "%", "%" + mail + "%", pageable);
        } else {
            users = userRepo.findAllPaged(pageable);
        }

    } 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));
    }

    PagedResources<UserResource> resources = assembler.toResource(users, userResourceAssembler);
    resources.add(linkTo(UserController.class).withSelfRel());
    if (httpServletRequest.isUserInRole("AK_ADMIN")) {
        resources.add(linkTo(UserController.class).withRel(ActionsConstants.CREATE_VIA_POST));
        //On rajoute les liens sur les users
        for (UserResource resource : resources) {
            resource.add(linkTo(methodOn(UserController.class).userGet(resource.getTech_id(), null))
                    .withRel(ActionsConstants.UPDATE_VIA_PUT));
            resource.add(linkTo(methodOn(UserController.class).userGet(resource.getTech_id(), null))
                    .withRel(ActionsConstants.DELETE_VIA_DELETE));
        }
    }
    return resources;
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@RequestMapping("/channel/{channelId}/help/api")
@Secured(false)//from   www .j av  a  2s. co m
@HttpConstraint(PERMIT)
public ModelAndView helpApi(@PathVariable("channelId") final String channelId,
        final HttpServletRequest request) {
    final Channel channel = this.service.getChannel(channelId);
    if (channel == null) {
        return CommonController.createNotFound("channel", channelId);
    }

    final Map<String, Object> model = new HashMap<>();

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

    final String exampleKey;
    if (request.isUserInRole("MANAGER")) {
        exampleKey = channel.getDeployGroups().stream().flatMap(dg -> dg.getKeys().stream())
                .map(DeployKey::getKey).findFirst().orElse(DEFAULT_EXAMPLE_KEY);
    } else {
        exampleKey = DEFAULT_EXAMPLE_KEY;
    }

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

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