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:$.LoginController.java

@RequestMapping(value = "/mainmenu.do")
    public ExtjsStore getMenu(HttpServletRequest request, Device device, Locale locale) {
        String[] roles = null;/*from w ww.  j av a 2s . c  o  m*/
        if (request.getUserPrincipal() instanceof AbstractAuthenticationToken) {
            AbstractAuthenticationToken user = (AbstractAuthenticationToken) request.getUserPrincipal();
            roles = new String[user.getAuthorities().size()];
            GrantedAuthority[] ga = user.getAuthorities().toArray(new GrantedAuthority[0]);
            for (int i = 0; i < user.getAuthorities().size(); i++) {
                roles[i] = ga[i].getAuthority();
            }
        }
        ExtjsStore result = new ExtjsStore();
        com.katsu.springframework.web.servlet.menu.Device deviceAux;
        if (device.isMobile())
            deviceAux = com.katsu.springframework.web.servlet.menu.Device.MOBILE;
        else if (device.isNormal())
            deviceAux = com.katsu.springframework.web.servlet.menu.Device.DESKTOP;
        else
            deviceAux = com.katsu.springframework.web.servlet.menu.Device.TABLET;
        result.setData(this.menuService.getMenus(request.getContextPath(), deviceAux, locale, roles));
        return result;
    }

From source file:it.geosolutions.geostore.services.rest.auditing.AuditInfoExtractorTest.java

private static HttpServletRequest getHttpServletRequest() {
    HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
    Mockito.when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1");
    Mockito.when(httpServletRequest.getRemoteHost()).thenReturn("127.0.0.1");
    Mockito.when(httpServletRequest.getRemoteUser())
            .thenReturn("User[id=2, name=admin, group=[UserGroup[id=1, groupName=everyone]], role=ADMIN]");
    Mockito.when(httpServletRequest.getServerName()).thenReturn("localhost");
    UserGroup userGroup = Mockito.mock(UserGroup.class);
    Mockito.when(userGroup.getGroupName()).thenReturn("everyone");
    User user = Mockito.mock(User.class);
    Mockito.when(user.getName()).thenReturn("admin");
    Mockito.when(user.getRole()).thenReturn(Role.ADMIN);
    Mockito.when(user.getGroups()).thenReturn(Collections.singleton(userGroup));
    Authentication authentication = Mockito.mock(Authentication.class);
    Mockito.when(authentication.getPrincipal()).thenReturn(user);
    Mockito.when(httpServletRequest.getUserPrincipal()).thenReturn(authentication);
    return httpServletRequest;
}

From source file:xbdd.webapp.rest.BasicAuthFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (httpRequest.getUserPrincipal() == null) {
        final String basicAuth = httpRequest.getHeader(AUTHORIZATION_HEADER);

        if (basicAuth != null && StringUtils.startsWithIgnoreCase(basicAuth, BASIC_PREFIX)) {
            final String usernamePassword = new String(
                    Base64.decodeBase64(basicAuth.substring(BASIC_PREFIX.length()).trim()), "UTF-8");
            final String[] args = usernamePassword.split(BASIC_AUTH_SEPARATOR, 2);
            httpRequest.login(args[0], args[1]);
        } else {// www  .  j  a va 2  s  .com
            httpRequest.authenticate(httpResponse);
            return;
        }
    }

    filterChain.doFilter(request, response);
}

From source file:de.adorsys.oauth.loginmodule.OAuthClientIdLoginModule.java

private boolean validateRequest() throws LoginException {

    HttpServletRequest request = fromPolicyContext(HttpServletRequest.class);
    if (request != null && request.getUserPrincipal() != null) {
        return false;
    }//  w  w w . j a  v  a 2 s . c o  m

    AuthorizationRequest authorizationRequest = fromPolicyContext(AuthorizationRequest.class);
    if (authorizationRequest == null) {
        return false;
    }

    ClientID clientID = authorizationRequest.getClientID();

    String redirectionURIs = System.getProperty("oauth.clients." + clientID + ".redirectionURIs");
    if (redirectionURIs == null) {
        LOG.warn(
                "Unknow OAUTH ClientID {} requested a token. Please define system property 'oauth.clients.{}.redirectionURIs'.",
                clientID, clientID);
        throw new LoginException(
                "Unknow OAUTH ClientID {} requested a token. Please define system property 'oauth.clients.{}.redirectionURIs'.");
    }

    String redirectUri = authorizationRequest.getRedirectionURI().toString();

    for (String allowedUri : Arrays.asList(redirectionURIs.split(","))) {
        if (StringUtils.startsWithIgnoreCase(redirectUri, allowedUri)) {
            return true;
        }
    }

    LOG.warn(
            "OAUTH ClientID {} requested a token but the redirect urls does not match. Actual redirectionurl {} is not defined in {}.",
            clientID, authorizationRequest.getRedirectionURI(), redirectionURIs);
    throw new LoginException(
            "OAUTH ClientID {} requested a token but the redirect urls does not match. Actual redirectionurl {} is not defined in {}.");
}

From source file:edu.nwpu.gemfire.monitor.service.MemberDetailsService.java

public ObjectNode execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    ObjectNode responseJSON = mapper.createObjectNode();

    JsonNode requestDataJSON = mapper.readTree(request.getParameter("pulseData"));
    String memberName = requestDataJSON.get("MemberDetails").get("memberName").textValue();

    Cluster.Member clusterMember = cluster.getMember(StringUtils.makeCompliantName(memberName));
    if (clusterMember != null) {
        responseJSON.put("memberId", clusterMember.getId());
        responseJSON.put("name", clusterMember.getName());
        responseJSON.put("host", clusterMember.getHost());
        responseJSON.put("clusterId", cluster.getId());
        responseJSON.put("clusterName", cluster.getServerName());
        responseJSON.put("userName", userName);
        responseJSON.put("loadAverage", clusterMember.getLoadAverage());
        responseJSON.put("sockets", clusterMember.getTotalFileDescriptorOpen());
        responseJSON.put("threads", clusterMember.getNumThreads());
        responseJSON.put("offHeapFreeSize", clusterMember.getOffHeapFreeSize());
        responseJSON.put("offHeapUsedSize", clusterMember.getOffHeapUsedSize());
        responseJSON.put("regionsCount", clusterMember.getMemberRegionsList().length);

        // Number of member clients
        if (PulseController.getPulseProductSupport().equalsIgnoreCase(PulseConstants.PRODUCT_NAME_SQLFIRE)) {
            responseJSON.put("numClients", clusterMember.getNumSqlfireClients());
        } else {// www .j a  v a 2s.  c o  m
            responseJSON.put("numClients", clusterMember.getMemberClientsHMap().size());
        }

        DecimalFormat df2 = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN);
        Long diskUsageVal = clusterMember.getTotalDiskUsage();
        Double diskUsage = diskUsageVal.doubleValue() / 1024;

        responseJSON.put("diskStorageUsed", Double.valueOf(df2.format(diskUsage)));

        Cluster.Alert[] alertsList = cluster.getAlertsList();

        String status = "Normal";

        for (Cluster.Alert alert : alertsList) {
            if (clusterMember.getName().equals(alert.getMemberName())) {
                if (alert.getSeverity() == Cluster.Alert.SEVERE) {
                    status = "Severe";
                    break;
                } else if (alert.getSeverity() == Cluster.Alert.ERROR) {
                    status = "Error";
                } else if (alert.getSeverity() == Cluster.Alert.WARNING) {
                    status = "Warning";
                }
            }
        }

        responseJSON.put("status", status);

    } else {
        responseJSON.put("errorOnMember", "Member [" + memberName + "] is not available");
    }

    // Send json response
    return responseJSON;
}

From source file:business.security.CustomLoggingInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    log.trace(String.format("%s\t%s\t%s\t%s\t%s", new Date(), request.getRemoteAddr(),
            request.getUserPrincipal() == null ? " - " : request.getUserPrincipal().getName(),
            request.getMethod(), request.getRequestURI()));
    return super.preHandle(request, response, handler);
}

From source file:com.nixmash.springdata.mvc.controller.UserController.java

@RequestMapping(value = "/register", method = RequestMethod.GET)
public String registrationForm(@ModelAttribute UserDTO userDTO, HttpServletRequest request) {
    if (request.getUserPrincipal() != null)
        return "redirect:/";
    else//w w w .j a  va  2  s . c  o  m
        return REGISTER_VIEW;
}

From source file:be.fedict.hsm.admin.webapp.security.AuthenticationController.java

public boolean isLoggedIn() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    return null != userPrincipal;
}

From source file:com.pivotal.gemfire.tools.pulse.internal.service.MemberDetailsService.java

public JSONObject execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    JSONObject responseJSON = new JSONObject();
    try {/*from  ww w  .j av a 2  s  .  co  m*/

        JSONObject requestDataJSON = new JSONObject(request.getParameter("pulseData"));
        String memberName = requestDataJSON.getJSONObject("MemberDetails").getString("memberName");

        responseJSON.put("connectedFlag", cluster.isConnectedFlag());
        responseJSON.put("connectedErrorMsg", cluster.getConnectionErrorMsg());

        Cluster.Member clusterMember = cluster.getMember(StringUtils.makeCompliantName(memberName));
        if (clusterMember != null) {
            responseJSON.put("memberId", clusterMember.getId());
            responseJSON.put("name", clusterMember.getName());
            responseJSON.put("host", clusterMember.getHost());
            responseJSON.put("clusterId", cluster.getId());
            responseJSON.put("clusterName", cluster.getServerName());
            responseJSON.put("userName", userName);
            responseJSON.put("loadAverage", clusterMember.getLoadAverage());
            responseJSON.put("sockets", clusterMember.getTotalFileDescriptorOpen());
            responseJSON.put("openFDs", clusterMember.getTotalFileDescriptorOpen());
            responseJSON.put("threads", clusterMember.getNumThreads());
            responseJSON.put("offHeapFreeSize", clusterMember.getOffHeapFreeSize());
            responseJSON.put("offHeapUsedSize", clusterMember.getOffHeapUsedSize());
            responseJSON.put("regionsCount", clusterMember.getMemberRegionsList().length);

            // Number of member clients
            if (PulseController.getPulseProductSupport()
                    .equalsIgnoreCase(PulseConstants.PRODUCT_NAME_GEMFIREXD)) {
                responseJSON.put("numClients", clusterMember.getNumGemFireXDClients());
            } else {
                responseJSON.put("numClients", clusterMember.getMemberClientsHMap().size());
            }

            DecimalFormat df2 = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN);
            Long diskUsageVal = clusterMember.getTotalDiskUsage();
            Double diskUsage = diskUsageVal.doubleValue() / 1024;

            responseJSON.put("diskStorageUsed", Double.valueOf(df2.format(diskUsage)));

            Cluster.Alert[] alertsList = cluster.getAlertsList();

            String status = "Normal";

            for (Cluster.Alert alert : alertsList) {
                if (clusterMember.getName().equals(alert.getMemberName())) {
                    if (alert.getSeverity() == Cluster.Alert.SEVERE) {
                        status = "Severe";
                        break;
                    } else if (alert.getSeverity() == Cluster.Alert.ERROR) {
                        status = "Error";
                    } else if (alert.getSeverity() == Cluster.Alert.WARNING) {
                        status = "Warning";
                    }
                }
            }

            responseJSON.put("status", status);

        } else {
            responseJSON.put("errorOnMember", "Member [" + memberName + "] is not available");
        }

        // Send json response
        return responseJSON;
    } catch (JSONException e) {
        throw new Exception(e);
    }
}

From source file:org.soulwing.cas.filter.SimpleAuthorizationFilter.java

private void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    String userName = request.getUserPrincipal().getName();
    if (isAuthorized(userName)) {
        filterChain.doFilter(request, response);
    } else {//from   w w  w .  j  a  v  a2 s.  c  om
        log.info(userName + " is not authorized");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
}