Example usage for javax.servlet.http HttpServletRequest getRemoteUser

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

Introduction

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

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:org.apache.hadoop.http.HttpServer2.java

/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException// w  w  w .  ja v  a2  s  .  c  o  m
 */
public static boolean hasAdministratorAccess(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
        return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Unauthenticated users are not " + "authorized to access this page.");
        return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
            && !userHasAdministratorAccess(servletContext, remoteUser)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "User " + remoteUser + " is unauthorized to access this page.");
        return false;
    }

    return true;
}

From source file:com.tremolosecurity.scale.passwordreset.ResetController.java

@PostConstruct
public void init() {
    try {/*w w  w  .j  a va 2s  .  co  m*/
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();

        this.resetCfg = (ScalePasswordResetConfigType) commonConfig.getScaleConfig();
        this.resetSubmitted = false;
        this.errors = null;

        //Lookup the account
        this.attrs = new AttributeData(resetCfg.getAttributes());
        this.attributes = new ArrayList<ScaleAttribute>();

        this.login = request.getRemoteUser();

        UnisonUserData userData = this.scaleSession.loadUserFromUnison(this.login, this.attrs);

        this.user = userData.getUserObj();

        this.displayName = userData.getUserObj().getDisplayName();

        this.attributes = userData.getUserObj().getAttributes();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.exoplatform.social.service.rest.NotificationsRestService.java

/**
 * Redirects the current user to an associated page, such as user activity stream, portal homepage,
 * space homepage and user profile.// w  ww  .  j  a  va2  s  .co m
 * 
 * @param type Type of the redirected page.
 * @param objectId Id of the associated type that can be activity Id, space Id, or user remote Id.
 * @authentication
 * @request
 * GET: localhost:8080/rest/social/notifications/redirectUrl/view_full_activity/e1d2870c7f0001014e32114f6ff8a7ab
 * @return Redirects to the associated page.
 * @throws Exception
 */
@GET
@Path("redirectUrl/{type}/{objectId}")
public Response redirectUrl(@Context UriInfo uriInfo, @PathParam("type") String type,
        @PathParam("objectId") String objectId) throws Exception {
    Space space = null;
    Identity userIdentity = null;
    String targetURL = null;

    HttpServletRequest currentServletRequest = Util.getCurrentServletRequest();
    boolean hasLoggedIn = (currentServletRequest.getRemoteUser() != null);
    String redirectLink = null;
    if (!hasLoggedIn) {
        //If user is not authenticated, the query parameter will be removed after login
        //so we will not redirect to an activity with query parameter but with path parameter
        //this new link will be processed on activity stream portlet
        redirectLink = Util.getBaseUrl()
                + LinkProvider.getRedirectUri(ACTIVITY_ID_PREFIX + "/redirect/" + type + "/" + objectId);
    }

    try {
        checkAuthenticatedRequest();
        URL_TYPE urlType = URL_TYPE.valueOf(type);
        switch (urlType) {
        case view_full_activity: {
            targetURL = hasLoggedIn
                    ? Util.getBaseUrl() + LinkProvider.getRedirectUri(ACTIVITY_ID_PREFIX + "?id=" + objectId)
                    : redirectLink;
            break;
        }
        case view_full_activity_highlight_comment: {
            String activityId = objectId.split("-")[0];
            String commentId = objectId.split("-")[1];
            targetURL = hasLoggedIn
                    ? Util.getBaseUrl() + LinkProvider
                            .getRedirectUri(ACTIVITY_ID_PREFIX + "?id=" + activityId + "#comment-" + commentId)
                    : redirectLink;
            break;
        }
        case view_likers_activity: {
            targetURL = hasLoggedIn
                    ? Util.getBaseUrl()
                            + LinkProvider.getRedirectUri(ACTIVITY_ID_PREFIX + "?id=" + objectId + "&likes=1")
                    : redirectLink;
            break;
        }
        case reply_activity: {
            targetURL = hasLoggedIn
                    ? Util.getBaseUrl()
                            + LinkProvider.getRedirectUri(ACTIVITY_ID_PREFIX + "?id=" + objectId + "&comment=1")
                    : redirectLink;
            break;
        }
        case reply_activity_highlight_comment: {
            String activityId = objectId.split("-")[0];
            String commentId = objectId.split("-")[1];
            targetURL = hasLoggedIn
                    ? Util.getBaseUrl() + LinkProvider.getRedirectUri(
                            ACTIVITY_ID_PREFIX + "?id=" + activityId + "#comment-" + commentId + "&comment=1")
                    : redirectLink;
            break;
        }
        case user: {
            userIdentity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, objectId,
                    true);
            targetURL = Util.getBaseUrl() + LinkProvider.getUserProfileUri(userIdentity.getRemoteId());
            break;
        }
        case user_activity_stream: {
            userIdentity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, objectId,
                    true);
            targetURL = Util.getBaseUrl() + LinkProvider.getUserActivityUri(userIdentity.getRemoteId());
            break;
        }
        case space: {
            space = getSpaceService().getSpaceById(objectId);
            targetURL = Util.getBaseUrl() + LinkProvider.getActivityUriForSpace(space.getPrettyName(),
                    space.getGroupId().replace("/spaces/", ""));
            break;
        }
        case space_members: {
            space = getSpaceService().getSpaceById(objectId);
            targetURL = Util.getBaseUrl() + LinkProvider.getActivityUriForSpace(space.getPrettyName(),
                    space.getGroupId().replace("/spaces/", "")) + "/settings/members";
            break;
        }
        case portal_home: {
            targetURL = Util.getBaseUrl() + LinkProvider.getRedirectUri("");
            break;
        }
        case all_space: {
            targetURL = Util.getBaseUrl() + LinkProvider.getRedirectUri("all-spaces");
            break;
        }
        case connections: {
            targetURL = Util.getBaseUrl() + LinkProvider.getRedirectUri("connexions");
            break;
        }
        case connections_request: {
            userIdentity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, objectId,
                    true);
            targetURL = Util.getBaseUrl() + LinkProvider
                    .getRedirectUri("connexions/receivedInvitations/" + userIdentity.getRemoteId());
            break;
        }
        case space_invitation: {
            targetURL = Util.getBaseUrl() + LinkProvider.getRedirectUri("invitationSpace");
            break;
        }
        case notification_settings: {
            userIdentity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, objectId,
                    true);
            targetURL = Util.getBaseUrl()
                    + LinkProvider.getUserNotificationSettingUri(userIdentity.getRemoteId());
            break;
        }
        default: {
            targetURL = Util.getBaseUrl() + LinkProvider.getRedirectUri("");
            break;
        }
        }
    } catch (Exception e) {
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }

    // redirect to target page
    return Response.seeOther(URI.create(targetURL)).build();
}

From source file:org.ambraproject.wombat.controller.CommentController.java

@RequestMapping(name = "postCommentFlag", method = RequestMethod.POST, value = "/article/comments/flag")
@ResponseBody//from ww w  .  jav  a2 s . c om
public Object receiveCommentFlag(HttpServletRequest request, @RequestParam("reasonCode") String reasonCode,
        @RequestParam("comment") String flagCommentBody, @RequestParam("target") String targetCommentDoi)
        throws IOException {
    checkCommentsAreEnabled();

    Map<String, Object> validationErrors = commentValidationService.validateFlag(flagCommentBody);
    if (!validationErrors.isEmpty()) {
        return ImmutableMap.of("validationErrors", validationErrors);
    }

    String authId = request.getRemoteUser();
    final String creatorUserId = authId == null ? null : userApi.getUserIdFromAuthId(authId);
    ArticleCommentFlag flag = new ArticleCommentFlag(creatorUserId, flagCommentBody, reasonCode);

    Map<String, Object> comment = getComment(targetCommentDoi);
    String parentArticleDoi = getParentArticleDoiFromComment(comment);

    ApiAddress address = ApiAddress.builder("articles").embedDoi(parentArticleDoi).addToken("comments")
            .embedDoi(targetCommentDoi).addToken("flags").build();

    articleApi.postObject(address, flag);
    return ImmutableMap.of(); // the "201 CREATED" status is all the AJAX client needs
}

From source file:org.eclipse.orion.server.docker.servlets.DockerHandler.java

/**
 * Handle the disconnect request for the user. The request detaches the web socket from the container for the user
 * @param request//  w ww . j  av  a2 s  . c o m
 * @param response
 * @return true if the disconnect was successful.
 * @throws ServletException
 */
private boolean handleDisconnectDockerContainerRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String user = request.getRemoteUser();

    DockerServer dockerServer = getDockerServer();

    // get the container for the user
    DockerContainer dockerContainer = dockerServer.getDockerContainer(user);
    if (dockerContainer.getStatusCode() == DockerResponse.StatusCode.NO_SUCH_CONTAINER) {
        if (logger.isDebugEnabled()) {
            logger.debug("Docker Container for user " + user + " is not running, no need to stop it.");
        }
        return true;
    }

    // detach if we have an open connection for the user
    if (dockerServer.isAttachedDockerContainer(user)) {
        // stop the running container
        dockerContainer = dockerServer.stopDockerContainer(dockerContainer.getId());
        if (dockerContainer.getStatusCode() != DockerResponse.StatusCode.STOPPED) {
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, dockerContainer.getStatusMessage(), null));
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Stopped Docker Container " + dockerContainer.getIdShort() + " for user " + user);
            }
        }
        dockerServer.detachDockerContainer(user);
    }

    return true;
}

From source file:ejportal.webapp.action.UserAction.java

/**
 * Grab the user from the database based on the "id" passed in.
 * //w  w w . j  a  v a 2s  . co m
 * @return success if user found
 * @throws IOException
 *             can happen when sending a "forbidden" from
 *             response.sendError()
 */
public String edit() throws IOException {
    final HttpServletRequest request = this.getRequest();
    final boolean editProfile = (request.getRequestURI().indexOf("editProfile") > -1);

    // if URL is "editProfile" - make sure it's the current user
    if (editProfile && ((request.getParameter("id") != null) || (request.getParameter("from") != null))) {
        ServletActionContext.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        this.log.warn("User '" + request.getRemoteUser() + "' is trying to edit user '"
                + request.getParameter("id") + "'");
        return null;
    }

    // if a user's id is passed in
    if (this.id != null) {
        // lookup the user using that id
        this.user = this.userManager.getUser(this.id);
    } else if (editProfile) {
        this.user = this.userManager.getUserByUsername(request.getRemoteUser());
    } else {
        this.user = new User();
        // TODO hier hart kondiert - evtl aendern
        this.user.addRole(new Role("ROLE_EXTERN"));
        // user.addRole(new Role(Constants.USER_ROLE));
    }

    if (this.user.getUsername() != null) {
        this.user.setConfirmPassword(this.user.getPassword());

        // if user logged in with remember me, display a warning that they
        // can't change passwords
        this.log.debug("checking for remember me login...");

        final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx != null) {
            final Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                this.getSession().setAttribute("cookieLogin", "true");
                this.saveMessage(this.getText("userProfile.cookieLogin"));
            }
        }
    }

    return Action.SUCCESS;
}

From source file:org.alfresco.web.site.servlet.SlingshotAlfrescoConnector.java

/**
 * Overrides the super method to add the HTTP header used by an external SSO
 * to provide the authenticated user name when calling alfresco from share.
 *///w ww . j av a 2s  .c  o  m
@Override
protected void applyRequestHeaders(RemoteClient remoteClient, ConnectorContext context) {
    // Need to override the headers set on the remoteClient to include the 'userHeader'
    // The following duplicates much of the code in the super method. Creating a new
    // context with the userHeader is even more complex.

    // copy in cookies that have been stored back as part of the connector session
    ConnectorSession connectorSession = getConnectorSession();
    if (connectorSession != null) {
        Map<String, String> cookies = new HashMap<String, String>(8);
        for (String cookieName : connectorSession.getCookieNames()) {
            cookies.put(cookieName, connectorSession.getCookie(cookieName));
        }
        remoteClient.setCookies(cookies);
    }

    Map<String, String> headers = new HashMap<String, String>(8);
    if (context != null) {
        headers.putAll(context.getHeaders());
    }

    // Proxy the authenticated user name if we have password-less credentials (indicates SSO auth over a secure connection)
    if (getCredentials() != null) {
        String userHeader = getUserHeader();
        if (userHeader != null) {
            // TODO: This is not ideal - for scenarios where the request has come through a Spring Dispatcher servlet
            //       the request will be available in the ServletUtil helper, else if it has come through another route
            //       it will be available on the MTAuthenticationFilter - this should be resolved.
            HttpServletRequest req = ServletUtil.getRequest();
            if (req == null) {
                req = MTAuthenticationFilter.getCurrentServletRequest();
            }
            // MNT-15866: In some cases req can be null so we need to check it before getHeader from it
            String user = null;
            if (req != null) {
                user = req.getHeader(userHeader);
                if (user == null) {
                    // MNT-15795
                    user = req.getRemoteUser();
                }
            }
            if (user != null) {
                // MNT-11041 Share SSOAuthenticationFilter and non-ascii username strings
                if (!org.apache.commons.codec.binary.Base64.isBase64(user)) {
                    try {
                        user = org.apache.commons.codec.binary.Base64.encodeBase64String(
                                (new String(user.getBytes("ISO-8859-1"), "UTF-8")).getBytes("UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        //TODO
                    }
                    headers.put("Remote-User-Encode", Boolean.TRUE.toString());
                }
                headers.put(userHeader, user);
            }
        }
    }

    // stamp all headers onto the remote client
    if (headers.size() != 0) {
        remoteClient.setRequestProperties(headers);
    }
}

From source file:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java

/**
 * Add other properties from the request to the attributes map.
 *
 * @param httpServletRequest Http Servlet Request
 * @param attributes Map of attributes to add additional attributes to from the Http Request
 *//*from  w ww  . ja v a 2  s  . c  om*/
protected void addRequestProperties(final HttpServletRequest httpServletRequest,
        final Map<String, List<Object>> attributes) {
    if (this.remoteUserAttribute != null) {
        final String remoteUser = httpServletRequest.getRemoteUser();
        attributes.put(this.remoteUserAttribute, list(remoteUser));
    }
    if (this.remoteAddrAttribute != null) {
        final String remoteAddr = httpServletRequest.getRemoteAddr();
        attributes.put(this.remoteAddrAttribute, list(remoteAddr));
    }
    if (this.remoteHostAttribute != null) {
        final String remoteHost = httpServletRequest.getRemoteHost();
        attributes.put(this.remoteHostAttribute, list(remoteHost));
    }
    if (this.serverNameAttribute != null) {
        final String serverName = httpServletRequest.getServerName();
        attributes.put(this.serverNameAttribute, list(serverName));
    }
    if (this.serverPortAttribute != null) {
        final int serverPort = httpServletRequest.getServerPort();
        attributes.put(this.serverPortAttribute, list(serverPort));
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitRemoteHandlerV1.java

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException {
    try {/* w  ww.  j ava 2 s .co  m*/
        Path p = new Path(path);
        IPath filePath = p;
        if (p.segment(1).equals("file")) { //$NON-NLS-1$
            filePath = p.removeFirstSegments(1);
        } else if (p.segment(2).equals("file")) { //$NON-NLS-1$
            filePath = p.removeFirstSegments(2);
        }
        if (!AuthorizationService.checkRights(request.getRemoteUser(), "/" + filePath.toString(),
                request.getMethod())) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return true;
        }

        switch (getMethod(request)) {
        case GET:
            return handleGet(request, response, path);
        case POST:
            return handlePost(request, response, path);
        case DELETE:
            return handleDelete(request, response, path);
        }

    } catch (Exception e) {
        String msg = NLS.bind("Failed to handle /git/remote request for {0}", path); //$NON-NLS-1$
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    }
    return false;
}

From source file:org.kuali.rice.ken.web.spring.BaseSendNotificationController.java

/**
 * Prepares the model used for sending the notification.
 *
 * @param request the servlet request//  ww  w . ja va 2s  . c  om
 *
 * @return the Spring MVC model
 */
protected Map<String, Object> setupModelForSendNotification(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();

    model.put("defaultSender", request.getRemoteUser());
    model.put("channels", notificationChannelService.getAllNotificationChannels());
    model.put("priorities", dataObjectService
            .findMatching(NotificationPriorityBo.class, QueryByCriteria.Builder.create().build()).getResults());

    // set sendDateTime to current datetime if not provided
    String sendDateTime = request.getParameter("sendDateTime");
    String currentDateTime = Util.getCurrentDateTime();
    if (StringUtils.isEmpty(sendDateTime)) {
        sendDateTime = currentDateTime;
    }
    model.put("sendDateTime", sendDateTime);

    // retain the original date time or set to current if it was not in the request
    if (request.getParameter("originalDateTime") == null) {
        model.put("originalDateTime", currentDateTime);
    } else {
        model.put("originalDateTime", request.getParameter("originalDateTime"));
    }

    model.put("userRecipients", request.getParameter("userRecipients"));
    model.put("workgroupRecipients", request.getParameter("workgroupRecipients"));
    model.put("workgroupNamespaceCodes", request.getParameter("workgroupNamespaceCodes"));

    return model;
}