001/* 002 * Copyright 2017 Anyware Services 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.ametys.plugins.site.population; 017 018import java.util.HashSet; 019import java.util.Set; 020 021import org.apache.avalon.framework.service.ServiceException; 022 023import org.ametys.core.user.population.PopulationContextHelper; 024import org.ametys.core.user.population.UserPopulation; 025import org.ametys.plugins.site.Site; 026import org.ametys.plugins.site.SiteInformationCache; 027 028/** 029 * Helper for associating {@link UserPopulation}s to contexts for FO application. 030 * Overrides {@link PopulationContextHelper#getUserPopulationsOnContext(String, boolean)} in order to authenticate through Front-Office URLs 031 */ 032public class SitePopulationContextHelper extends PopulationContextHelper 033{ 034 private static final String __SITES_PREFIX_CONTEXT = "/sites/"; 035 private static final String __SITES_FO_PREFIX_CONTEXT = "/sites-fo/"; 036 037 private SiteInformationCache _siteInformationCache; 038 039 private void _delayedService() 040 { 041 if (_siteInformationCache == null) 042 { 043 try 044 { 045 _siteInformationCache = (SiteInformationCache) _manager.lookup(SiteInformationCache.ROLE); 046 } 047 catch (ServiceException e) 048 { 049 // do nothing, we are in safe mode 050 } 051 } 052 } 053 054 @Override 055 public Set<String> getUserPopulationsOnContext(String context, boolean withDisabled) 056 { 057 if (context.startsWith(__SITES_PREFIX_CONTEXT)) 058 { 059 String siteName = context.substring(__SITES_PREFIX_CONTEXT.length()); 060 Site site = _findSite(siteName); 061 if (site != null) 062 { 063 return new HashSet<>(site.getPopulationIds()); 064 } 065 } 066 else if (context.startsWith(__SITES_FO_PREFIX_CONTEXT)) 067 { 068 String siteName = context.substring(__SITES_FO_PREFIX_CONTEXT.length()); 069 Site site = _findSite(siteName); 070 if (site != null) 071 { 072 return new HashSet<>(site.getPopulationIds()); 073 } 074 } 075 076 return super.getUserPopulationsOnContext(context, withDisabled); 077 } 078 079 private Site _findSite(String siteName) 080 { 081 _delayedService(); 082 083 if (_siteInformationCache != null) 084 { 085 for (Site site : _siteInformationCache.getSites().values()) 086 { 087 if (site.getName().equals(siteName)) 088 { 089 return site; 090 } 091 } 092 } 093 094 return null; 095 } 096}