Example usage for javax.servlet.http HttpServletRequest getRemoteAddr

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

Introduction

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

Prototype

public String getRemoteAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

Usage

From source file:com.google.identitytoolkit.GitkitClient.java

private JSONObject buildChangeEmailRequest(HttpServletRequest req, String gitkitToken) throws JSONException {
    return new JSONObject().put("email", req.getParameter("oldEmail")).put("userIp", req.getRemoteAddr())
            .put("newEmail", req.getParameter("newEmail")).put("idToken", gitkitToken)
            .put("requestType", "NEW_EMAIL_ACCEPT");
}

From source file:org.jasig.cas.web.support.InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapter.java

@Override
protected final int findCount(final HttpServletRequest request, final String usernameParameter,
        final int failureRangeInSeconds) {
    final String SQL = "Select count(*) from COM_AUDIT_TRAIL where AUD_CLIENT_IP = ? and AUD_USER = ? AND AUD_ACTION = ? AND APPLIC_CD = ? AND AUD_DATE >= ?";
    final String userToUse = constructUsername(request, usernameParameter);
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -1 * failureRangeInSeconds);
    final Date oldestDate = calendar.getTime();
    return this.jdbcTemplate.queryForInt(SQL,
            new Object[] { request.getRemoteAddr(), userToUse, INSPEKTR_ACTION, this.applicationCode,
                    oldestDate },/*  w  w  w  .  j  a  v  a  2  s.c  om*/
            new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP });
}

From source file:com.adito.security.actions.UpdatePrivateKeyPassphraseDispatchAction.java

private ActionForward cleanUpAndReturn(ActionMapping mapping, HttpServletRequest request, ActionForward af) {
    CoreUtil.removePageInterceptListener(request.getSession(), "updatePrivateKeyPassphrase");
    /*//from  w w  w  .j  a  va 2  s  .  c  o  m
     * And update the user attributes and fire the logon event
     */
    CoreServlet.getServlet()
            .fireCoreEvent(new CoreEvent(this, CoreEventConstants.LOGON,
                    getSessionInfo(request).getCredentials(), getSessionInfo(request))
                            .addAttribute(CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr())
                            .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost()));

    return af;
}

From source file:net.webpasswordsafe.server.webservice.rest.PasswordController.java

@RequestMapping(value = "/passwords/{passwordId}/currentValue", method = RequestMethod.GET)
public ModelAndView getCurrentPassword(@PathVariable("passwordId") String passwordId,
        HttpServletRequest request, @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    boolean isSuccess = false;
    String message = "";
    String currentPassword = "";
    try {// www.  j  a  v  a2 s . c om
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            Password password = passwordService.getPassword(Long.valueOf(passwordId));
            if (password != null) {
                currentPassword = passwordService.getCurrentPassword(password.getId());
                isSuccess = true;
            } else {
                message = "Password not found";
            }
        } else {
            message = "Invalid authentication";
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        isSuccess = false;
        message = e.getMessage();
    }
    return createModelAndView(isSuccess, message, "currentPassword", currentPassword);
}

From source file:com.google.sampling.experiential.server.PubExperimentServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json;charset=UTF-8");

    DateTimeZone timezone = TimeUtil.getTimeZoneForClient(req);
    log.info("Timezone is computed to be: " + timezone.toString());
    logPacoClientVersion(req);//from  w  w  w .j av a  2 s.  c  om

    User user = AuthUtil.getWhoFromLogin();
    String email = null;
    if (user != null) {
        email = AuthUtil.getEmailOfUser(req, user);
    } else {
        email = req.getRemoteAddr();
    }

    String selectedExperimentsParam = req.getParameter("id");

    String pacoProtocol = req.getHeader("pacoProtocol");
    if (pacoProtocol == null) {
        pacoProtocol = req.getParameter("pacoProtocol");
    }

    String experimentsJson = null;
    ExperimentServletHandler handler = null;
    if (selectedExperimentsParam != null) {
        handler = new ExperimentServletSelectedExperimentsFullLoadHandler(email, timezone,
                selectedExperimentsParam, pacoProtocol);
    }
    if (handler != null) {
        log.info("Loading experiments...");
        experimentsJson = handler.performLoad();
        resp.getWriter().println(scriptBust(experimentsJson));
    } else {
        resp.getWriter().println(scriptBust("Unrecognized parameters!"));
    }
}

From source file:org.alfresco.encryption.DefaultEncryptionUtils.java

/**
 * {@inheritDoc}//from   www . j ava 2 s.  co m
 */
@Override
public boolean authenticate(HttpServletRequest req, byte[] decryptedBody) {
    try {
        byte[] expectedMAC = getMac(req);
        Long timestamp = getTimestamp(req);
        if (timestamp == null) {
            return false;
        }
        String ipAddress = IPUtils.getRealIPAddress(req.getRemoteAddr());
        return authenticate(expectedMAC, new MACInput(decryptedBody, timestamp.longValue(), ipAddress));
    } catch (Exception e) {
        throw new AlfrescoRuntimeException("Unable to authenticate HTTP request", e);
    }
}

From source file:seava.j4e.web.controller.session.SessionController.java

/**
 * Pack extra information about login into a ThreadLocal to be passed to the
 * authentication-provider service/*from  ww  w  . java2s.c  o m*/
 * 
 * @param clientCode
 * @param language
 * @param request
 */
private void prepareLoginParamsHolder(String clientCode, String language, HttpServletRequest request) {

    ILoginParams lp = this.getApplicationContext().getBean(ILoginParams.class);

    String ip = request.getHeader("X-Forwarded-For");
    if (ip != null && !"".equals(ip)) {
        ip = ip.substring(0, ip.indexOf(","));
    } else {
        ip = request.getRemoteAddr();
    }

    lp.setRemoteIp(ip);
    lp.setUserAgent(request.getHeader("User-Agent"));
    lp.setRemoteHost(request.getRemoteHost());
    lp.setLanguage(language);
    lp.setClientCode(clientCode);
    LoginParamsHolder.params.set(lp);

}

From source file:org.ambraproject.user.EnsureUserAccountInterceptor.java

/**
 * Check for a user matching the SSO ticket, if one exists.  Forwards to new profile page if no matching user exists.
 * <p/>//from w ww .j a v  a2 s .c o m
 * The work flow is as such:
 * <p/>
 * 1. Check if there is a ticket from CAS
 * If not, then we do nothing.
 * If there is, then we:
 * 2. Check if a user object is in the session.
 * a. If not, look up the user in the database, and put it in the session.
 * i.  if the user is not in the database, this must be a new profile.  forward to profile creation page.
 * 3. Update the database to ensure that the email address on file for this user matches the one from CAS
 * TODO: this next step may be deprecated
 * 4. Check if the user object in the session has a display name
 * a. If not, the user is an old account.  forward to the update profile page
 *
 * @param actionInvocation
 * @return
 * @throws Exception
 */
public String intercept(final ActionInvocation actionInvocation) throws Exception {
    log.debug("ensure user account interceptor called");

    Map<String, Object> session = actionInvocation.getInvocationContext().getSession();

    //STEP 1: check if there is an auth id from cas
    final String authId = (String) session.get(AUTH_KEY);
    if (authId == null) {
        //No auth id, nothing to do here
        if (log.isDebugEnabled()) {
            log.debug("no single sign on user key");
            log.debug("ticket is: " + session.get(SINGLE_SIGNON_RECEIPT));
        }
        return actionInvocation.invoke();
    } else {
        //STEP 2: check if there's a user object in the session
        UserProfile ambraUser = (UserProfile) session.get(AMBRA_USER_KEY);
        if (ambraUser == null) {
            //No user object, so we must just be returning from CAS.  Look up the user in the db, and record their login
            final HttpServletRequest request = ServletActionContext.getRequest();
            ambraUser = (UserProfile) new TransactionTemplate(transactionManager)
                    .execute(new TransactionCallback() {
                        @Override
                        public Object doInTransaction(TransactionStatus transactionStatus) {
                            return userService.login(authId, new UserLogin(request.getRequestedSessionId(), //session id
                                    request.getRemoteAddr(), //ip
                                    request.getHeader("user-agent") //user-agent
                            ));
                        }
                    });
            if (ambraUser == null) {
                //No matching user in the database. redirect to the profile creation page
                log.debug("This is a new user with auth id: {}", authId);
                return ReturnCode.NEW_PROFILE;
            }
            //put the user in the session
            session.put(AMBRA_USER_KEY, ambraUser);
        }

        //STEP 3: make sure that ambra's email address matches the one from CAS
        String emailFromCAS = (String) session.get(SINGLE_SIGNON_EMAIL_KEY);
        if (emailFromCAS == null) {
            emailFromCAS = userService.fetchUserEmailFromCas(authId);
            session.put(SINGLE_SIGNON_EMAIL_KEY, emailFromCAS);
        }
        if (ambraUser.getEmail() == null || (!ambraUser.getEmail().equals(emailFromCAS))) {
            userService.updateEmail(ambraUser.getID(), emailFromCAS);
        }

        //STEP 4: Check if the user has a display name  (this is only relevant for old users)
        if (!StringUtils.hasText(ambraUser.getDisplayName())) {
            return ReturnCode.UPDATE_PROFILE;
        }
        //continue with the action invocation
        return actionInvocation.invoke();
    }
}

From source file:no.dusken.aranea.web.control.FormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws Exception {
    Mail mail = (Mail) object;//from w w w. j  a  v a2  s  .c  o m
    // this content does not change that often, allow one hour cache
    response.setHeader("Cache-Control", "max-age=3600");
    String hidden = ServletRequestUtils.getStringParameter(request, "info", null); //this is a hidden field,
    if (hidden != null && !hidden.equals("")) { //if filled, tis teh botz!
        log.info("Botfield filled in contestform. IP: " + request.getRemoteAddr());
        return new ModelAndView("redirect:");
    }
    String id = ServletRequestUtils.getStringParameter(request, "captchaID", null);
    String input = ServletRequestUtils.getStringParameter(request, "captchaText", null);

    //mailCleaner.cleanMail(mail);

    Boolean correct = true;
    if (id != null) {
        try {
            correct = imageCaptchaService.validateResponseForID(id, input);
        } catch (CaptchaServiceException e) { //When first pressing wrong key, then refreshing the captchaid is wrong
            correct = false;

        }
    }

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

    map.put("tlf", ServletRequestUtils.getStringParameter(request, "tlf", ""));

    if (correct || !captchaEnabled) {
        mailSender.sendEmail(mail, map, "no/dusken/aranea/base/web/mail/template.vm");
        return new ModelAndView("no/dusken/aranea/base/web/form/success");
    } else {
        map.put("CaptchaError", true);
        log.info("Input of wrong captcha");
        // view form
        map.put("captchaString", UUID.randomUUID().toString());
        map.put("entity", mail);
        logger.info("Input of wrong captcha in form");
        return new ModelAndView("no/dusken/aranea/base/web/form/form", map);
    }
}

From source file:be.dnsbelgium.rdap.servlet.LoggerFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    StatusExposingServletResponse response = new StatusExposingServletResponse(
            (HttpServletResponse) servletResponse);
    try {// w w w  .j av  a2 s.  c o m
        chain.doFilter(servletRequest, response);
    } finally {
        String currentUser = null;
        try {
            currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
        } catch (NullPointerException npe) {
            LOGGER.debug("No SecurityContext", npe);
        }
        LOGGER.info("{} {} {} {}", request.getRemoteAddr(), currentUser, request.getServletPath(),
                response.getStatus());
    }
}