Java Code Examples for javax.servlet.http.HttpServletRequest#isUserInRole()

The following examples show how to use javax.servlet.http.HttpServletRequest#isUserInRole() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestController.java    From cerberus-source with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Read By Key
 *
 * @param request
 * @param test
 * @return
 */
@ApiImplicitParams({
    @ApiImplicitParam(required = true, dataType = "string", name = "test", value = "This is the test")})
@GetMapping("/readByKey")
public String readByKey(HttpServletRequest request, String test) {

    JSONObject object = new JSONObject();
    boolean userHasPermissions = request.isUserInRole("TestAdmin");

    try {
        // Calling Servlet Transversal Util.
        ServletUtil.servletStart(request);

        test = policy.sanitize(test);

        AnswerItem<Test> answerTest = testService.readByKey(test);

        if (answerTest.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            //if the service returns an OK message then we can get the item and convert it to JSONformat
            Gson gson = new Gson();
            Test testObj = (Test) answerTest.getItem();
            object.put("contentTable", new JSONObject(gson.toJson(testObj)));
        }

        object.put("hasPermissions", userHasPermissions);

    } catch (JSONException ex) {
        LOG.warn(ex);
    }
    return object.toString();

}
 
Example 2
Source File: OrganisationController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping(path = "/create")
   public String create(@ModelAttribute OrganisationForm organisationForm, HttpServletRequest request)
    throws Exception {
initLocalesAndStatus();

if (!(request.isUserInRole(Role.SYSADMIN) || userManagementService.isUserGlobalGroupManager())) {
    // only sysadmins and global group admins can create groups
    if (((organisationForm.getTypeId() != null)
	    && organisationForm.getTypeId().equals(OrganisationType.COURSE_TYPE))
	    || (organisationForm.getTypeId() == null)) {
	return error(request);
    }
}

// creating new organisation
organisationForm.setOrgId(null);
Integer parentId = WebUtil.readIntParam(request, "parentId", true);
if (parentId != null) {
    Organisation parentOrg = (Organisation) userManagementService.findById(Organisation.class,
	    parentId);
    organisationForm.setParentName(parentOrg.getName());
}
request.getSession().setAttribute("status", status);
return "organisation/createOrEdit";
   }
 
Example 3
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@GetMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 4
Source File: TestController.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Read
 *
 * @param request
 * @return
 */
@GetMapping("/read")
public String read(HttpServletRequest request) {

    boolean userHasPermissions = request.isUserInRole("TestAdmin");

    JSONObject object = new JSONObject();
    try {
        AnswerItem<JSONObject> answer = new AnswerItem<>(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED));
        AnswerList<Test> testList = new AnswerList<>();

        DataTableInformation dti = new DataTableInformation(request, "test,description,active,automated,tdatecrea");

        testList = testService.readByCriteria(dti.getStartPosition(), dti.getLength(), dti.getColumnName(), dti.getSort(), dti.getSearchParameter(), dti.getIndividualSearch());

        JSONArray jsonArray = new JSONArray();
        if (testList.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
            for (Test test : (List<Test>) testList.getDataList()) {
                Gson gson = new Gson();
                jsonArray.put(new JSONObject(gson.toJson(test)).put("hasPermissions", userHasPermissions));
            }
        }

        object.put("contentTable", jsonArray);
        object.put("hasPermissions", userHasPermissions);
        object.put("iTotalRecords", testList.getTotalRows());
        object.put("iTotalDisplayRecords", testList.getTotalRows());

    } catch (JSONException ex) {
        LOG.warn(ex);
    }
    return object.toString();
}
 
Example 5
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 6
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 7
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 8
Source File: AppServerLoginCommand.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
protected boolean doAuthorization(Principal principal, List roles, HttpServletRequest request)
    throws SecurityException
{
    for (Object role : roles)
    {
        if (request.isUserInRole((String)role))
            return true;
    }

    return false;
}
 
Example 9
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 10
Source File: TesterSupport.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/plain");
    resp.getWriter().print("OK");
    if (req.isUserInRole(ROLE)) {
        resp.getWriter().print("-" + ROLE);
    }
}
 
Example 11
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return redirect.apply("/events/");
    }
    return redirect.apply("/");
}
 
Example 12
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 13
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@GetMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 14
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 15
Source File: DefaultController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/events/";
    }
    return "redirect:/";
}
 
Example 16
Source File: UserRoleAuthorizationInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws ServletException, IOException {

	if (this.authorizedRoles != null) {
		for (String role : this.authorizedRoles) {
			if (request.isUserInRole(role)) {
				return true;
			}
		}
	}
	handleNotAuthorized(request, response, handler);
	return false;
}
 
Example 17
Source File: Summary.java    From trader with Apache License 2.0 4 votes vote down vote up
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String rows = null;

	try {
		rows = getTableRows(request);
	} catch (Throwable t) {
		logException(t);
		message = t.getMessage();
		error = true;
	}

	boolean editor = request.isUserInRole(EDITOR);
	Writer writer = response.getWriter();
	writer.append("<!DOCTYPE html>");
	writer.append("<html>");
	writer.append("  <head>");
	writer.append("    <title>Stock Trader</title>");
	writer.append("    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
	writer.append("  </head>");
	writer.append("  <body>");
	writer.append("    <img src=\"header.jpg\" width=\"534\" height=\"200\"/>");
	writer.append("    <br/>");
	writer.append("    <br/>");
	if (error) {
		writer.append("    Error communicating with the Portfolio microservice: \""+message+"\"");
		writer.append("    <p/>");
		writer.append("    Please consult the <i>trader</i> and <i>portfolio</i> pod logs for more details, or ask your administator for help.");
		writer.append("    <p/>");
	} else {
		writer.append("    <form method=\"post\"/>");
		if (editor) {
			writer.append("      <input type=\"radio\" name=\"action\" value=\""+CREATE+"\"> Create a new portfolio<br>");
		}
			writer.append("      <input type=\"radio\" name=\"action\" value=\""+RETRIEVE+"\" checked> Retrieve selected portfolio<br>");
		if (editor) {
			writer.append("      <input type=\"radio\" name=\"action\" value=\""+UPDATE+"\"> Update selected portfolio (add stock)<br>");
			writer.append("      <input type=\"radio\" name=\"action\" value=\""+DELETE+"\"> Delete selected portfolio<br>");
		}
		writer.append("      <br/>");
		writer.append("      <table border=\"1\" cellpadding=\"5\">");
		writer.append("        <tr>");
		writer.append("          <th></th>");
		writer.append("          <th>Owner</th>");
		writer.append("          <th>Total</th>");
		writer.append("          <th>Loyalty Level</th>");
		writer.append("        </tr>");
		writer.append(rows);
		writer.append("      </table>");
		writer.append("      <br/>");
		writer.append("      <input type=\"submit\" name=\"submit\" value=\"Submit\" style=\"font-family: sans-serif; font-size: 16px;\"/>");
		writer.append("      <input type=\"submit\" name=\"submit\" value=\"Log Out\" style=\"font-family: sans-serif; font-size: 16px;\"/>");
		writer.append("    </form>");
	}
	writer.append("    <br/>");
	writer.append("    <a href=\"https://github.com/IBMStockTrader\">");
	writer.append("      <img src=\"footer.jpg\"/>");
	writer.append("    </a>");
	writer.append("  </body>");
	writer.append("</html>");
}
 
Example 18
Source File: DeleteUser.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();

    String login = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("login"), "", charset);

    boolean userHasPermissions = request.isUserInRole("Administrator");

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(login)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "User")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "User name is missing!"));
        ans.setResultMessage(msg);
    } else if (!userHasPermissions) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "User")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "You don't have the right to do that"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */

        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IUserService userService = appContext.getBean(IUserService.class);

        AnswerItem resp = userService.readByKey(login);
        if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            if (resp.getItem() != null) {
                ans = userService.delete((User) resp.getItem());

                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Object updated. Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/DeleteUser", "DELETE", "Delete User : ['" + login + "']", request);
                }
            } else {
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                msg.setDescription(msg.getDescription().replace("%ITEM%", "User")
                        .replace("%OPERATION%", "Delete")
                        .replace("%REASON%", "User not found"));
                ans.setResultMessage(msg);
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();

}
 
Example 19
Source File: AuthServlet.java    From document-management-system with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);

    if (isMultipleInstancesAdmin(request) || request.isUserInRole(Config.DEFAULT_ADMIN_ROLE)) {
        try {

            if (action.equals("userCreate")) {
                userCreate(userId, request, response);
            } else if (action.equals("roleCreate")) {
                roleCreate(userId, request, response);
            } else if (action.equals("userEdit")) {
                userEdit(userId, request, response);
            } else if (action.equals("roleEdit")) {
                roleEdit(userId, request, response);
            } else if (action.equals("userDelete")) {
                userDelete(userId, request, response);
            } else if (action.equals("roleDelete")) {
                roleDelete(userId, request, response);
            }

            // Go to list
            if (action.startsWith("user")) {
                response.sendRedirect(request.getContextPath() + request.getServletPath() + "?action=userList");
            } else {
                response.sendRedirect(request.getContextPath() + request.getServletPath() + "?action=roleList");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            sendErrorRedirect(request, response, e);
        }
    } else {
        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_ACCESS_DENIED", request.getRequestURI(), null,
                request.getQueryString());

        AccessDeniedException ade = new AccessDeniedException("You should not access this resource");
        sendErrorRedirect(request, response, ade);
    }
}
 
Example 20
Source File: BaseServlet.java    From document-management-system with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Test if an user can access to administration when configured as SaaS: An user can
 * access if:
 * <p>
 * - Multiple Instances is active AND user id okmAdmin
 * - Multiple Instances is inactive AND user has AdminRole role
 */
public static boolean isMultipleInstancesAdmin(HttpServletRequest request) {
	return (Config.SYSTEM_MULTIPLE_INSTANCES || Config.CLOUD_MODE) && request.getRemoteUser().equals(Config.ADMIN_USER) ||
			!(Config.SYSTEM_MULTIPLE_INSTANCES || Config.CLOUD_MODE) && request.isUserInRole(Config.DEFAULT_ADMIN_ROLE);
}