001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Michal Obrebski - Nuxeo
018 */
019
020package org.nuxeo.easyshare;
021
022import javax.security.auth.login.LoginContext;
023import javax.security.auth.login.LoginException;
024import javax.servlet.http.HttpServletRequest;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.ecm.core.api.CoreInstance;
029import org.nuxeo.ecm.core.api.CoreSession;
030import org.nuxeo.ecm.core.api.IdRef;
031import org.nuxeo.ecm.webengine.jaxrs.context.RequestCleanupHandler;
032import org.nuxeo.ecm.webengine.jaxrs.context.RequestContext;
033import org.nuxeo.runtime.api.Framework;
034
035public abstract class EasyShareUnrestrictedRunner {
036
037    private static final Log log = LogFactory.getLog(EasyShareUnrestrictedRunner.class);
038
039    protected CoreSession session;
040
041    public Object runUnrestricted(String docId) {
042        final LoginContext lc;
043        try {
044            lc = Framework.login();
045        } catch (LoginException ex) {
046            log.error("Unable to render page", ex);
047            return null;
048        }
049        CoreSession coreSession = null;
050        try {
051            coreSession = CoreInstance.openCoreSession(null);
052
053            // Run unrestricted operation
054            IdRef docRef = new IdRef(docId);
055            return run(coreSession, docRef);
056
057        } finally {
058            final CoreSession session2close = coreSession;
059            RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() {
060
061                @Override
062                public void cleanup(HttpServletRequest req) {
063                    try {
064                        session2close.close();
065                        lc.logout();
066                    } catch (LoginException e) {
067                        log.error("Error during request context cleanup", e);
068                    }
069                }
070            });
071
072        }
073
074    }
075
076    public abstract Object run(CoreSession coreSession, IdRef docId);
077}