001/**
002 * Copyright 2015 DuraSpace, Inc.
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 */
016package org.fcrepo.http.commons.session;
017
018import static com.google.common.base.Preconditions.checkNotNull;
019import static javax.ws.rs.core.Response.Status.GONE;
020import static org.slf4j.LoggerFactory.getLogger;
021
022import java.security.Principal;
023
024import javax.annotation.PostConstruct;
025import javax.jcr.Repository;
026import javax.jcr.RepositoryException;
027import javax.jcr.Session;
028import javax.servlet.http.HttpServletRequest;
029import javax.ws.rs.BadRequestException;
030import javax.ws.rs.ClientErrorException;
031
032import org.fcrepo.kernel.exception.RepositoryRuntimeException;
033import org.fcrepo.kernel.exception.TransactionMissingException;
034import org.fcrepo.kernel.Transaction;
035import org.fcrepo.kernel.services.TransactionService;
036import org.modeshape.jcr.api.ServletCredentials;
037import org.slf4j.Logger;
038import org.springframework.beans.factory.annotation.Autowired;
039
040/**
041 * Factory for generating sessions for HTTP requests, taking
042 * into account transactions and authentication.
043 *
044 * @author awoods
045 * @author gregjan
046 * @author kaisternad
047 */
048public class SessionFactory {
049
050    protected static enum Prefix{
051        TX("tx:");
052
053        private final String prefix;
054
055        Prefix(final String prefix) {
056            this.prefix = prefix;
057        }
058
059        public String getPrefix() {
060            return prefix;
061        }
062    }
063
064    private static final Logger LOGGER = getLogger(SessionFactory.class);
065
066    @Autowired
067    private Repository repo;
068
069    @Autowired
070    private TransactionService transactionService;
071
072    /**
073     * initialize an empty session factory
074     */
075    public SessionFactory() {
076
077    }
078
079    /**
080     * Initialize a session factory for the given Repository
081     *
082     * @param repo
083     * @param transactionService
084     */
085    public SessionFactory(final Repository repo,
086            final TransactionService transactionService) {
087        this.repo = repo;
088        this.transactionService = transactionService;
089    }
090
091    /**
092     * Validate the spring wiring
093     */
094    @PostConstruct
095    public void init() {
096        checkNotNull(repo, "SessionFactory requires a Repository instance!");
097    }
098
099    /**
100     * Get a new JCR Session
101     *
102     * @return an internal session
103     * @throws RepositoryException
104     */
105    public Session getInternalSession() {
106        try {
107            return repo.login();
108        } catch (final RepositoryException e) {
109            throw new RepositoryRuntimeException(e);
110        }
111    }
112
113    /**
114     * Get a JCR session for the given HTTP servlet request with a
115     * SecurityContext attached
116     *
117     * @param servletRequest
118     * @return the Session
119     * @throws RuntimeException if the transaction could not be found
120     */
121    public Session getSession(final HttpServletRequest servletRequest) {
122        final Session session;
123        final String txId = getEmbeddedId(servletRequest, Prefix.TX);
124
125        try {
126            if (txId == null) {
127                session = createSession(servletRequest);
128            } else {
129                session = getSessionFromTransaction(servletRequest, txId);
130            }
131        } catch (final TransactionMissingException e) {
132            throw new ClientErrorException(GONE, e);
133        } catch (final RepositoryException e) {
134            throw new BadRequestException(e);
135        }
136
137        return session;
138    }
139
140    /**
141     * Create a JCR session for the given HTTP servlet request with a
142     * SecurityContext attached.
143     *
144     * @param servletRequest
145     * @return a newly created JCR session
146     * @throws RepositoryException if the session could not be created
147     */
148    protected Session createSession(final HttpServletRequest servletRequest) throws RepositoryException {
149
150        final ServletCredentials creds =
151                new ServletCredentials(servletRequest);
152
153        LOGGER.debug("Returning an authenticated session in the default workspace");
154        return  repo.login(creds);
155    }
156
157    /**
158     * Retrieve a JCR session from an active transaction
159     *
160     * @param servletRequest
161     * @return a JCR session that is associated with the transaction
162     */
163    protected Session getSessionFromTransaction(final HttpServletRequest servletRequest, final String txId) {
164
165        final Principal userPrincipal = servletRequest.getUserPrincipal();
166
167        String userName = null;
168        if (userPrincipal != null) {
169            userName = userPrincipal.getName();
170        }
171
172        final Transaction transaction =
173                transactionService.getTransaction(txId, userName);
174        LOGGER.debug(
175                "Returning a session in the transaction {} for user {}",
176                transaction, userName);
177        return transaction.getSession();
178
179    }
180
181    /**
182     * Extract the id embedded at the beginning of a request path
183     *
184     * @param servletRequest
185     * @param prefix the prefix for the id
186     * @return the found id or null
187     */
188    protected String getEmbeddedId(
189            final HttpServletRequest servletRequest, final Prefix prefix) {
190        String requestPath = servletRequest.getPathInfo();
191
192        // http://stackoverflow.com/questions/18963562/grizzlys-request-getpathinfo-returns-always-null
193        if (requestPath == null && servletRequest.getContextPath().isEmpty()) {
194            requestPath = servletRequest.getRequestURI();
195        }
196
197        String id = null;
198        if (requestPath != null) {
199            final String pathPrefix = prefix.getPrefix();
200            final String[] part = requestPath.split("/");
201            if (part.length > 1 && part[1].startsWith(pathPrefix)) {
202                id = part[1].substring(pathPrefix.length());
203            }
204        }
205        return id;
206    }
207
208}