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.CloseableCoreSession;
029import org.nuxeo.ecm.core.api.CoreInstance;
030import org.nuxeo.ecm.core.api.CoreSession;
031import org.nuxeo.ecm.core.api.IdRef;
032import org.nuxeo.ecm.webengine.jaxrs.context.RequestCleanupHandler;
033import org.nuxeo.ecm.webengine.jaxrs.context.RequestContext;
034import org.nuxeo.runtime.api.Framework;
035
036public abstract class EasyShareUnrestrictedRunner {
037
038    private static final Log log = LogFactory.getLog(EasyShareUnrestrictedRunner.class);
039
040    protected CoreSession session;
041
042    public Object runUnrestricted(String docId) {
043        final LoginContext lc;
044        try {
045            lc = Framework.login();
046        } catch (LoginException ex) {
047            log.error("Unable to render page", ex);
048            return null;
049        }
050        CloseableCoreSession coreSession = null;
051        try {
052            coreSession = CoreInstance.openCoreSession(null);
053
054            // Run unrestricted operation
055            IdRef docRef = new IdRef(docId);
056            return run(coreSession, docRef);
057
058        } finally {
059            final CloseableCoreSession session2close = coreSession;
060            RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() {
061
062                @Override
063                public void cleanup(HttpServletRequest req) {
064                    try {
065                        session2close.close();
066                        lc.logout();
067                    } catch (LoginException e) {
068                        log.error("Error during request context cleanup", e);
069                    }
070                }
071            });
072
073        }
074
075    }
076
077    public abstract Object run(CoreSession coreSession, IdRef docId);
078}