View Javadoc

1   /**
2    * This file Copyright (c) 2011-2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.setup.for4_5;
35  
36  import static java.lang.String.format;
37  import static org.apache.commons.lang.ArrayUtils.contains;
38  import info.magnolia.cms.core.Content;
39  import info.magnolia.cms.core.HierarchyManager;
40  import info.magnolia.cms.core.NodeData;
41  import info.magnolia.cms.filters.FilterManager;
42  import info.magnolia.cms.util.ContentUtil;
43  import info.magnolia.jcr.util.NodeTypes;
44  import info.magnolia.module.InstallContext;
45  import info.magnolia.module.delta.AbstractRepositoryTask;
46  import info.magnolia.module.delta.TaskExecutionException;
47  
48  import java.util.Collection;
49  import java.util.Set;
50  
51  import javax.jcr.RepositoryException;
52  
53  import org.apache.commons.lang.ArrayUtils;
54  import org.apache.commons.lang.StringUtils;
55  import org.slf4j.Logger;
56  import org.slf4j.LoggerFactory;
57  
58  import com.google.common.base.Function;
59  import com.google.common.base.Predicates;
60  import com.google.common.collect.Iterables;
61  import com.google.common.collect.Sets;
62  
63  /**
64   * Updates the given security filter's client callback configuration to reflect the changes introduced in 4.5.
65   */
66  public class UpdateSecurityFilterClientCallbacksConfiguration extends AbstractRepositoryTask {
67  
68      private static final Logger log = LoggerFactory.getLogger(UpdateSecurityFilterClientCallbacksConfiguration.class);
69  
70      private static final String FORM_CLASS = "info.magnolia.cms.security.auth.callback.FormClientCallback";
71      private static final String COMPOSITE_CLASS = "info.magnolia.cms.security.auth.callback.CompositeCallback";
72      private static final String BASIC_CLASS = "info.magnolia.cms.security.auth.callback.BasicClientCallback";
73      private static final String REDIRECT_CLASS = "info.magnolia.cms.security.auth.callback.RedirectClientCallback";
74      private static final String[] SIMPLE_CALLBACK_CLASSES = new String[]{FORM_CLASS, BASIC_CLASS, REDIRECT_CLASS};
75      private final String fromFilterName;
76      private final String targetFilterName;
77      private boolean wereWeAbleToUpdateEverything = true;
78  
79      public UpdateSecurityFilterClientCallbacksConfiguration(String fromFilterName, String targetFilterName) {
80          super("Security filter configuration", "Moves the client callback configuration from the " + fromFilterName + " to the new " + targetFilterName + " filter to enable multiple client callbacks.");
81          this.fromFilterName = fromFilterName;
82          this.targetFilterName = targetFilterName;
83      }
84  
85      @Override
86      protected void doExecute(InstallContext ctx) throws RepositoryException, TaskExecutionException {
87          final HierarchyManager hm = ctx.getConfigHierarchyManager();
88          final Content fromFilterNode = hm.getContent(FilterManager.SERVER_FILTERS + "/" + fromFilterName);
89          final Content targetFilterNode = hm.getContent(FilterManager.SERVER_FILTERS + "/" + targetFilterName);
90  
91          final Content newCallbacksNode = targetFilterNode.createContent("clientCallbacks", NodeTypes.ContentNode.NAME);
92          final Content currentCallbackNode = fromFilterNode.getContent("clientCallback");
93          final String currentClass = currentCallbackNode.getNodeData("class").getString();
94          if (contains(SIMPLE_CALLBACK_CLASSES, currentClass)) {
95              addCallback(ctx, newCallbacksNode, null, currentCallbackNode, null);
96          } else if (!currentCallbackNode.hasChildren()) {
97              // we can assume it's a simple custom callback which we can simply move
98              addCallback(ctx, newCallbacksNode, "custom", currentCallbackNode, null);
99          } else if (COMPOSITE_CLASS.equals(currentClass)) {
100             final Collection<Content> existingCallbacks = currentCallbackNode.getContent("patterns").getChildren();
101             for (Content existingCallback : existingCallbacks) {
102                 final String clazz = existingCallback.getNodeData("class").getString();
103                 if ("info.magnolia.cms.util.UrlPatternDelegate".equals(clazz)) {
104                     final String url = existingCallback.getNodeData("url").getString();
105                     addCallback(ctx, newCallbacksNode, existingCallback.getName(), existingCallback.getContent("delegate"), url);
106                 } else {
107                     ctx.warn("Unknown callback class at " + existingCallback.getHandle() + ":" + clazz);
108                     wereWeAbleToUpdateEverything = false;
109                 }
110             }
111         } else {
112             ctx.warn("Unknown callback class:" + currentClass);
113             wereWeAbleToUpdateEverything = false;
114         }
115 
116         // only rename if unsuccessful ?
117         if (wereWeAbleToUpdateEverything) {
118             currentCallbackNode.delete();
119         } else {
120             ContentUtil.moveInSession(currentCallbackNode, fromFilterNode.getHandle() + "/_clientCallback_backup_config");
121             ctx.warn(format(
122                             "Client callback configuration for %s was not standard: an untouched copy of %s has been kept at %s. Please check, validate and correct the new configuration at %s.",
123                             fromFilterName, fromFilterNode.getHandle() + "/clientCallback", fromFilterNode.getHandle() + "/_clientCallback_backup_config", newCallbacksNode.getHandle()
124                     ));
125 
126         }
127     }
128 
129     private void addCallback(InstallContext ctx, Content target, String givenCallbackName, Content source, String urlPattern) throws RepositoryException {
130         final String clazz = source.getNodeData("class").getString();
131         final String newName;
132         if (givenCallbackName == null && contains(SIMPLE_CALLBACK_CLASSES, clazz)) {
133             newName = simplifyClassName(clazz);
134         } else if (givenCallbackName != null) {
135             newName = givenCallbackName;
136         } else {
137             log.warn("Can not determine name for callback at " + source.getHandle());
138             wereWeAbleToUpdateEverything = false;
139             return;
140         }
141 
142         final Content newCallback = target.createContent(newName, NodeTypes.ContentNode.NAME);
143         copyStringProperty(source, newCallback, "class");
144         if (FORM_CLASS.equals(clazz)) {
145             copyStringProperty(source, newCallback, "loginForm");
146             logAndIgnore(ctx, source, "realmName");
147             checkRemainingProperties(ctx, source, "class", "loginForm", "realmName");
148         } else if (REDIRECT_CLASS.equals(clazz)) {
149             copyStringProperty(source, newCallback, "location");
150             logAndIgnore(ctx, source, "realmName");
151             checkRemainingProperties(ctx, source, "class", "location", "realmName");
152         } else if (BASIC_CLASS.equals(clazz)) {
153             copyStringProperty(source, newCallback, "realmName");
154             checkRemainingProperties(ctx, source, "class", "realmName");
155         } else {
156             log.warn("Unknown callback class: " + clazz + "; copying all properties.");
157             wereWeAbleToUpdateEverything = false;
158             copyRemainingProperties(ctx, source, newCallback, "class");
159         }
160 
161         if (urlPattern != null) {
162             Content urlPatternContent = newCallback.createContent("urlPattern", NodeTypes.ContentNode.NAME);
163             urlPatternContent.setNodeData("class", "info.magnolia.cms.util.SimpleUrlPattern");
164             urlPatternContent.setNodeData("patternString", urlPattern);
165         }
166 
167     }
168 
169     private String simplifyClassName(String clazz) {
170         return StringUtils.removeEnd(StringUtils.substringAfterLast(clazz, "."), "ClientCallback").toLowerCase();
171     }
172 
173     private void copyStringProperty(Content source, Content target, String propertyName) throws RepositoryException {
174         target.setNodeData(propertyName, source.getNodeData(propertyName).getString());
175     }
176 
177     /**
178      * Checks if the given node has a given property; logs it and continues if so.
179      */
180     private void logAndIgnore(InstallContext ctx, Content source, String propertyName) throws RepositoryException {
181         if (source.hasNodeData(propertyName)) {
182             ctx.warn(source.getHandle() + " has a '" + propertyName + "' property; it is ignored and has been removed.");
183         }
184     }
185 
186     /**
187      * Checks if the given node has other properties than those specified by the ignoredProperties parameter.
188      */
189     private void checkRemainingProperties(InstallContext ctx, Content source, String... ignoredProperties) {
190         final Set<String> ignoredPropsSet = Sets.newHashSet(ignoredProperties);
191         final Collection<NodeData> allProps = source.getNodeDataCollection();
192         final Iterable<String> allPropsNames = Iterables.transform(allProps, new Function<NodeData, String>() {
193             @Override
194             public String apply(NodeData from) {
195                 return from.getName();
196             }
197         });
198         final Iterable<String> remaining = Iterables.filter(allPropsNames, Predicates.not(Predicates.in(ignoredPropsSet)));
199         if (!Iterables.isEmpty(remaining)) {
200             log.warn(source.getHandle() + " has the following unknown properties which were not copied: " + remaining);
201             wereWeAbleToUpdateEverything = false;
202         }
203     }
204 
205     private void copyRemainingProperties(InstallContext ctx, Content source, Content target, String... ignoredProperties) throws RepositoryException {
206         final Collection<NodeData> existingProps = source.getNodeDataCollection();
207         for (NodeData prop : existingProps) {
208             if (ArrayUtils.contains(ignoredProperties, prop.getName())) {
209                 continue;
210             }
211             copyStringProperty(source, target, prop.getName());
212         }
213     }
214 
215 }