Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getUserPrincipal.

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:org.onehippo.forge.content.exim.repository.jaxrs.AbstractContentEximService.java

/**
 * Find user principal's name from {@code securityContext} or {@code request}.
 * @param securityContext security context
 * @param request servlet request//ww  w .j  a va  2  s  .  c o  m
 * @return user principal's name from {@code securityContext} or {@code request}
 */
protected String getUserPrincipalName(SecurityContext securityContext, HttpServletRequest request) {
    if (securityContext != null) {
        Principal userPrincipal = securityContext.getUserPrincipal();
        if (userPrincipal != null) {
            return userPrincipal.getName();
        }
    }

    if (request != null) {
        Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal != null) {
            return userPrincipal.getName();
        }

        final String authHeader = request.getHeader("Authorization");

        if (StringUtils.isNotBlank(authHeader)) {
            if (StringUtils.startsWithIgnoreCase(authHeader, "Basic ")) {
                final String encoded = authHeader.substring(6).trim();
                final String decoded = new String(Base64.getDecoder().decode(encoded));
                return StringUtils.substringBefore(decoded, ":");
            }
        }
    }

    return null;
}

From source file:org.opendaylight.controller.web.DaylightWebAdmin.java

@RequestMapping(value = "/users/password/{username}", method = RequestMethod.POST)
@ResponseBody//  w ww .  j  a  va  2  s  .  c  om
public Status changePassword(@PathVariable("username") String username, HttpServletRequest request,
        @RequestParam(value = "currentPassword", required = false) String currentPassword,
        @RequestParam("newPassword") String newPassword) {
    IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    if (userManager == null) {
        return new Status(StatusCode.NOSERVICE, "User Manager unavailable");
    }

    Status status;
    String requestingUser = request.getUserPrincipal().getName();

    //changing own password
    if (requestingUser.equals(username)) {
        status = userManager.changeLocalUserPassword(username, currentPassword, newPassword);
        //enforce the user to re-login with new password
        if (status.isSuccess() && !newPassword.equals(currentPassword)) {
            userManager.userLogout(username);
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }

        //admin level user resetting other's password
    } else if (authorize(userManager, UserLevel.NETWORKADMIN, request)) {

        //Since User Manager doesn't have an unprotected password change API,
        //we re-create the user with the new password (and current roles).
        List<String> roles = userManager.getUserRoles(username);
        UserConfig newConfig = new UserConfig(username, newPassword, roles);

        //validate before removing existing config, so we don't remove but fail to add
        status = newConfig.validate();
        if (!status.isSuccess()) {
            return status;
        }

        userManager.userLogout(username);
        status = userManager.removeLocalUser(username);
        if (!status.isSuccess()) {
            return status;
        }
        if (userManager.addLocalUser(newConfig).isSuccess()) {
            status = new Status(StatusCode.SUCCESS, "Password for user " + username + " reset successfully.");
        } else {
            //unexpected
            status = new Status(StatusCode.INTERNALERROR,
                    "Failed resetting password for user " + username + ". User is now removed.");
        }

        //unauthorized
    } else {
        status = new Status(StatusCode.UNAUTHORIZED, "Operation not permitted");
    }

    if (status.isSuccess()) {
        DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "changed password for",
                username);
    }
    return status;
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testInjectCookiePrincipal() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.0.123");
    EasyMock.expect(request.getHeader("remote_user")).andReturn(null);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn("ieb");
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();//from  w ww. j a v  a2 s . c o  m
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:org.apache.geode.tools.pulse.internal.controllers.PulseController.java

@RequestMapping(value = "/dataBrowserQueryHistory", method = RequestMethod.GET)
public void dataBrowserQueryHistory(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ObjectNode responseJSON = mapper.createObjectNode();
    ArrayNode queryResult = null;/*from  w w w  . j  a  va 2 s  .com*/
    String action = "";

    try {
        // get cluster object
        Cluster cluster = Repository.get().getCluster();
        String userName = request.getUserPrincipal().getName();

        // get query string
        action = request.getParameter(QUERYSTRING_PARAM_ACTION);
        if (!StringUtils.isNotNullNotEmptyNotWhiteSpace(action)) {
            action = ACTION_VIEW;
        }

        if (action.toLowerCase().equalsIgnoreCase(ACTION_DELETE)) {
            String queryId = request.getParameter(QUERYSTRING_PARAM_QUERYID);
            if (StringUtils.isNotNullNotEmptyNotWhiteSpace(queryId)) {

                boolean deleteStatus = cluster.deleteQueryById(userName, queryId);
                if (deleteStatus) {
                    responseJSON.put("status", STATUS_REPSONSE_SUCCESS);
                } else {
                    responseJSON.put("status", STATUS_REPSONSE_FAIL);
                    responseJSON.put("error", ERROR_REPSONSE_QUERYNOTFOUND);
                }
            } else {
                responseJSON.put("status", STATUS_REPSONSE_FAIL);
                responseJSON.put("error", ERROR_REPSONSE_QUERYIDMISSING);
            }
        }

        // Get list of past executed queries
        queryResult = cluster.getQueryHistoryByUserId(userName);
        responseJSON.put("queryHistory", queryResult);
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }
    response.getOutputStream().write(responseJSON.toString().getBytes());

}

From source file:org.opendaylight.controller.topology.web.Topology.java

/**
 * Update node position//w  ww .  j  av a  2s.c  om
 *
 * This method is mainly used by the visual topology
 *
 * @param nodeId - The node to update
 * @return The node object
 */
@RequestMapping(value = "/node/{nodeId}", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> post(@PathVariable String nodeId, @RequestParam(required = true) String x,
        @RequestParam(required = true) String y, @RequestParam(required = false) String container,
        HttpServletRequest request) {
    String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;

    // Derive the privilege this user has on the current container
    String userName = request.getUserPrincipal().getName();
    Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);

    if (privilege != Privilege.WRITE) {
        return new HashMap<String, Object>(); // silently disregard new node position
    }

    String id = new String(nodeId);

    if (!metaCache.get(containerName).containsKey(id)) {
        return null;
    }

    Map<String, Object> node = metaCache.get(containerName).get(id);
    Map<String, String> data = (Map<String, String>) node.get("data");

    data.put("$x", x);
    data.put("$y", y);

    node.put("data", data);

    return node;
}

From source file:edu.nwpu.gemfire.monitor.controllers.PulseController.java

@RequestMapping(value = "/dataBrowserQueryHistory", method = RequestMethod.GET)
public void dataBrowserQueryHistory(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ObjectNode responseJSON = mapper.createObjectNode();
    ArrayNode queryResult = null;/*ww w . j a v a2 s .c o m*/
    String action = "";

    try {
        // get cluster object
        Cluster cluster = Repository.get().getCluster();
        String userName = request.getUserPrincipal().getName();

        // get query string
        action = request.getParameter(QUERYSTRING_PARAM_ACTION);
        if (!StringUtils.isNotNullNotEmptyNotWhiteSpace(action)) {
            action = ACTION_VIEW;
        }

        if (action.toLowerCase().equalsIgnoreCase(ACTION_DELETE)) {
            String queryId = request.getParameter(QUERYSTRING_PARAM_QUERYID);
            if (StringUtils.isNotNullNotEmptyNotWhiteSpace(queryId)) {

                boolean deleteStatus = cluster.deleteQueryById(userName, queryId);
                if (deleteStatus) {
                    responseJSON.put("status", STATUS_REPSONSE_SUCCESS);
                } else {
                    responseJSON.put("status", STATUS_REPSONSE_FAIL);
                    responseJSON.put("error", ERROR_REPSONSE_QUERYNOTFOUND);
                }
            } else {
                responseJSON.put("status", STATUS_REPSONSE_FAIL);
                responseJSON.put("error", ERROR_REPSONSE_QUERYIDMISSING);
            }
        }

        // Get list of past executed queries
        queryResult = cluster.getQueryHistoryByUserId(userName);
        responseJSON.put("queryHistory", queryResult);
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }
    response.getOutputStream().write(responseJSON.toString().getBytes());
}

From source file:com.pivotal.gemfire.tools.pulse.internal.controllers.PulseController.java

@RequestMapping(value = "/dataBrowserQueryHistory", method = RequestMethod.GET)
public void dataBrowserQueryHistory(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    JSONObject responseJSON = new JSONObject();
    JSONArray queryResult = null;//from   ww  w  .j  ava2s.co  m
    String action = "";
    try {

        // get cluster object
        Cluster cluster = Repository.get().getCluster();
        String userName = request.getUserPrincipal().getName();

        // get query string
        action = request.getParameter(QUERYSTRING_PARAM_ACTION);
        if (!StringUtils.isNotNullNotEmptyNotWhiteSpace(action)) {
            action = ACTION_VIEW;
        }

        if (action.toLowerCase().equalsIgnoreCase(ACTION_DELETE)) {
            String queryId = request.getParameter(QUERYSTRING_PARAM_QUERYID);
            if (StringUtils.isNotNullNotEmptyNotWhiteSpace(queryId)) {

                boolean deleteStatus = cluster.deleteQueryById(queryId);
                if (deleteStatus) {
                    responseJSON.put("status", STATUS_REPSONSE_SUCCESS);
                } else {
                    responseJSON.put("status", STATUS_REPSONSE_FAIL);
                    responseJSON.put("error", ERROR_REPSONSE_QUERYNOTFOUND);
                }
            } else {
                responseJSON.put("status", STATUS_REPSONSE_FAIL);
                responseJSON.put("error", ERROR_REPSONSE_QUERYIDMISSING);
            }
        }

        // Get list of past executed queries
        queryResult = cluster.getQueryHistoryByUserId(userName);
        responseJSON.put("queryHistory", queryResult);

    } catch (JSONException eJSON) {
        LOGGER.logJSONError(eJSON, new String[] { "action:" + action, "queryResult:" + queryResult });
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }
    response.getOutputStream().write(responseJSON.toString().getBytes());
}

From source file:org.opendaylight.controller.topology.web.Topology.java

/**
 * Topology of nodes and hosts in the network in JSON format.
 *
 * Mainly intended for consumption by the visual topology.
 *
 * @return - JSON output for visual topology
 *//*from  w w w.  j  a v a  2  s .co m*/
@RequestMapping(value = "/visual.json", method = RequestMethod.GET)
@ResponseBody
public Collection<Map<String, Object>> getLinkData(@RequestParam(required = false) String container,
        HttpServletRequest request) {
    String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;

    // Derive the privilege this user has on the current container
    String userName = request.getUserPrincipal().getName();
    Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);

    if (privilege == Privilege.NONE) {
        return null;
    }

    ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class,
            containerName, this);
    if (topologyManager == null) {
        return null;
    }
    ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
            containerName, this);
    if (switchManager == null) {
        return null;
    }

    Map<Node, Set<Edge>> nodeEdges = topologyManager.getNodeEdges();
    Map<Node, Set<NodeConnector>> hostEdges = topologyManager.getNodesWithNodeConnectorHost();
    int hostEdgesHashCode = getHostHashCode(hostEdges, topologyManager);
    List<Switch> nodes = switchManager.getNetworkDevices();

    List<SwitchConfig> switchConfigurations = new ArrayList<SwitchConfig>();
    for (Switch sw : nodes) {
        Node n = sw.getNode();
        SwitchConfig config = switchManager.getSwitchConfig(n.toString());
        switchConfigurations.add(config);
    }

    // initialize cache if needed
    if (!metaCache.containsKey(containerName)) {
        metaCache.put(containerName, new HashMap<String, Map<String, Object>>());
        // initialize hashes
        metaNodeHash.put(containerName, null);
        metaHostHash.put(containerName, null);
        metaNodeSingleHash.put(containerName, null);
        metaNodeConfigurationHash.put(containerName, null);
    }

    // return cache if topology hasn't changed
    if ((metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null
            && metaNodeSingleHash.get(containerName) != null
            && metaNodeConfigurationHash.get(containerName) != null)
            && metaNodeHash.get(containerName).equals(nodeEdges.hashCode())
            && metaHostHash.get(containerName).equals(hostEdgesHashCode)
            && metaNodeSingleHash.get(containerName).equals(nodes.hashCode())
            && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())) {
        return metaCache.get(containerName).values();
    }

    // cache has changed, we must assign the new values
    metaNodeHash.put(containerName, nodeEdges.hashCode());
    metaHostHash.put(containerName, hostEdgesHashCode);
    metaNodeSingleHash.put(containerName, nodes.hashCode());
    metaNodeConfigurationHash.put(containerName, switchConfigurations.hashCode());

    stagedNodes = new HashMap<String, Map<String, Object>>();
    newNodes = new HashMap<String, Map<String, Object>>();

    // nodeEdges addition
    addNodes(nodeEdges, topologyManager, switchManager, containerName);

    // single nodes addition
    addSingleNodes(nodes, switchManager, containerName);

    // hostNodes addition
    addHostNodes(hostEdges, topologyManager, containerName);

    repositionTopology(containerName);

    return metaCache.get(containerName).values();
}

From source file:org.picketlink.social.standalone.login.ExternalAuthentication.java

protected boolean processFacebook(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession();
    String state = (String) session.getAttribute("STATE");

    if (STATES.FINISH.name().equals(state)) {
        Principal principal = request.getUserPrincipal();
        if (principal == null) {
            principal = getFacebookPrincipal(request, response);
        }//from www  .  ja  v  a2 s  . com
        if (principal == null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        return dealWithFacebookPrincipal(request, response, principal);
    }

    if (state == null || state.isEmpty()) {
        return initialFacebookInteraction(request, response);
    }
    // We have sent an auth request
    if (state.equals(STATES.AUTH.name())) {
        return facebookProcessor.handleAuthStage(request, response);
    }

    // Principal facebookPrincipal = null;
    if (state.equals(STATES.AUTHZ.name())) {
        Principal principal = getFacebookPrincipal(request, response);

        if (principal == null) {
            log.error(
                    "Principal was null. Maybe login modules need to be configured properly. Or user chose no data");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }

        return dealWithFacebookPrincipal(request, response, principal);
    }
    return false;
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testCreateRolePerms() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);
    ApplicationContext appContext = mock(ApplicationContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")).thenReturn(null);
    when(context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
            .thenReturn(appContext);/*from  ww w.  j a v  a 2 s .  com*/
    when(context.getInitParameter("contextAuthConfigLocation")).thenReturn("somewhere");
    when(appContext.getResource("somewhere")).thenReturn(
            new DefaultResourceLoader().getResource("com/betfair/tornjak/monitor/overlay/auth.properties"));

    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(true);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);

    assertThat(auth, notNullValue());
    assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED));
}