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.workspaces.odf; 017 018import java.util.Collection; 019import java.util.Map; 020 021import org.apache.avalon.framework.parameters.Parameters; 022import org.apache.cocoon.acting.AbstractAction; 023import org.apache.cocoon.environment.ObjectModelHelper; 024import org.apache.cocoon.environment.Redirector; 025import org.apache.cocoon.environment.Request; 026import org.apache.cocoon.environment.SourceResolver; 027 028import org.ametys.core.util.StringUtils; 029import org.ametys.runtime.authentication.AccessDeniedException; 030import org.ametys.runtime.config.Config; 031 032/** 033 * Abstract class for ODF authentication by IP (useful for CDM-fr portals). 034 */ 035public abstract class AbstractODFAuthenticateAction extends AbstractAction 036{ 037 @Override 038 public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception 039 { 040 Request request = ObjectModelHelper.getRequest(objectModel); 041 authenticate(request); 042 return null; 043 } 044 045 /** 046 * Method to authenticate 047 * @param request The request 048 */ 049 protected void authenticate(Request request) 050 { 051 // Verify the IP address 052 String conf = Config.getInstance().getValue(getConfigParameter()); 053 Collection<String> ips = StringUtils.stringToCollection(conf); 054 055 // The real client IP may have been put in the non-standard 056 // "X-Forwarded-For" request header, in case of reverse proxy 057 String xff = request.getHeader("X-Forwarded-For"); 058 String ip = null; 059 060 if (xff != null) 061 { 062 ip = xff.split(",")[0]; 063 } 064 else 065 { 066 ip = request.getRemoteAddr(); 067 } 068 069 if (!ips.contains(ip)) 070 { 071 throw new AccessDeniedException(String.format(getExceptionMessage(), ip)); 072 } 073 } 074 075 /** 076 * Get the config parameter name contained the allowed IP adresses. 077 * @return The parameter name 078 */ 079 protected abstract String getConfigParameter(); 080 081 /** 082 * Get the exception message if the current IP is not allowed. 083 * @return The exception message 084 */ 085 protected abstract String getExceptionMessage(); 086} 087