View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.lifecycle;
21  
22  import org.apache.myfaces.tobago.config.TobagoConfig;
23  import org.apache.myfaces.tobago.webapp.Secret;
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  
27  import javax.enterprise.inject.spi.CDI;
28  import javax.faces.context.FacesContext;
29  import javax.faces.event.PhaseEvent;
30  import javax.faces.event.PhaseId;
31  import javax.faces.event.PhaseListener;
32  import java.lang.invoke.MethodHandles;
33  import java.util.Map;
34  
35  public class SecretPhaseListener implements PhaseListener {
36  
37    private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
38  
39    @Override
40    public void afterPhase(final PhaseEvent event) {
41      final FacesContext facesContext = event.getFacesContext();
42      final TobagoConfig tobagoConfig = CDI.current().select(TobagoConfig.class).get();
43  
44      if (!facesContext.getResponseComplete()
45          && facesContext.isPostback()
46          && tobagoConfig.isCheckSessionSecret()
47          && !check(facesContext)) {
48        if (LOG.isDebugEnabled()) {
49          LOG.debug("Secret is invalid!");
50        }
51        facesContext.renderResponse(); // this ends the normal lifecycle
52      }
53    }
54  
55    /**
56     * Checks that the request contains a parameter {@link org.apache.myfaces.tobago.webapp.Secret#KEY} which is equals to
57     * a secret value in the session.
58     */
59    private boolean check(final FacesContext facesContext) {
60      final Map<String, String> requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
61      final String fromRequest = requestParameterMap.get(Secret.KEY);
62      final Secret secret = CDI.current().select(Secret.class).get();
63      return secret.check(fromRequest);
64    }
65  
66    @Override
67    public void beforePhase(final PhaseEvent event) {
68    }
69  
70    @Override
71    public PhaseId getPhaseId() {
72      return PhaseId.RESTORE_VIEW;
73    }
74  }