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:com.openkm.servlet.admin.LogCatServlet.java

/**
 * View log/*from   w  w  w  .j av  a2  s.c  o  m*/
 */
private void view(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("view({}, {})", request, response);
    int begin = WebUtils.getInt(request, "begin");
    int end = WebUtils.getInt(request, "end");
    String str = WebUtils.getString(request, "str");
    String file = WebUtils.getString(request, "file");
    ServletContext sc = getServletContext();
    File lf = new File(logFolder, file);
    sc.setAttribute("file", file);
    sc.setAttribute("begin", begin);
    sc.setAttribute("end", end);
    sc.setAttribute("str", str);
    sc.setAttribute("messages", FormatUtil.parseLog(lf, begin, end, str));
    sc.getRequestDispatcher("/admin/logcat_view.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_LOGCAT_VIEW", file, null, str);

    log.debug("view: void");
}

From source file:edu.isi.wings.portal.classes.config.Config.java

private void initializeUserConfig(HttpServletRequest request, String userid, String domainid) {
    this.userId = userid;
    this.domainId = domainid;
    this.viewerId = request.getRemoteUser();

    // Set default script values
    this.scriptPath = request.getRequestURI();

    if (this.domainId != null)
        this.userDomainUrl = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + "/" + this.getDomainId();

    this.sessionId = request.getSession().getId();

    if (this.viewerId == null)
        return;/* w  ww .j a  v a 2  s  . co  m*/

    // If no userId specified, then set the viewer as the user
    if (this.userId == null)
        this.userId = this.viewerId;

    if (!this.checkUser(null))
        return;

    this.exportUserUrl = serverUrl + contextRootPath + exportServletPath + "/" + usersRelativeDir + "/"
            + userId;
    this.userDir = storageDirectory + File.separator + usersRelativeDir + File.separator + userId;

    this.userPath = contextRootPath + "/" + usersRelativeDir + "/" + userId;

    // Create userDir (if it doesn't exist)
    File uf = new File(this.userDir);
    if (!uf.exists() && !uf.mkdirs())
        System.err.println("Cannot create user directory : " + uf.getAbsolutePath());

    // Get domain and user list
    DomainController dc = new DomainController(this);
    this.domainsList = dc.getReadableDomainsList();
    this.usersList = this.userapi.getUsersList();

    // Get user's selected domain
    this.domain = dc.getUserDomain();

    // If the domain isn't a part of the readable domain list,
    // then choose the first one
    if (this.domain == null || !domainsList.contains(this.domain.getDomainName())) {
        if (domainsList.size() > 0)
            this.domain = dc.getDomain(domainsList.get(0));
        else
            this.domain = null;
    }

    if (this.domain != null) {
        this.domainId = this.domain.getDomainName();
        this.userDomainUrl = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + "/" + this.domain.getDomainName();
    }
}

From source file:com.openkm.servlet.admin.ConfigServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    ServletContext sc = getServletContext();
    String action = null;// www .jav  a  2s  .c o  m
    String filter = "";
    String userId = request.getRemoteUser();
    Session dbSession = null;
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            ConfigStoredFile stFile = new ConfigStoredFile();
            Config cfg = new Config();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("filter")) {
                        filter = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("cfg_key")) {
                        cfg.setKey(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("cfg_type")) {
                        cfg.setType(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("cfg_value")) {
                        cfg.setValue(item.getString("UTF-8").trim());
                    }
                } else {
                    is = item.getInputStream();
                    stFile.setName(item.getName());
                    stFile.setMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));

                    if (cfg.getKey() != null && cfg.getKey().startsWith("logo")) {
                        String size = null;

                        if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_LOGIN)) {
                            size = "316x74>";
                        } else if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_REPORT)) {
                            size = "150x35>";
                        }

                        File tmpIn = FileUtils.createTempFileFromMime(stFile.getMime());
                        File tmpOut = FileUtils.createTempFileFromMime(stFile.getMime());
                        FileOutputStream fos = null;

                        try {
                            fos = new FileOutputStream(tmpIn);
                            IOUtils.copy(is, fos);
                            ImageUtils.resize(tmpIn, size, tmpOut);
                            data = FileUtils.readFileToByteArray(tmpOut);
                        } finally {
                            FileUtils.deleteQuietly(tmpIn);
                            FileUtils.deleteQuietly(tmpOut);
                            IOUtils.closeQuietly(fos);
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        data = IOUtils.toByteArray(is);
                        IOUtils.closeQuietly(is);
                    }

                    stFile.setContent(SecureStore.b64Encode(data));
                }
            }

            if (action.equals("create")) {
                if (Config.FILE.equals(cfg.getType())) {
                    cfg.setValue(new Gson().toJson(stFile));
                } else if (Config.BOOLEAN.equals(cfg.getType())) {
                    cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals("")));
                } else if (Config.SELECT.equals(cfg.getType())) {
                    ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey());

                    if (stSelect != null) {
                        for (ConfigStoredOption stOption : stSelect.getOptions()) {
                            if (stOption.getValue().equals(cfg.getValue())) {
                                stOption.setSelected(true);
                            }
                        }
                    }

                    cfg.setValue(new Gson().toJson(stSelect));
                }

                ConfigDAO.create(cfg);
                com.openkm.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString());
                list(userId, filter, request, response);
            } else if (action.equals("edit")) {
                if (Config.FILE.equals(cfg.getType())) {
                    cfg.setValue(new Gson().toJson(stFile));
                } else if (Config.BOOLEAN.equals(cfg.getType())) {
                    cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals("")));
                } else if (Config.SELECT.equals(cfg.getType())) {
                    ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey());

                    if (stSelect != null) {
                        for (ConfigStoredOption stOption : stSelect.getOptions()) {
                            if (stOption.getValue().equals(cfg.getValue())) {
                                stOption.setSelected(true);
                            } else {
                                stOption.setSelected(false);
                            }
                        }
                    }

                    cfg.setValue(new Gson().toJson(stSelect));
                }

                ConfigDAO.update(cfg);
                com.openkm.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString());
                list(userId, filter, request, response);
            } else if (action.equals("delete")) {
                ConfigDAO.delete(cfg.getKey());
                com.openkm.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null);
                list(userId, filter, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importConfig(userId, request, response, data, dbSession);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null);
                list(userId, filter, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:com.greenpepper.confluence.velocity.ConfluenceGreenPepper.java

public User getRemoteUser() {
    HttpServletRequest request = ServletActionContext.getRequest();

    if (request != null) {
        String remoteUserName = request.getRemoteUser();

        if (remoteUserName != null) {
            return getUserAccessor().getUser(remoteUserName);
        }//from w  w w.  ja va  2  s .  c  o  m
    }

    return AuthenticatedUserThreadLocal.getUser();
}

From source file:edu.isi.wings.portal.classes.Config.java

private void initializeUserConfig(HttpServletRequest request) {
    // Set userid, domainid, viewerId
    this.userId = request.getParameter("userid");
    this.domainId = request.getParameter("domainid");
    this.viewerId = request.getRemoteUser();

    // Set default script values
    this.scriptPath = this.contextRootPath + request.getServletPath();
    this.scriptArguments = new String[] {};

    String path = request.getPathInfo();
    if (path == null)
        path = "/";
    this.scriptArguments = path.split("/");
    if (this.scriptArguments.length > 0)
        this.scriptArguments = (String[]) ArrayUtils.remove(this.scriptArguments, 0);

    if (this.domainId != null) {
        this.userDomainUrl = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + "/" + this.getDomainId();
        this.scriptPath = this.userDomainUrl + request.getServletPath();
    } else if (this.userId != null) {
        this.scriptPath = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + request.getServletPath();
    }/*  w w w.j  a  va 2s. com*/

    this.sessionId = request.getSession().getId();

    if (this.viewerId == null)
        return;

    // If no userId specified, then set the viewer as the user
    if (this.userId == null)
        this.userId = this.viewerId;

    if (!this.checkUser(null))
        return;

    this.exportUserUrl = serverUrl + contextRootPath + exportServletPath + "/" + usersRelativeDir + "/"
            + userId;
    this.userPath = contextRootPath + "/" + usersRelativeDir + "/" + userId;
    this.userDir = storageDirectory + File.separator + usersRelativeDir + File.separator + userId;

    // Create userDir (if it doesn't exist)
    File uf = new File(this.userDir);
    if (!uf.exists() && !uf.mkdirs())
        System.err.println("Cannot create user directory : " + uf.getAbsolutePath());

    // Get domain and user list
    DomainController dc = new DomainController(1, this);
    this.domainsList = dc.getReadableDomainsList();
    this.usersList = this.userapi.getUsersList();

    // Get user's selected domain
    this.domain = dc.getUserDomain();

    // If the domain isn't a part of the readable domain list, 
    // then choose the first one
    if (this.domain == null || !domainsList.contains(this.domain.getDomainName())) {
        if (domainsList.size() > 0)
            this.domain = dc.getDomain(domainsList.get(0));
        else
            this.domain = null;
    }

    if (this.domain != null) {
        this.userDomainUrl = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + "/" + this.domain.getDomainName();
        this.domainId = this.domain.getDomainName();
    }
}

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

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*w ww  .  j  av a  2  s.  co  m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String type = "";
            String qs = "";
            byte[] data = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    executeMetadata(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DatabaseQueryServlet.GlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:org.beanfuse.security.monitor.SecurityFilter.java

/**
 * /*from  w  w  w .j  a  va  2  s.c  o  m*/
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String resource = resourceExtractor.extract(httpRequest);
    request.setAttribute("resourceName", resource);
    HttpSession session = httpRequest.getSession(true);
    if (null == monitor) {
        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(session.getServletContext());
        monitor = (SecurityMonitor) wac.getBean("securityMonitor", SecurityMonitor.class);
    }
    // ??login??
    if (!freeResources.contains(resource) && !monitor.isPublicResource(resource)) {
        OnlineActivity info = monitor.getSessionController().getOnlineActivity(session.getId());
        if (info != null && null != httpRequest.getRemoteUser()
                && !info.getPrincipal().equals(httpRequest.getRemoteUser())) {
            info = null;
        }
        if (null == info) {
            Authentication auth = null;
            // remember me
            if (monitor.enableRememberMe()) {
                auth = monitor.getRememberMeService().autoLogin(httpRequest);
            }
            if (null == auth) {
                auth = new SsoAuthentication(httpRequest);
                auth.setDetails(monitor.getUserDetailsSource().buildDetails(httpRequest));
            }
            try {
                monitor.authenticate(auth);
            } catch (AuthenticationException e) {
                // URL
                session.setAttribute(PREVIOUS_URL,
                        httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, loginFailPath);
                return;
            }
        } else if (info.isExpired()) {
            monitor.logout(session);
            // URL
            session.setAttribute(PREVIOUS_URL,
                    httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
            redirectTo((HttpServletRequest) request, (HttpServletResponse) response, expiredPath);
            return;
        } else {
            info.refreshLastRequest();
            boolean pass = monitor.isAuthorized(info.getUserid(), resource);
            if (pass) {
                logger.debug("user {} access {} success", info.getPrincipal(), resource);
            } else {
                logger.info("user {} cannot access resource[{}]", info.getPrincipal(), resource);
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, noAuthorityPath);
                return;
            }
        }
    } else {
        logger.debug("free or public resource {} was accessed", resource);
    }
    chain.doFilter(request, response);
}

From source file:io.hops.hopsworks.api.project.ProjectService.java

@POST
@Path("{id}/downloadCert")
@Produces(MediaType.APPLICATION_JSON)//from  www .  j a  v a 2  s  . c  om
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER })
public Response downloadCerts(@PathParam("id") Integer id, @FormParam("password") String password,
        @Context HttpServletRequest req) throws ProjectException, HopsSecurityException, DatasetException {
    Users user = userFacade.findByEmail(req.getRemoteUser());
    if (user.getEmail().equals(Settings.AGENT_EMAIL) || !authController.validatePwd(user, password, req)) {
        throw new HopsSecurityException(RESTCodes.SecurityErrorCode.CERT_ACCESS_DENIED, Level.FINE);
    }
    Project project = projectController.findProjectById(id);
    String keyStore = "";
    String trustStore = "";
    try {
        //Read certs from database and stream them out
        certificateMaterializer.materializeCertificatesLocal(user.getUsername(), project.getName());
        CertificateMaterializer.CryptoMaterial material = certificateMaterializer
                .getUserMaterial(user.getUsername(), project.getName());
        keyStore = Base64.encodeBase64String(material.getKeyStore().array());
        trustStore = Base64.encodeBase64String(material.getTrustStore().array());
        String certPwd = new String(material.getPassword());
        //Pop-up a message from admin
        messageController.send(user, userFacade.findByEmail(Settings.SITE_EMAIL), "Certificate Info", "",
                "An email was sent with the password for your project's certificates. If an email does not arrive shortly, "
                        + "please check spam first and then contact the administrator.",
                "");
        emailBean.sendEmail(user.getEmail(), Message.RecipientType.TO, "Hopsworks certificate information",
                "The password for keystore and truststore is:" + certPwd);
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new DatasetException(RESTCodes.DatasetErrorCode.DOWNLOAD_ERROR, Level.SEVERE, "projectId: " + id,
                ex.getMessage(), ex);
    } finally {
        certificateMaterializer.removeCertificatesLocal(user.getUsername(), project.getName());
    }
    CertsDTO certsDTO = new CertsDTO("jks", keyStore, trustStore);
    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(certsDTO).build();
}

From source file:org.apache.sling.httpauth.impl.AuthorizationHeaderAuthenticationHandler.java

/**
 * Sends back the form to log into the system.
 * /* w  ww  .j  a v a 2  s  .  co m*/
 * @param request The request object
 * @param response The response object to which to send the request
 * @return <code>true</code> is always returned by this handler
 * @throws IOException if an error occurrs sending back the form.
 */
public boolean requestAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    // if the response is already committed, we have a problem !!
    if (!response.isCommitted()) {

        // reset the response
        response.reset();
        response.setStatus(HttpServletResponse.SC_OK);

        String form = getLoginForm();

        if (form != null) {

            form = replaceVariables(form, "@@contextPath@@", request.getContextPath(), "/");
            form = replaceVariables(form, "@@authType@@", request.getAuthType(), "");
            form = replaceVariables(form, "@@user@@", request.getRemoteUser(), "");

            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(form);

        } else {

            // have no form, so just send 401/UNATHORIZED for simple login
            sendUnauthorized(response);

        }

    } else {

        log.error("requestAuthentication: Response is committed, cannot request authentication");

    }

    return true;
}