Exemple #1
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, Exception {

    RequestDispatcher rd;
    try {
      // get db connection
      getConnection();

      if ("initSchoolCompletion".equals(request.getParameter("report"))) {
        if (request.isUserInRole(Constants.Role_Admin)) {
          request.setAttribute("schoolList", Dao.getSchoolList(connection));
        } else {
          request.setAttribute(
              "schoolList", Dao.getLimitedSchoolList(connection, getUmdPersonPk(request)));
        }
        rd =
            this.getServletContext().getRequestDispatcher(PRE_JSP_PARAMS + "/schoolCompletion.jsp");
        rd.forward(request, response);
      } else if ("initRoadTester".equals(request.getParameter("report"))) {
        if (request.isUserInRole(Constants.Role_Admin)) {
          request.setAttribute("testerList", Dao.getTesterList(connection));
        } else {
          request.setAttribute("testerList", getRoadTester(getLoggedInPerson(request)));
        }
        rd = this.getServletContext().getRequestDispatcher(PRE_JSP_PARAMS + "/roadTester.jsp");
        rd.forward(request, response);
      } else if ("initInstructorExpiration".equals(request.getParameter("report"))) {
        rd =
            this.getServletContext()
                .getRequestDispatcher(PRE_JSP_PARAMS + "/instructorExpiration.jsp");
        rd.forward(request, response);
      } else if ("initSchoolExpiration".equals(request.getParameter("report"))) {
        rd =
            this.getServletContext().getRequestDispatcher(PRE_JSP_PARAMS + "/schoolExpiration.jsp");
        rd.forward(request, response);
      } else if (request.getParameter("showPage") != null) {
        rd =
            this.getServletContext()
                .getRequestDispatcher(PRE_JSP_PARAMS + "/" + request.getParameter("page") + ".jsp");
        rd.forward(request, response);
      } else {
        createReport(request, response);
      }
    } catch (Exception e) {
      // show error page
      e.printStackTrace();
      request.setAttribute("errorMsg", e.getMessage());
      rd = this.getServletContext().getRequestDispatcher("/reportErrorPage.jsp");
      rd.forward(request, response);
    } finally {
      closeConnection();
    }
  }
 protected void testSuccessfulLogin(List<String> validGmailAddresses)
     throws IOException, ServletException {
   googleReturnsUserinfo();
   GoogleOauthFilter googleOauthFilter = filterNotYetAuthorised();
   HttpServletResponse response = mock(HttpServletResponse.class);
   HttpServletRequest request =
       request(
           "http",
           "myserver.co.uk",
           "webapp",
           "oauth.html",
           "state=http://myserver.co.uk/webapp/index.html?forename=brian&surname=may",
           "code=4/b--2fGSRhhkub2d0wg7dZoNFUXLN.EluGs0IJqNIcOl05ti8ZT3b3nc9jcwI");
   FilterChain chain = mock(FilterChain.class);
   googleOauthFilter.doFilter(request, response, chain);
   // we expect a redirect to the original page.
   verify(response)
       .sendRedirect("http://myserver.co.uk/webapp/index.html?forename=brian&surname=may");
   verifyZeroInteractions(chain);
   // now check the redirect contains a user principal.
   response = mock(HttpServletResponse.class);
   request =
       request("http", "myserver.co.uk", "webapp", "index.html", "forename=brian", "surname=may");
   when(userManager.getValidGmailAddresses()).thenReturn(validGmailAddresses);
   when(userManager.isUserInRole("*****@*****.**", "guitarist")).thenReturn(true);
   when(userManager.isUserInRole("*****@*****.**", "drummer")).thenReturn(false);
   RequestStoringFilterChain requestStoringFilterChain = new RequestStoringFilterChain();
   googleOauthFilter.doFilter(request, response, requestStoringFilterChain);
   HttpServletRequest filterRequest = requestStoringFilterChain.getRequest();
   verify(userManager)
       .createNewUserIfRequired(
           eq("*****@*****.**"), any(Userinfo.class), any(Credential.class));
   assertNotNull("The filter chain was not called.", filterRequest);
   assertNotNull("The user principal was not set.", filterRequest.getUserPrincipal());
   assertEquals(
       "The user principal had the wrong class",
       OauthPrincipal.class,
       filterRequest.getUserPrincipal().getClass());
   OauthPrincipal oauthPrincipal = (OauthPrincipal) filterRequest.getUserPrincipal();
   assertTrue(
       "The user was not found to be in the correct group.",
       filterRequest.isUserInRole("guitarist"));
   assertFalse(
       "The user was found to be in the wrong group.", filterRequest.isUserInRole("drummer"));
   assertEquals(
       "The user principal had the wrong email address",
       "*****@*****.**",
       oauthPrincipal.getUserinfo().getEmail());
 }
  @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: "******", actualRoles requested: "
            + roleCheck);

    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));
  }
 public static boolean isAuthorizedx(String roleName, HttpServletRequest servletReq) {
   boolean isAuthorized = false;
   if (servletReq.isUserInRole(roleName)) {
     isAuthorized = true;
   }
   return isAuthorized;
 }
 public Boolean getIsAdmin() {
   //        return sessionContext.isCallerInRole(FamRole.ADMIN_SITE.name());
   FacesContext context = FacesContext.getCurrentInstance();
   // recuperer l’objet request
   HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
   return request.isUserInRole(FamRole.ADMIN_SITE.name());
 }
  /** {@inheritDoc} */
  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    BufferedWriter bw =
        new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    ThreadCategory.setPrefix(MapsConstants.LOG4J_CATEGORY);
    log = ThreadCategory.getInstance(this.getClass());

    try {
      String user = request.getRemoteUser();

      if (log.isDebugEnabled()) log.debug("MapStartUp for user:"******"Error in map's startup", e);
      bw.write(ResponseAssembler.getMapErrorResponse(MapsConstants.MAPS_STARTUP_ACTION));
    } finally {
      bw.close();
    }

    return null;
  }
  /**
   * Retrieve user by id
   *
   * @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;
  }
  @RequestMapping(value = "/member/{nickname}")
  public String profileByNickname(
      @PathVariable String nickname, Model model, HttpServletRequest request) {
    User user =
        userDao.findUserByNickname(
            nickname,
            new Consumer<User>() {
              @Override
              public void accept(User u) {
                if (u != null) {
                  u.getCharacters().size();
                }
              }
            });

    if (user != null) {
      model.addAttribute("user", user);

      if (request.isUserInRole("ROLE_ADMIN")) {
        model.addAttribute("rankings", rankingDao.findAll());
      }
    }

    return "members/member_detail";
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!request.isUserInRole("2")) {
      response.sendRedirect("/");
    }

    Reponse uneReponse = new Reponse();
    uneReponse.setLibelle(request.getParameter("libelle"));
    uneReponse.setEst_correct(Boolean.parseBoolean(request.getParameter("estCorrect")));
    uneReponse.setId_question(Integer.parseInt(request.getParameter("idQuestion")));

    Question question = null;

    try {
      question = QuestionService.getQuestion(Integer.parseInt(request.getParameter("idQuestion")));
    } catch (NumberFormatException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (SQLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {
      ReponseService.insert(uneReponse);
      response.sendRedirect(
          "themeQuestRep?idTheme="
              + String.valueOf(question.getId_theme())
              + "&idQuestion="
              + request.getParameter("idQuestion"));
    } catch (Exception e) {
      doGet(request, response);
    }
  }
Exemple #10
0
  @Transactional
  public String approveVacation(Integer vacationId) {
    Vacation vacation = findVacation(vacationId);
    Set<VacationApproval> vacationApprovals = vacation.getVacationApprovals();

    Date responseDate = new Date();

    vacation.setStatus(dictionaryItemService.find(VacationStatusEnum.APPROVED.getId()));
    store(vacation);

    vacationApprovalProcessService.sendBackDateVacationApproved(vacation);

    if (!vacationApprovals.isEmpty()) {
      for (VacationApproval vacationApproval : vacationApprovals) {
        vacationApproval.setResult(true);
        vacationApproval.setResponseDate(responseDate);
        StringBuilder comment = new StringBuilder("Согласовано ");
        if (isVacationApprovePermission(vacation)) {
          comment.append("РЦК");
        } else if (request.isUserInRole(ROLE_ADMIN)) {
          comment.append("Администратором");
        }
        vacationApproval.setComment(comment.toString());
        vacationApprovalService.store(vacationApproval);
      }
    }

    return JsonUtil.format(
        anObjectBuilder().withField("isApproved", JsonNodeBuilders.aTrueBuilder()));
  }
  /* ------------------------------------------------------------ */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      response.setContentType("text/html");
      ServletOutputStream out = response.getOutputStream();
      out.println("<html>");
      out.println(
          "<HEAD><link rel=\"stylesheet\" type=\"text/css\"  href=\"stylesheet.css\"/></HEAD>");
      out.println("<h1>Jetty DeclareRoles Annotation Results</h1>");
      out.println("<body>");

      out.println("<h2>Roles</h2>");
      boolean result = request.isUserInRole("other");
      out.println(
          "<br/><b>Result: isUserInRole(\"other\")="
              + result
              + ":"
              + (result == false ? " <span class=\"pass\">PASS" : " <span class=\"fail\">FAIL")
              + "</span></b>");

      result = request.isUserInRole("manager");
      out.println(
          "<br/><b>Result: isUserInRole(\"manager\")="
              + result
              + ":"
              + (result ? " <span class=\"pass\">PASS" : " <span class=\"fail\">FAIL")
              + "</span></b>");
      result = request.isUserInRole("user");
      out.println(
          "<br/><b>Result: isUserInRole(\"user\")="
              + result
              + ":"
              + (result ? " <span class=\"pass\">PASS" : " <span class=\"fail\">FAIL")
              + "</span></b>");
      String context = _config.getServletContext().getContextPath();
      if (!context.endsWith("/")) context += "/";

      out.println("<p><A HREF=\"" + context + "logout.jsp\">Logout</A></p>");

      out.println("</body>");
      out.println("</html>");
      out.flush();
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  @ModelAttribute
  @RequestMapping(method = RequestMethod.GET)
  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.");
      }
    }

    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"));
    }
  }
  @RequestMapping(Routes.DEFAULT)
  public String defaultAfterLogin(HttpServletRequest request, Principal principal) {

    try {
      if (request.isUserInRole(User.ROLE_CUSTODIAN)) {
        return "redirect:/custodian/home";
      } else if (request.isUserInRole(User.ROLE_USER)) {
        if (currentCustomer(principal) == null) {
          return "/customer/nongbhome";
        }

        return "redirect:/RetailCustomer/" + currentCustomer(principal).getId() + "/home";
      }
    } catch (Exception ignore) {
      return "redirect:/login";
    }
    return "redirect:/home";
  }
 @RequestMapping(path = "/securesudo", method = RequestMethod.GET)
 @ResponseBody
 public String getManifestAttributes(HttpServletRequest request, HttpSession httpSession) {
   // DO note that this only covers roles that start by ROLE_****
   if (request.isUserInRole("ADMIN")) {
     return "OK! " + SecurityContextHolder.getContext().getAuthentication().getName();
   } else {
     throw new UnauthorizedException();
   }
 }
  /**
   * Determines if the request should be allowed for the action
   *
   * @param request The request
   * @param action The action object
   * @return True if allowed, false otherwise
   */
  protected boolean isAllowed(HttpServletRequest request, Object action) {
    for (String role : disallowedRoles) {
      if (request.isUserInRole(role)) {
        return false;
      }
    }

    if (allowedRoles.isEmpty()) {
      return true;
    }

    for (String role : allowedRoles) {
      if (request.isUserInRole(role)) {
        return true;
      }
    }

    return false;
  }
  @RequestMapping("/checkRoleProgrammatically")
  String checkRoleProgrammatically(HttpServletRequest request) {
    boolean isInAdminRole =
        request.isUserInRole(
            roles
                .ADMIN); // Will only work if rolePrefix is set  to "" in
                         // SpringSecurityWebAppConfig.

    return "checkRoleProgrammatically - is " + (isInAdminRole ? "" : "not") + " in ADMIN role";
  }
  /** Process POST requests/responses (login) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get our current session
    session = request.getSession();

    // get the number of logins
    /*if(session.getAttribute("loginAttempts") == null){
    	loginAttempts = 0;
    }

    //exceeded logins
    if(loginAttempts > 2){
    	String errorMessage = "Error: Number of Login Attempts Exceeded";
    	request.setAttribute("errorMessage", errorMessage);
    	url = "index.jsp";
    }else{	//proceed*/
    // pull the fields from the form
    String username = request.getParameter("email");
    String password = request.getParameter("password");

    // encrypt the password to check against what's stored in DB
    PasswordService pws = new PasswordService();
    String encryptedPass = pws.encrypt(password);

    // create a user helper class to make database calls, and call authenticate user method
    UserHelper uh = new UserHelper();
    User user = uh.authenticateUser(username, encryptedPass);

    // we've found a user that matches the credentials
    if (user != null) {
      // invalidate current session, then get new session for our user (combats: session hijacking)
      session.invalidate();
      session = request.getSession(true);
      session.setAttribute("user", user);
      url = "UserAccount.jsp";
      request.isUserInRole("translator");
      Cookie cookie = new Cookie("SSID", session.getId());
      response.addCookie(cookie);
    }
    // user doesn't exist, redirect to previous page and show error
    else {
      String errorMessage =
          "Error: Unrecognized Username or Password<br>Login attempts remaining: "
              + (3 - (loginAttempts));
      request.setAttribute("errorMessage", errorMessage);

      // track login attempts (combats: brute force attacks)
      session.setAttribute("loginAttempts", loginAttempts++);
      url = "index.jsp";
    }
    // }
    // forward our request along
    RequestDispatcher dispatcher = request.getRequestDispatcher(url);
    dispatcher.forward(request, response);
  }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      resp.setContentType("text/plain;charset=UTF-8");

      if (VALUE.equals(req.getParameter(PARAM)) && req.isUserInRole("tomcat")) {
        resp.getWriter().print("OK");
      } else {
        resp.getWriter().print("FAIL");
      }
    }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    HttpSession session = req.getSession();
    Principal p = req.getUserPrincipal();

    String username = p.getName();
    req.setAttribute("username", username);
    if (req.isUserInRole("user")) {
      session.setAttribute("user", true);
    } else if (req.isUserInRole("owner")) {
      session.setAttribute("owner", true);
      OwnerAccountPage ownerAccountPage = new OwnerAccountPage(entityManagerFactory);
      CharityOwner ownersCharity = ownerAccountPage.getCharity(username);
      req.setAttribute("charity", ownersCharity);
    }
    RequestDispatcher requestDispatcher = req.getRequestDispatcher("../WEB-INF/account.jsp");
    requestDispatcher.forward(req, resp);
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    if (req.isUserInRole("administrateur")) {
      req.setAttribute("role", "administrateur");
    } else {
      req.setAttribute("role", "utilisateur");
    }

    req.setAttribute("utils", udao.readAll());
    req.getRequestDispatcher("/WEB-INF/utilisateurs/index.jsp").forward(req, resp);
  }
 public static boolean isAuthorized(String roleNames, HttpServletRequest servletReq) {
   boolean isAuthorized = false;
   StringTokenizer tokenizer = new StringTokenizer(roleNames, ",");
   if (tokenizer.countTokens() > 0) {
     while (tokenizer.hasMoreTokens()) {
       String roleName = tokenizer.nextToken();
       if (servletReq.isUserInRole(roleName)) {
         isAuthorized = true;
         break;
       }
     }
   }
   return isAuthorized;
 }
 @RequestMapping(value = "/{fanficId}", method = RequestMethod.POST)
 public String removeFanfic(@PathVariable("fanficId") int fanficId, HttpServletRequest request) {
   if (!(request.isUserInRole(Role.ROLE_ADMIN)
       || fanficService
           .getFanficById(fanficId)
           .getAuthor()
           .getUsername()
           .equals(request.getRemoteUser()))) {
     return "redirect:/";
   }
   User author = fanficService.getFanficById(fanficId).getAuthor();
   fanficService.removeFanficById(author, fanficId);
   return "redirect:/user/" + author.getId();
 }
  /**
   * Called when admin wants to delete user. Deletes user by login.
   *
   * @param target login of user to be deleted.
   */
  @RequestMapping(value = "/admin/delete/{target}", method = RequestMethod.POST)
  @ResponseBody
  public void delete(@PathVariable String target, HttpServletRequest request) {
    logger.info("Delete POST request");

    if (!request.isUserInRole("ADMIN") || !userService.loginExists(target)) {
      String error = MessageFormat.format("Error trying delete user: {0}", target);
      logger.error(error);
      return;
    }

    UserAdminDto userAdminDto = userService.getUserAdminDto(target);
    userService.deleteUser(userAdminDto);
  }
  /**
   * Called when admin unbans user. Sets enabled access to user.
   *
   * @param target login of user to be unbanned.
   */
  @RequestMapping(value = "/admin/unban/{target}", method = RequestMethod.POST)
  @ResponseBody
  public void unban(@PathVariable String target, HttpServletRequest request) {
    logger.info("Unban POST request");

    if (!request.isUserInRole("ADMIN") || !userService.loginExists(target)) {
      String error = MessageFormat.format("Error trying unban user: {0}", target);
      logger.error(error);
      return;
    }

    UserAdminDto userAdminDto = userService.getUserAdminDto(target);
    userAdminDto.setAccess(Access.ALLOWED);
    userService.updateUser(userAdminDto);
  }
  /** Retrieve Decorator named in 'name' attribute. Checks the role if specified. */
  public Decorator getNamedDecorator(HttpServletRequest request, String name) {
    Decorator result = null;
    try {
      result = configLoader.getDecoratorByName(name);
    } catch (ServletException e) {
      e.printStackTrace();
    }

    if (result == null || (result.getRole() != null && !request.isUserInRole(result.getRole()))) {
      // if the result is null or the user is not in the role
      return super.getNamedDecorator(request, name);
    } else {
      return result;
    }
  }
  @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;

    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;
  }
  public static String showSecurity(HttpServletRequest req, String role) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Security Info\n");
    sbuff.append(" req.getRemoteUser(): ").append(req.getRemoteUser()).append("\n");
    sbuff.append(" req.getUserPrincipal(): ").append(req.getUserPrincipal()).append("\n");
    sbuff
        .append(" req.isUserInRole(")
        .append(role)
        .append("):")
        .append(req.isUserInRole(role))
        .append("\n");
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
Exemple #28
0
 @RequestMapping(value = "/{fanficId}", method = RequestMethod.GET)
 public String getFanfic(
     @PathVariable("fanficId") int fanficId, Model model, HttpServletRequest request) {
   settingModel(model);
   Fanfic fanfic = fanficService.getFanficById(fanficId);
   model.addAttribute("fanfic", fanfic);
   model.addAttribute("noChapters", fanfic.getChapters().size() == 0);
   model.addAttribute("noComments", fanfic.getComments().size() == 0);
   if (request.isUserInRole(Role.ROLE_ADMIN)
       || fanfic.getAuthor().getUsername().equals(request.getRemoteUser())) {
     model.addAttribute("canChangeFanfic", true);
   } else {
     model.addAttribute("canChangeFanfic", false);
   }
   return "fanfic";
 }
Exemple #29
0
  /**
   * 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.
   *
   * @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);
  }
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   String userId = null;
   try {
     HttpServletRequest httpRequest = (HttpServletRequest) request;
     Principal userPrincipal = httpRequest.getUserPrincipal();
     if (userPrincipal != null) {
       userId = userPrincipal.getName();
       boolean isAdminUser = httpRequest.isUserInRole(ApplicationRoles.ADMINISTRATOR_ROLE);
       UserManager.setUserId(userId);
       UserManager.setIsUserAdmin(isAdminUser);
       // pass the request along the filter chain
       chain.doFilter(request, response);
     }
   } finally {
     UserManager.cleanUp();
   }
 }