001package ca.uhn.fhir.rest.server.tenant;
002
003/*-
004 * #%L
005 * HAPI FHIR - Server Framework
006 * %%
007 * Copyright (C) 2014 - 2019 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.i18n.HapiLocalizer;
024import ca.uhn.fhir.rest.api.server.RequestDetails;
025import ca.uhn.fhir.rest.server.RestfulServer;
026import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
027import ca.uhn.fhir.util.UrlPathTokenizer;
028import org.apache.commons.lang3.Validate;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031
032import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
033
034/**
035 * This class is a tenant identification strategy which assumes that a single path
036 * element will be present between the server base URL and the beginning
037 */
038public class UrlBaseTenantIdentificationStrategy implements ITenantIdentificationStrategy {
039
040        private static final Logger ourLog = LoggerFactory.getLogger(UrlBaseTenantIdentificationStrategy.class);
041
042        @Override
043        public void extractTenant(UrlPathTokenizer theUrlPathTokenizer, RequestDetails theRequestDetails) {
044                String tenantId = null;
045                if (theUrlPathTokenizer.hasMoreTokens()) {
046                        tenantId = defaultIfBlank(theUrlPathTokenizer.nextTokenUnescapedAndSanitized(), null);
047                        ourLog.trace("Found tenant ID {} in request string", tenantId);
048                        theRequestDetails.setTenantId(tenantId);
049                }
050
051                if (tenantId == null) {
052                        HapiLocalizer localizer = theRequestDetails.getServer().getFhirContext().getLocalizer();
053                        throw new InvalidRequestException(localizer.getMessage(RestfulServer.class, "rootRequest.multitenant"));
054                }
055        }
056
057        @Override
058        public String massageServerBaseUrl(String theFhirServerBase, RequestDetails theRequestDetails) {
059                Validate.notNull(theRequestDetails.getTenantId(), "theTenantId is not populated on this request");
060                return theFhirServerBase + '/' + theRequestDetails.getTenantId();
061        }
062
063}