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.openecomp.sdcrests.action.rest.services.ActionsImpl.java

private Response uploadArtifactInternal(String actionInvariantUuId, String artifactName, String artifactLabel,
        String artifactCategory, String artifactDescription, String artifactProtection, String checksum,
        Attachment artifactToUpload, HttpServletRequest servletRequest) {
    ListResponseWrapper responseList = null;
    byte[] payload = null;
    Map<String, String> errorMap = validateRequestHeaders(servletRequest);
    //Artifact name empty validation
    if (StringUtils.isEmpty(artifactName)) {
        errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE,
                ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_NAME);
    } else {/*from  w w  w. ja va2s.  c  om*/
        //Artifact name syntax check for whitespaces and invalid characters
        if (artifactName.matches(invalidFilenameRegex)) {
            errorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_ARTIFACT_INVALID_NAME);
        }
    }

    //Content-Type Header Validation
    String contentType = servletRequest.getContentType();
    if (StringUtils.isEmpty(contentType)) {
        errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
    }

    if (artifactToUpload == null) {
        throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE,
                ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE);
    }

    InputStream artifactInputStream = null;
    try {
        artifactInputStream = artifactToUpload.getDataHandler().getInputStream();
    } catch (IOException e) {
        throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
    }

    payload = FileUtils.toByteArray(artifactInputStream);
    //Validate Artifact size
    if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
        throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR);
    }

    //Validate Checksum
    if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
        errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
    }

    //Validate artifact protection values
    if (StringUtils.isEmpty(artifactProtection))
        artifactProtection = ActionArtifactProtection.readWrite.name();

    if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name())
            && !artifactProtection.equals(ActionArtifactProtection.readWrite.name())) {
        errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
    }

    ActionArtifact uploadedArtifact = new ActionArtifact();
    if (errorMap.isEmpty()) {
        String user = servletRequest.getRemoteUser();
        ActionArtifact upload = new ActionArtifact();
        upload.setArtifactName(artifactName);
        upload.setArtifactLabel(artifactLabel);
        upload.setArtifactDescription(artifactDescription);
        upload.setArtifact(payload);
        upload.setArtifactCategory(artifactCategory);
        upload.setArtifactProtection(artifactProtection);
        uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUuId, user);
    } else {
        checkAndThrowError(errorMap);
    }
    return Response.ok(uploadedArtifact).build();
}

From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java

@Override
public List<MenuEntry> getActions(final HttpServletRequest request, final Object object) {
    if (object instanceof ChannelId) {
        final ChannelId channel = (ChannelId) object;

        final Map<String, Object> model = new HashMap<>(1);
        model.put("channelId", channel.getId());

        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            if (object instanceof ChannelInformation) {
                final ChannelInformation channelInformation = (ChannelInformation) object;

                if (!channelInformation.getState().isLocked()) {
                    result.add(new MenuEntry("Add Artifact", 100,
                            LinkTarget.createFromController(ChannelController.class, "add").expand(model),
                            Modifier.PRIMARY, null));
                    result.add(new MenuEntry("Delete Channel", 400,
                            LinkTarget.createFromController(ChannelController.class, "delete").expand(model),
                            Modifier.DANGER, "trash").makeModalMessage("Delete channel",
                                    "Are you sure you want to delete the whole channel?"));
                    result.add(new MenuEntry("Clear Channel", 500,
                            LinkTarget.createFromController(ChannelController.class, "clear").expand(model),
                            Modifier.WARNING, null).makeModalMessage("Clear channel",
                                    "Are you sure you want to delete all artifacts from this channel?"));

                    result.add(new MenuEntry("Lock Channel", 600,
                            LinkTarget.createFromController(ChannelController.class, "lock").expand(model),
                            Modifier.DEFAULT, null));
                } else {
                    result.add(new MenuEntry("Unlock Channel", 600,
                            LinkTarget.createFromController(ChannelController.class, "unlock").expand(model),
                            Modifier.DEFAULT, null));
                }/*from   w  w w.  ja  va2  s  .c o m*/
            }

            result.add(new MenuEntry("Edit", EDIT.getPriority(), "Edit Channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "edit").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry("Maintenance", 160, "Refresh aspects", 100,
                    LinkTarget.createFromController(ChannelController.class, "refreshAllAspects").expand(model),
                    Modifier.SUCCESS, "refresh"));
        }

        if (request.getRemoteUser() != null) {
            result.add(new MenuEntry("Edit", EDIT.getPriority(), "Configure Aspects", 300,
                    LinkTarget.createFromController(ChannelController.class, "aspects").expand(model),
                    Modifier.DEFAULT, null));
        }

        return result;
    } else if (Tags.ACTION_TAG_CHANNELS.equals(object)) {
        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            // result.add ( new MenuEntry ( "Create Channel", 100, LinkTarget.createFromController ( ChannelController.class, "createDetailed" ), Modifier.PRIMARY, null ) );
            result.add(new MenuEntry("Create Channel", 120,
                    LinkTarget.createFromController(ChannelController.class, "createWithRecipe"),
                    Modifier.PRIMARY, null));
        }

        return result;
    } else if (object instanceof org.eclipse.packagedrone.repo.channel.ChannelArtifactInformation) {
        final ChannelArtifactInformation ai = (ChannelArtifactInformation) object;

        final List<MenuEntry> result = new LinkedList<>();

        final Map<String, Object> model = new HashMap<>(2);
        model.put("channelId", ai.getChannelId().getId());
        model.put("artifactId", ai.getId());

        if (request.isUserInRole("MANAGER")) {
            if (ai.is("stored")) {
                result.add(new MenuEntry(
                        "Attach Artifact", 200, LinkTarget
                                .createFromController(ChannelController.class, "attachArtifact").expand(model),
                        Modifier.PRIMARY, null));
                result.add(new MenuEntry(
                        "Delete", 1000, LinkTarget
                                .createFromController(ChannelController.class, "deleteArtifact").expand(model),
                        Modifier.DANGER, "trash"));
            }
        }

        return result;
    }
    return null;
}

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

/**
 * Run the filter//w w w.j  a v  a 2s .c om
 * 
 * @param sreq ServletRequest
 * @param sresp ServletResponse
 * @param chain FilterChain
 * 
 * @exception IOException
 * @exception ServletException
 */
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain)
        throws IOException, ServletException {
    NDC.remove();
    NDC.push(Thread.currentThread().getName());
    final boolean debug = logger.isDebugEnabled();

    // Wrap externally authenticated requests that provide the user in an HTTP header
    // with one that returns the correct name from getRemoteUser(). For use in our own
    // calls to this method and any chained filters.
    sreq = wrapHeaderAuthenticatedRequest(sreq);

    // Bypass the filter if we don't have an endpoint with external auth enabled
    if (this.endpoint == null) {
        if (debug)
            logger.debug("There is no endpoint with external auth enabled.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // Get the HTTP request/response/session
    HttpServletRequest req = (HttpServletRequest) sreq;
    HttpServletResponse res = (HttpServletResponse) sresp;
    HttpSession session = req.getSession();

    if (req.getServletPath() != null && req.getServletPath().startsWith(UNAUTHENTICATED_ACCESS_PROXY)) {
        if (debug)
            logger.debug("SSO is by-passed for unauthenticated access endpoint.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // external invitation link should not trigger any SSO
    if (PAGE_SERVLET_PATH.equals(req.getServletPath()) && IGNORE_LINK.equals(req.getPathInfo())) {
        if (debug)
            logger.debug("SSO is by-passed for external invitation link.");
        chain.doFilter(sreq, sresp);
        return;
    }

    if (debug)
        logger.debug("Processing request " + req.getRequestURI() + " SID:" + session.getId());

    // Login page or login submission
    String pathInfo;
    if (PAGE_SERVLET_PATH.equals(req.getServletPath())
            && (LOGIN_PATH_INFORMATION.equals(pathInfo = req.getPathInfo())
                    || pathInfo == null && LOGIN_PARAMETER.equals(req.getParameter("pt")))) {
        if (debug)
            logger.debug("Login page requested, chaining ...");

        // Chain to the next filter
        chain.doFilter(sreq, sresp);
        return;
    }

    // initialize a new request context
    RequestContext context = null;
    try {
        // perform a "silent" init - i.e. no user creation or remote connections
        context = RequestContextUtil.initRequestContext(getApplicationContext(), req, true);
    } catch (Exception ex) {
        logger.error("Error calling initRequestContext", ex);
        throw new ServletException(ex);
    }

    // get the page from the model if any - it may not require authentication
    Page page = context.getPage();
    if (page != null && page.getAuthentication() == RequiredAuthentication.none) {
        if (logger.isDebugEnabled())
            logger.debug("Unauthenticated page requested - skipping auth filter...");
        chain.doFilter(sreq, sresp);
        return;
    }

    // If userHeader (X-Alfresco-Remote-User or similar) external auth - does not require a challenge/response
    if (this.userHeader != null) {
        String userId = AuthenticationUtil.getUserId(req);
        if (userId != null && req.getRemoteUser() != null) {
            if (logger.isDebugEnabled())
                logger.debug("userHeader external auth - skipping auth filter...");
            setExternalAuthSession(session);
            onSuccess(req, res, session, req.getRemoteUser());
            chain.doFilter(sreq, sresp);
            return;
        } else {
            // initial external user login requires a ping check to authenticate remote Session
            challengeOrPassThrough(chain, req, res, session);
            return;
        }
    }

    // Check if there is an authorization header with a challenge response
    String authHdr = req.getHeader(HEADER_AUTHORIZATION);

    // We are not passing on a challenge response and we have sufficient client session information
    if (authHdr == null && AuthenticationUtil.isAuthenticated(req)) {
        if (debug)
            logger.debug("Touching the repo to ensure we still have an authenticated session.");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }

    // Check the authorization header
    if (authHdr == null) {
        if (debug)
            logger.debug("New auth request from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":"
                    + req.getRemotePort() + ")");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }
    // SPNEGO / Kerberos authentication
    else if (authHdr.startsWith(AUTH_SPNEGO) && this.krbRealm != null) {
        if (debug)
            logger.debug("Processing SPNEGO / Kerberos authentication.");
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decode(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (logger.isDebugEnabled())
                logger.debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
            return;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            if (debug)
                logger.debug("Parsing the SPNEGO security blob to get the Kerberos ticket.");

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    if (debug)
                        logger.debug("Kerberos logon.");
                    //  Kerberos logon

                    if (doKerberosLogon(negToken, req, res, session) != null) {
                        // Allow the user to access the requested page

                        chain.doFilter(req, res);
                        if (logger.isDebugEnabled())
                            logger.debug("Request processing ended");
                    } else {
                        // Send back a request for SPNEGO authentication

                        restartAuthProcess(session, req, res, AUTH_SPNEGO);
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (logger.isDebugEnabled())
                        logger.debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartAuthProcess(session, req, res, AUTH_SPNEGO);
                }
            } catch (IOException ex) {
                // Log the error

                if (logger.isDebugEnabled())
                    logger.debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (logger.isDebugEnabled())
                logger.debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
        }
    }
    // NTLM authentication
    else if (authHdr.startsWith(AUTH_NTLM)) {
        if (debug)
            logger.debug("Processing NTLM authentication.");
        // Decode the received NTLM blob and validate
        final byte[] authHdrByts = authHdr.substring(5).getBytes();
        final byte[] ntlmByts = Base64.decode(authHdrByts);
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        Object sessionMutex = WebUtils.getSessionMutex(session);

        if (ntlmTyp == NTLM.Type1) {
            if (debug)
                logger.debug("Process the type 1 NTLM message.");
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, req, res, session);
            }
        } else if (ntlmTyp == NTLM.Type3) {
            if (debug)
                logger.debug("Process the type 3 NTLM message.");
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType3(type3Msg, req, res, session, chain);
            }
        } else {
            if (debug)
                logger.debug("NTLM not handled, redirecting to login page");

            redirectToLoginPage(req, res);
        }
    }
    // Possibly basic auth - allow through
    else {
        if (debug)
            logger.debug("Processing Basic Authentication.");
        // ACE-3257 fix, it looks like basic auth header was sent.
        // However lets check for presence of remote_user CGI variable in AJP.
        // If remote user is not null then it most likely that apache proxy with mod_auth_basic module is used
        if (AuthenticationUtil.isAuthenticated(req) || req.getRemoteUser() != null) {
            if (debug)
                logger.debug("Ensuring the session is still valid.");
            challengeOrPassThrough(chain, req, res, session);
        } else {
            if (debug)
                logger.debug("Establish a new session or bring up the login page.");
            chain.doFilter(req, res);
        }
    }
}

From source file:org.ecocean.servlet.EncounterAddImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.setAction("EncounterAddImage.class");

    //setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
    if (!shepherdDataDir.exists()) {
        shepherdDataDir.mkdirs();/*from  w  w  w.  ja v  a  2  s  .c  om*/
    }
    File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
    if (!encountersDir.exists()) {
        encountersDir.mkdirs();
    }

    //set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;

    String fileName = "None";
    String encounterNumber = "None";
    String fullPathFilename = "";

    try {
        MultipartParser mp = new MultipartParser(request,
                (CommonConfiguration.getMaxMediaSizeInMegabytes(context) * 1048576));
        Part part;
        while ((part = mp.readNextPart()) != null) {
            String name = part.getName();
            if (part.isParam()) {

                // it's a parameter part
                ParamPart paramPart = (ParamPart) part;
                String value = paramPart.getStringValue();

                //determine which variable to assign the param to
                if (name.equals("number")) {
                    encounterNumber = value;
                }

            }

            ////TODO this will need to be generified for offsite storage prob via SinglePhotoVideo? as in EncounterForm?
            if (part.isFile()) {
                FilePart filePart = (FilePart) part;
                fileName = ServletUtilities.cleanFileName(filePart.getFileName());
                if (fileName != null) {
                    //fileName = Util.generateUUID() + "-orig." + FilenameUtils.getExtension(fileName);
                    //File thisSharkDir = new File(encountersDir.getAbsolutePath() +"/"+ Encounter.subdir(encounterNumber));
                    File thisSharkDir = new File(Encounter.dir(shepherdDataDir, encounterNumber));
                    if (!thisSharkDir.exists()) {
                        thisSharkDir.mkdirs();
                    }
                    File finalFile = new File(thisSharkDir, fileName);
                    fullPathFilename = finalFile.getCanonicalPath();
                    long file_size = filePart.writeTo(finalFile);

                }
            }
        }

        //File thisEncounterDir = new File(encountersDir, Encounter.subdir(encounterNumber));
        File thisEncounterDir = new File(Encounter.dir(shepherdDataDir, encounterNumber));

        myShepherd.beginDBTransaction();
        if (myShepherd.isEncounter(encounterNumber)) {

            int positionInList = 10000;

            Encounter enc = myShepherd.getEncounter(encounterNumber);
            try {

                SinglePhotoVideo newSPV = new SinglePhotoVideo(encounterNumber, (new File(fullPathFilename)));
                enc.addSinglePhotoVideo(newSPV);
                ///// NOT YET -->  enc.refreshAssetFormats(myShepherd);
                //enc.refreshAssetFormats(context, ServletUtilities.dataDir(context, rootWebappPath), newSPV, false);
                enc.addComments("<p><em>" + request.getRemoteUser() + " on " + (new java.util.Date()).toString()
                        + "</em><br>" + "Submitted new encounter image graphic: " + fileName + ".</p>");
                positionInList = enc.getAdditionalImageNames().size();
            } catch (Exception le) {
                locked = true;
                myShepherd.rollbackDBTransaction();
                myShepherd.closeDBTransaction();
            }

            if (!locked) {
                myShepherd.commitDBTransaction();
                myShepherd.closeDBTransaction();
                out.println(ServletUtilities.getHeader(request));
                out.println(
                        "<strong>Success!</strong> I have successfully uploaded your new encounter image file.");
                if (positionInList == 1) {
                    out.println(
                            "<p><i>You should also reset the thumbnail image for this encounter. You can do so by <a href=\"http://"
                                    + CommonConfiguration.getURLLocation(request)
                                    + "/resetThumbnail.jsp?number=" + encounterNumber
                                    + "\">clicking here.</a></i></p>");
                }
                out.println("<p><a href=\"http://" + CommonConfiguration.getURLLocation(request)
                        + "/encounters/encounter.jsp?number=" + encounterNumber + "\">Return to encounter "
                        + encounterNumber + "</a></p>\n");
                out.println(ServletUtilities.getFooter(context));
                String message = "An additional image file has been uploaded for encounter #" + encounterNumber
                        + ".";
                ServletUtilities.informInterestedParties(request, encounterNumber, message, context);
            } else {

                out.println(ServletUtilities.getHeader(request));
                out.println(
                        "<strong>Failure!</strong> This encounter is currently being modified by another user. Please wait a few seconds before trying to add this image again.");
                out.println("<p><a href=\"http://" + CommonConfiguration.getURLLocation(request)
                        + "/encounters/encounter.jsp?number=" + encounterNumber + "\">Return to encounter "
                        + encounterNumber + "</a></p>\n");
                out.println(ServletUtilities.getFooter(context));

            }
        } else {
            myShepherd.rollbackDBTransaction();
            myShepherd.closeDBTransaction();
            out.println(ServletUtilities.getHeader(request));
            out.println(
                    "<strong>Error:</strong> I was unable to upload your image file. I cannot find the encounter that you intended it for in the database.");
            out.println(ServletUtilities.getFooter(context));

        }
    } catch (IOException lEx) {
        lEx.printStackTrace();
        out.println(ServletUtilities.getHeader(request));
        out.println(
                "<strong>Error:</strong> I was unable to upload your image file. Please contact the web master about this message.");
        out.println(ServletUtilities.getFooter(context));
    } catch (NullPointerException npe) {
        npe.printStackTrace();
        out.println(ServletUtilities.getHeader(request));
        out.println("<strong>Error:</strong> I was unable to upload an image as no file was specified.");
        out.println(ServletUtilities.getFooter(context));
    }
    out.close();
}

From source file:org.dspace.authenticate.ShibAuthentication.java

/**
 * Identify an existing EPerson based upon the shibboleth attributes provided on
 * the request object. There are three cases where this can occurr, each as
 * a fallback for the previous method./*from  w  w  w .j  a va2s  .co  m*/
 * 
 * 1) NetID from Shibboleth Header (best)
 *    The NetID-based method is superior because users may change their email
 *    address with the identity provider. When this happens DSpace will not be 
 *    able to associate their new address with their old account.
 * 
 * 2) Email address from Shibboleth Header (okay)
 *    In the case where a NetID header is not available or not found DSpace
 *    will fall back to identifying a user based upon their email address. 
 *    
 * 3) Tomcat's Remote User (worst)
 *    In the event that neither Shibboleth headers are found then as a last
 *    resort DSpace will look at Tomcat's remote user field. This is the least
 *    attractive option because Tomcat has no way to supply additional 
 *    attributes about a user. Because of this the autoregister option is not
 *    supported if this method is used.
 *    
 * If successful then the identified EPerson will be returned, otherwise null.
 * 
 * @param context The DSpace database context
 * @param request The current HTTP Request
 * @return The EPerson identified or null.
 * @throws SQLException if database error
 * @throws AuthorizeException if authorization error
 */
protected EPerson findEPerson(Context context, HttpServletRequest request)
        throws SQLException, AuthorizeException {

    boolean isUsingTomcatUser = configurationService
            .getBooleanProperty("authentication-shibboleth.email-use-tomcat-remote-user");
    String netidHeader = configurationService.getProperty("authentication-shibboleth.netid-header");
    String emailHeader = configurationService.getProperty("authentication-shibboleth.email-header");

    EPerson eperson = null;
    boolean foundNetID = false;
    boolean foundEmail = false;
    boolean foundRemoteUser = false;

    // 1) First, look for a netid header.
    if (netidHeader != null) {
        String netid = findSingleAttribute(request, netidHeader);

        if (netid != null) {
            foundNetID = true;
            eperson = ePersonService.findByNetid(context, netid);

            if (eperson == null)
                log.info("Unable to identify EPerson based upon Shibboleth netid header: '" + netidHeader
                        + "'='" + netid + "'.");
            else
                log.debug("Identified EPerson based upon Shibboleth netid header: '" + netidHeader + "'='"
                        + netid + "'.");
        }
    }

    // 2) Second, look for an email header.
    if (eperson == null && emailHeader != null) {
        String email = findSingleAttribute(request, emailHeader);

        if (email != null) {
            foundEmail = true;
            email = email.toLowerCase();
            eperson = ePersonService.findByEmail(context, email);

            if (eperson == null)
                log.info("Unable to identify EPerson based upon Shibboleth email header: '" + emailHeader
                        + "'='" + email + "'.");
            else
                log.info("Identified EPerson based upon Shibboleth email header: '" + emailHeader + "'='"
                        + email + "'.");

            if (eperson != null && eperson.getNetid() != null) {
                // If the user has a netID it has been locked to that netid, don't let anyone else try and steal the account.
                log.error("The identified EPerson based upon Shibboleth email header, '" + emailHeader + "'='"
                        + email + "', is locked to another netid: '" + eperson.getNetid()
                        + "'. This might be a possible hacking attempt to steal another users credentials. If the user's netid has changed you will need to manually change it to the correct value or unset it in the database.");
                eperson = null;
            }
        }
    }

    // 3) Last, check to see if tomcat is passing a user.
    if (eperson == null && isUsingTomcatUser) {
        String email = request.getRemoteUser();

        if (email != null) {
            foundRemoteUser = true;
            email = email.toLowerCase();
            eperson = ePersonService.findByEmail(context, email);

            if (eperson == null)
                log.info("Unable to identify EPerson based upon Tomcat's remote user: '" + email + "'.");
            else
                log.info("Identified EPerson based upon Tomcat's remote user: '" + email + "'.");

            if (eperson != null && eperson.getNetid() != null) {
                // If the user has a netID it has been locked to that netid, don't let anyone else try and steal the account.
                log.error("The identified EPerson based upon Tomcat's remote user, '" + email
                        + "', is locked to another netid: '" + eperson.getNetid()
                        + "'. This might be a possible hacking attempt to steal another users credentials. If the user's netid has changed you will need to manually change it to the correct value or unset it in the database.");
                eperson = null;
            }
        }
    }

    if (!foundNetID && !foundEmail && !foundRemoteUser) {
        log.error(
                "Shibboleth authentication was not able to find a NetId, Email, or Tomcat Remote user for which to indentify a user from.");
    }

    return eperson;
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  Serves a GET with two parameters: 'wikiname' specifying the wikiname
 *  of the attachment, 'version' specifying the version indicator.
 *  //w  ww  .j  a v a2  s.co m
 *  {@inheritDoc}
 */

// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");

    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;

    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();

    String page = context.getPage().getName();

    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    OutputStream out = null;
    InputStream in = null;

    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }

        Attachment att = mgr.getAttachmentInfo(page, ver);

        if (att != null) {
            //
            //  Check if the user has permission for this attachment
            //

            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //
            //  Check if the client already has a version of this attachment.
            //
            if (HttpUtil.checkFor304(req, att)) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }

            String mimetype = getMimeType(context, att.getFileName());

            res.setContentType(mimetype);

            //
            //  We use 'inline' instead of 'attachment' so that user agents
            //  can try to automatically open the file.
            //

            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");

            res.addDateHeader("Last-Modified", att.getLastModified().getTime());

            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }

            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                // log.info("size:"+att.getSize());
                res.setContentLength((int) att.getSize());
            }

            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);

            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }

            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                        + req.getRemoteAddr();
                log.debug(msg);
            }
            if (nextPage != null)
                res.sendRedirect(nextPage);

            return;
        }

        msg = "Attachment '" + page + "', version " + ver + " does not exist.";

        log.info(msg);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();

        log.debug("Provider failed while reading", pe);
        //
        //  This might fail, if the response is already committed.  So in that
        //  case we just log it.
        //
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } catch (NumberFormatException nfe) {
        msg = "Invalid version number (" + version + ")";
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (SocketException se) {
        //
        //  These are very common in download situations due to aggressive
        //  clients.  No need to try and send an error.
        //
        log.debug("I/O exception during download", se);
        return;
    } catch (IOException ioe) {
        //
        //  Client dropped the connection or something else happened.
        //  We don't know where the error came from, so we'll at least
        //  try to send an error and catch it quietly if it doesn't quite work.
        //
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);

        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        //
        //  Quite often, aggressive clients close the connection when they have
        //  received the last bits.  Therefore, we close the output, but ignore
        //  any exception that might come out of it.
        //

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void removeField(HttpServletRequest request, Connection conn, BaseField field) throws SQLException,
        DisallowedException, CantDoThatException, CodingErrorException, ObjectNotFoundException {
    TableInfo table = field.getTableContainingField();
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            table))) {/*w ww.  j a v  a 2s  .  co  m*/
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                table);
    }
    this.removeFieldChecks(field, request);
    this.removeFieldWithoutChecks(request, conn, field, table);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logTableSchemaChange(user, table, AppAction.REMOVE_FIELD, "field: " + field);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java

/**
 * Serves a GET with two parameters: 'wikiname' specifying the wikiname of the attachment,
 * 'version' specifying the version indicator. {@inheritDoc}
 *//*w  w w .  ja v  a2 s  .  c o m*/
// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");

    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;

    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();

    String page = context.getPage().getName();

    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    OutputStream out = null;
    InputStream in = null;

    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }

        Attachment att = mgr.getAttachmentInfo(page, ver);

        if (att != null) {
            //
            // Check if the user has permission for this attachment
            //

            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //
            // Check if the client already has a version of this attachment.
            //
            if (HttpUtil.checkFor304(req, att)) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }

            String mimetype = getMimeType(context, att.getFileName());

            res.setContentType(mimetype);

            //
            // We use 'inline' instead of 'attachment' so that user agents
            // can try to automatically open the file.
            //

            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");

            res.addDateHeader("Last-Modified", att.getLastModified().getTime());

            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }

            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                res.setContentLength((int) att.getSize());
            }

            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);
            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }
            System.out.println("Attachment file is c:/tmp/result/" + att.getFileName());
            System.out.println("Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                    + req.getRemoteAddr());
            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                        + req.getRemoteAddr();
                log.debug(msg);
            }
            if (nextPage != null) {
                res.sendRedirect(nextPage);
            }

            return;
        }

        msg = "Attachment '" + page + "', version " + ver + " does not exist.";

        log.info(msg);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();

        log.debug("Provider failed while reading", pe);
        //
        // This might fail, if the response is already committed. So in that
        // case we just log it.
        //
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } catch (NumberFormatException nfe) {
        msg = "Invalid version number (" + version + ")";
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (SocketException se) {
        //
        // These are very common in download situations due to aggressive
        // clients. No need to try and send an error.
        //
        log.debug("I/O exception during download", se);
        return;
    } catch (IOException ioe) {
        //
        // Client dropped the connection or something else happened.
        // We don't know where the error came from, so we'll at least
        // try to send an error and catch it quietly if it doesn't quite work.
        //
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);

        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        //
        // Quite often, aggressive clients close the connection when they have
        // received the last bits. Therefore, we close the output, but ignore
        // any exception that might come out of it.
        //

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void addDistinctToReport(HttpServletRequest request, Connection conn, SimpleReportInfo report,
        BaseField distinctField) throws DisallowedException, ObjectNotFoundException, CantDoThatException,
        CodingErrorException, SQLException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }//ww  w . j  av a2 s  .  c  o m
    HibernateUtil.activateObject(report);
    report.addDistinctField(distinctField);
    this.updateViewDbAction(conn, report, request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.ADD_REPORT_DISTINCT, "field: " + distinctField);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void removeDistinctFromReport(HttpServletRequest request, Connection conn, SimpleReportInfo report,
        BaseField distinctField) throws DisallowedException, ObjectNotFoundException, CantDoThatException,
        CodingErrorException, SQLException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }/*  w  ww  .  j  av a2s .com*/
    HibernateUtil.activateObject(report);
    report.removeDistinctField(distinctField);
    this.updateViewDbAction(conn, report, request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.REMOVE_REPORT_DISTINCT,
            "field: " + distinctField);
    UsageLogger.startLoggingThread(usageLogger);
}