下面列出了javax.servlet.http.HttpServletRequest#isUserInRole() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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";
}
/**
* 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();
}
/**
* 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();
}
@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;
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@GetMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return redirect.apply("/events/");
}
return redirect.apply("/");
}
@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);
}
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
protected boolean doAuthorization(Principal principal, List roles, HttpServletRequest request)
throws SecurityException
{
for (Object role : roles)
{
if (request.isUserInRole((String)role))
return true;
}
return false;
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@RequestMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@GetMapping("/default")
public String defaultAfterLogin(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "redirect:/events/";
}
return "redirect:/";
}
@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);
}
}
/**
* @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>");
}
/**
* 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();
}
/**
* 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);
}