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:io.hops.hopsworks.api.user.AuthService.java

@POST
@Path("ldapLogin")
@Produces(MediaType.APPLICATION_JSON)//w  w  w .  jav  a2s .c om
public Response ldapLogin(@FormParam("username") String username, @FormParam("password") String password,
        @FormParam("chosenEmail") String chosenEmail, @FormParam("consent") boolean consent,
        @Context HttpServletRequest req) throws LoginException, UserException {
    RESTApiJsonResponse json = new RESTApiJsonResponse();
    if (username == null || username.isEmpty()) {
        throw new IllegalArgumentException("Username can not be empty.");
    }
    if (password == null || password.isEmpty()) {
        throw new IllegalArgumentException("Password can not be empty.");
    }
    LdapUserState ldapUserState = ldapUserController.login(username, password, consent, chosenEmail);
    if (!ldapUserState.isSaved()) {
        return Response.status(Response.Status.PRECONDITION_FAILED).entity(ldapUserState.getUserDTO()).build();
    }
    LdapUser ladpUser = ldapUserState.getLdapUser();
    if (ladpUser == null || ladpUser.getUid() == null) {
        throw new LoginException("Failed to get ldap user from table.");
    }
    Users user = ladpUser.getUid();
    // Do pre cauth realm check 
    String passwordWithSalt = authController.preLdapLoginCheck(user, ladpUser.getAuthKey());
    if (req.getRemoteUser() != null && !req.getRemoteUser().equals(user.getEmail())) {
        logoutAndInvalidateSession(req);
    }
    //only login if not already logged...
    if (req.getRemoteUser() == null) {
        login(user, user.getEmail(), passwordWithSalt, req);
    } else {
        req.getServletContext().log("Skip logged because already logged in: " + username);
    }
    //read the user data from db and return to caller
    json.setSessionID(req.getSession().getId());
    json.setData(user.getEmail());
    return Response.status(Response.Status.OK).entity(json).build();
}

From source file:alpha.portal.webapp.controller.CardFileUploadController.java

/**
 * handles the case, if the user clicks on one of the buttons.
 * //from w  w  w. j av a 2 s . c o m
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return success view
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws IOException {

    final String caseId = request.getParameter("case");
    final String cardId = request.getParameter("card");
    final Locale locale = request.getLocale();

    this.setCancelView("redirect:/caseform?caseId=" + caseId + "&activeCardId=" + cardId);
    this.setSuccessView("redirect:/caseform?caseId=" + caseId + "&activeCardId=" + cardId);

    final AlphaCard card = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId));
    if (card == null) {
        this.saveError(request, this.getText("card.invalidId", locale));
        return this.getCancelView();
    }
    final Adornment contributor = card.getAlphaCardDescriptor()
            .getAdornment(AdornmentType.Contributor.getName());

    if ((contributor.getValue() == null) || contributor.getValue().isEmpty()) {

        this.saveError(request, this.getText("adornment.noAccess", locale));
        return this.getCancelView();

    } else {

        final Long contributorID = Long.parseLong(contributor.getValue());
        final User currentUser = this.getUserManager().getUserByUsername(request.getRemoteUser());

        if (contributorID != currentUser.getId()) {

            this.saveError(request, this.getText("adornment.noAccess", locale));
            return this.getCancelView();
        }
    }

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.validator != null) { // validator is null during testing
        fileUpload.setName("alphaCardPayloadFile");

        this.validator.validate(fileUpload, errors);

        if (errors.hasErrors())
            return "redirect:/cardfileupload?card=" + cardId + "&case=" + caseId;
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "redirect:/cardfileupload?card=" + cardId + "&case=" + caseId;
    }

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final MultipartFile file = multipartRequest.getFile("file");

    Payload payload = new Payload(file.getOriginalFilename(), file.getContentType());
    payload.setContent(file.getBytes());

    payload = this.payloadManager.saveNewPayload(payload, card);

    this.saveMessage(request, this.getText("card.payloadOK", locale));
    return this.getSuccessView();
}

From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java

/**
 * Initialize MDC for logging the current request
 * @param actionInvariantId Action Invariant Id if available (null otherwise)
 * @param servletRequest Request Contecxt object
 * @param requestType Current action request (CRUD of Action, Artifact, Version operations)
 *//*from w  w  w .  ja v  a  2  s  .co  m*/
private void initializeRequestMDC(HttpServletRequest servletRequest, String actionInvariantId,
        ActionRequest requestType) {
    MDC.put(REQUEST_ID, servletRequest.getHeader(X_ECOMP_REQUEST_ID_HEADER_PARAM));
    MDC.put(PARTNER_NAME, servletRequest.getRemoteUser());
    MDC.put(INSTANCE_UUID, MDC_ASDC_INSTANCE_UUID);
    MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
    MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
    MDC.put(SERVICE_NAME, requestType.name());
    MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST));
    MDC.put(SERVICE_INSTANCE_ID, actionInvariantId);
    MDC.put(LOCAL_ADDR, MDC.get("ServerIPAddress"));
    MDC.put(BE_FQDN, MDC.get("ServerFQDN"));

    if (log.isDebugEnabled())
        MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name());
    else if (log.isInfoEnabled())
        MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name());
    else if (log.isWarnEnabled())
        MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name());
    else if (log.isErrorEnabled())
        MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name());
}

From source file:com.ikon.servlet.admin.PropertyGroupsServlet.java

/**
 * Register property group/*from  ww w . j  a v a2 s .c  o m*/
 */
private void register(Session session, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException,
        org.apache.jackrabbit.core.nodetype.compact.ParseException, javax.jcr.RepositoryException,
        InvalidNodeTypeDefException, DatabaseException {
    log.debug("register({}, {}, {})", new Object[] { session, request, response });

    // If it is ok, register it
    FileInputStream fis = null;

    try {
        if (Config.REPOSITORY_NATIVE) {
            DbRepositoryModule.registerPropertyGroups(Config.PROPERTY_GROUPS_XML);
        } else if (session != null) {
            // Check xml property groups definition
            FormUtils.resetPropertyGroupsForms();
            FormUtils.parsePropertyGroupsForms(Config.PROPERTY_GROUPS_XML);

            fis = new FileInputStream(Config.PROPERTY_GROUPS_CND);
            JcrRepositoryModule.registerCustomNodeTypes(session, fis);
        }
    } finally {
        IOUtils.closeQuietly(fis);
    }

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_REGISTER", null, null,
            Config.PROPERTY_GROUPS_CND);
    log.debug("register: void");
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    FilterChain filterChainWrapper = new FilterChain() {
        @Override//from   www .j a va2 s .c  o  m
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

            if (isKerberos) {
                Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                String userName = readUserFromCookie(httpResponse);

                if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                    userName = httpRequest.getRemoteUser();
                }

                if ((existingAuth == null || !existingAuth.isAuthenticated())
                        && (!StringUtils.isEmpty(userName))) {

                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider
                            .getAuthoritiesFromUGI(userName);

                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                            principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    SecurityContextHolder.getContext().setAuthentication(finalAuthentication);

                    request.setAttribute("atlas.http.authentication.type", true);
                    LOG.info("Logged into Atlas as = {}", userName);
                }
            }
            // OPTIONS method is sent from quick start jersey atlas client
            if (httpRequest.getMethod().equals("OPTIONS")) {
                optionsServlet.service(request, response);
            } else {
                try {
                    String requestUser = httpRequest.getRemoteUser();
                    NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                    RequestContext requestContext = RequestContext.get();
                    if (requestContext != null) {
                        requestContext.setUser(requestUser);
                    }
                    LOG.info("Request from authenticated user: {}, URL={}", requestUser,
                            Servlets.getRequestURI(httpRequest));

                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    NDC.pop();
                }
            }
        }
    };

    try {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
        responseWrapper.setHeader("X-Frame-Options", "DENY");

        if (existingAuth == null) {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper, filterChain);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    } catch (NullPointerException e) {
        LOG.error("Exception in AtlasAuthenticationFilter ", e);
        //PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
        ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "Authentication is enabled and user is not specified. Specify user.name parameter");
    }
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionsUtilityToolServlet.java

private void logApiCall(String uniqname, String originalUrl, HttpServletRequest request) {
    String loggingApiWithSessionInfo = null;
    String baseString = "CANVAS API request with Uniqname \"%s\" for URL \"%s\"";
    if (uniqname != null) {
        loggingApiWithSessionInfo = String.format(baseString, uniqname, originalUrl);
    } else if (request.getRemoteUser() != null) {
        loggingApiWithSessionInfo = String.format(baseString, request.getRemoteUser(), originalUrl);
    } else {/*from  www.j ava 2 s.  c  om*/
        loggingApiWithSessionInfo = String.format(baseString, request.getSession().getAttribute("testUser"),
                originalUrl);
    }
    M_log.info(loggingApiWithSessionInfo);
}

From source file:org.eclipse.orion.internal.server.servlets.workspace.WorkspaceServlet.java

private void doCreateWorkspace(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String userId = getUserId(req);
    if (!checkUser(userId, resp))
        return;// ww  w. j  a  v a  2  s  .co  m
    String workspaceName = req.getHeader(ProtocolConstants.HEADER_SLUG);
    if (workspaceName == null) {
        handleException(resp, "Workspace name not specified", null, HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    try {
        WorkspaceInfo workspace = new WorkspaceInfo();
        workspace.setFullName(workspaceName);
        workspace.setUserId(userId);
        OrionConfiguration.getMetaStore().createWorkspace(workspace);
        URI requestLocation = ServletResourceHandler.getURI(req);
        JSONObject result = WorkspaceResourceHandler.toJSON(workspace, requestLocation, requestLocation);
        writeJSONResponse(req, resp, result);
        String resultLocation = result.optString(ProtocolConstants.KEY_LOCATION);
        resp.setHeader(ProtocolConstants.KEY_LOCATION, resultLocation);

        // add user rights for the workspace
        String workspacePath = Activator.LOCATION_WORKSPACE_SERVLET + '/' + workspace.getUniqueId();
        AuthorizationService.addUserRight(req.getRemoteUser(), workspacePath);
        AuthorizationService.addUserRight(req.getRemoteUser(), workspacePath + "/*"); //$NON-NLS-1$
        // add user rights for file servlet location
        String filePath = Activator.LOCATION_FILE_SERVLET + '/' + workspace.getUniqueId();
        AuthorizationService.addUserRight(req.getRemoteUser(), filePath);
        AuthorizationService.addUserRight(req.getRemoteUser(), filePath + "/*"); //$NON-NLS-1$
    } catch (CoreException e) {
        handleException(resp, e.getStatus());
        return;
    }
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/** Test.
 * @throws ServletException e//  w  w w  . j ava 2  s .  c  om
 * @throws IOException e */
@Test
public void testDoFilterWithSessionBis() throws ServletException, IOException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final HttpSession session = createNiceMock(HttpSession.class);
    expect(request.getSession(false)).andReturn(session);
    // Locale sans pays
    expect(request.getLocale()).andReturn(Locale.FRENCH).anyTimes();
    // "X-Forwarded-For"
    expect(request.getHeader("X-Forwarded-For")).andReturn("somewhere").anyTimes();
    // getRemoteUser
    expect(request.getRemoteUser()).andReturn("me").anyTimes();
    replay(session);
    doFilter(request);
    verify(session);
}

From source file:org.opennms.web.controller.event.EventController.java

/**
 * Acknowledge the events specified in the POST and then redirect the client
 * to an appropriate URL for display.// w w  w  .  ja va2  s.com
 */
public ModelAndView acknowledgeByFilter(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // required parameter
    String[] filterStrings = request.getParameterValues("filter");
    String action = request.getParameter("actionCode");

    if (filterStrings == null) {
        filterStrings = new String[0];
    }

    if (action == null) {
        throw new MissingParameterException("actionCode", new String[] { "filter", "actionCode" });
    }

    // handle the filter parameters
    ArrayList<Filter> filterArray = new ArrayList<Filter>();
    for (String filterString : filterStrings) {
        Filter filter = EventUtil.getFilter(filterString, getServletContext());
        if (filter != null) {
            filterArray.add(filter);
        }
    }

    Filter[] filters = filterArray.toArray(new Filter[filterArray.size()]);

    EventCriteria criteria = new EventCriteria(filters);

    if (action.equals(AcknowledgeType.ACKNOWLEDGED.getShortName())) {
        m_webEventRepository.acknowledgeMatchingEvents(request.getRemoteUser(), new Date(), criteria);
    } else if (action.equals(AcknowledgeType.UNACKNOWLEDGED.getShortName())) {
        m_webEventRepository.unacknowledgeMatchingEvents(criteria);
    } else {
        throw new ServletException("Unknown acknowledge action: " + action);
    }
    return getRedirectView(request);
}

From source file:org.osaf.cosmo.dav.servlet.StandardRequestHandler.java

@SuppressWarnings("unchecked")
private void dumpRequest(HttpServletRequest req) {
    if (!log.isTraceEnabled())
        return;//from w  ww  . j  a  va2  s.c  om

    StringBuffer sb = new StringBuffer("\n------------------------ Dump of request -------------------\n");
    try {
        Enumeration names = req.getHeaderNames();

        sb.append("Request headers:\n");
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getHeader(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"\n");
        }

        names = req.getParameterNames();
        String title = "Request parameters";

        sb.append(title).append(" - global info and uris:").append("\n");
        sb.append("getMethod = ").append(req.getMethod()).append("\n");
        sb.append("getRemoteAddr = ").append(req.getRemoteAddr()).append("\n");
        sb.append("getRequestURI = ").append(req.getRequestURI()).append("\n");
        sb.append("getRemoteUser = ").append(req.getRemoteUser()).append("\n");
        sb.append("getRequestedSessionId = ").append(req.getRequestedSessionId()).append("\n");
        sb.append("HttpUtils.getRequestURL(req) = ").append(req.getRequestURL()).append("\n");
        sb.append("contextPath=").append(req.getContextPath()).append("\n");
        sb.append("query=").append(req.getQueryString()).append("\n");
        sb.append("contentlen=").append(req.getContentLength()).append("\n");
        sb.append("request=").append(req).append("\n");
        sb.append(title).append(":\n");

        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getParameter(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
            ;
        }
        sb.append("Request attributes:\n");
        for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            Object val = req.getAttribute(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
            ;
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    sb.append("------------------------ End dump of request -------------------");
    log.trace(sb);
}