001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Michal Obrebski - Nuxeo
016 */
017
018package org.nuxeo.easyshare;
019
020import javax.security.auth.login.LoginContext;
021import javax.security.auth.login.LoginException;
022import javax.servlet.http.HttpServletRequest;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.ecm.core.api.CoreSession;
027import org.nuxeo.ecm.core.api.IdRef;
028import org.nuxeo.ecm.core.api.repository.Repository;
029import org.nuxeo.ecm.core.api.repository.RepositoryManager;
030import org.nuxeo.ecm.webengine.jaxrs.context.RequestCleanupHandler;
031import org.nuxeo.ecm.webengine.jaxrs.context.RequestContext;
032import org.nuxeo.runtime.api.Framework;
033
034public abstract class EasyShareUnrestrictedRunner {
035
036    private static final Log log = LogFactory.getLog(EasyShareUnrestrictedRunner.class);
037
038    protected CoreSession session;
039
040    public Object runUnrestricted(String docId) {
041        final LoginContext lc;
042        try {
043            lc = Framework.login();
044        } catch (LoginException ex) {
045            log.error("Unable to render page", ex);
046            return null;
047        }
048        CoreSession coreSession = null;
049        try {
050            RepositoryManager rm = Framework.getService(RepositoryManager.class);
051            coreSession = rm.getDefaultRepository().open();
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                        Repository.close(session2close);
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}