View Javadoc
1   /*
2    * Copyright (c) 2002-2021, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  /**
35   * Nom du Fichier : $RCSfile: CaptchaServlet.java,v $
36   * Version CVS : $Revision: 1.6 $
37   * Auteur : A.Floquet
38   * Description : Servlet de génération de l'image captcha.
39   *
40   */
41  package fr.paris.lutece.plugins.captcha.modules.jcaptcha.service.image;
42  
43  import fr.paris.lutece.portal.service.spring.SpringContextService;
44  import fr.paris.lutece.portal.service.util.AppLogService;
45  
46  import java.awt.image.BufferedImage;
47  import java.io.ByteArrayOutputStream;
48  import java.io.IOException;
49  
50  import javax.imageio.ImageIO;
51  import javax.servlet.Filter;
52  import javax.servlet.FilterChain;
53  import javax.servlet.FilterConfig;
54  import javax.servlet.ServletException;
55  import javax.servlet.ServletOutputStream;
56  import javax.servlet.ServletRequest;
57  import javax.servlet.ServletResponse;
58  import javax.servlet.http.HttpServletRequest;
59  import javax.servlet.http.HttpServletResponse;
60  
61  import com.octo.captcha.service.CaptchaServiceException;
62  import com.octo.captcha.service.multitype.GenericManageableCaptchaService;
63  
64  /**
65   * Generate Jcapcha test.
66   */
67  public class ImageCaptchaFilter implements Filter
68  {
69      private static final String PARAMETER_SESSION_IMAGE_CAPTCHA = "imageCaptcha";
70      private static final String LOGGER = "lutece.captcha";
71      private static final String IMAGE_TYPE = "jpeg";
72      private static final long serialVersionUID = -1806578484091247923L;
73  
74      /**
75       * {@inheritDoc}
76       */
77      public void init( FilterConfig filterConfig ) throws ServletException
78      {
79          // This would be a good place to collect a parameterized
80          // default encoding type. For brevity, we're going to
81          // use a hard-coded value in this example.
82      }
83  
84      /**
85       * Apply the filter
86       * 
87       * @param req
88       *            The HTTP request
89       * @param res
90       *            The HTTP response
91       * @param filterChain
92       *            The Filter Chain
93       * @throws IOException
94       *             If an error occured
95       * @throws ServletException
96       *             If an error occured
97       */
98      public void doFilter( ServletRequest req, ServletResponse res, FilterChain filterChain ) throws IOException, ServletException
99      {
100         HttpServletRequest request = (HttpServletRequest) req;
101         HttpServletResponse response = (HttpServletResponse) res;
102 
103         AppLogService.debug( LOGGER, "challenge captcha generation start" );
104 
105         byte [ ] captchaChallengeImage = null;
106 
107         // the output stream to render the captcha image as jpeg into
108         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream( );
109 
110         try
111         {
112             // grab bean
113             // MultiTypeCaptchaService captcha = (MultiTypeCaptchaService) SpringContextService.getPluginBean("jcaptcha", "imageCaptchaService");
114             GenericManageableCaptchaService captcha = (GenericManageableCaptchaService) SpringContextService.getBean( "jcaptcha.imageCaptchaService" );
115             AppLogService.info( "captcha : " + captcha );
116 
117             // get the session id that will identify the generated captcha.
118             // the same id must be used to validate the response, the session id
119             // is a good candidate!
120             BufferedImage challengeImage = captcha.getImageChallengeForID( request.getSession( ).getId( ), request.getLocale( ) );
121 
122             ImageIO.write( challengeImage, IMAGE_TYPE, jpegOutputStream );
123             // a jpeg encoder
124             /*
125              * JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder( jpegOutputStream ); jpegEncoder.encode( challengeImage );
126              */
127         }
128         catch( IllegalArgumentException e )
129         {
130             AppLogService.error( "exception :" + e.getMessage( ), e );
131             response.sendError( HttpServletResponse.SC_NOT_FOUND );
132 
133             return;
134         }
135         catch( CaptchaServiceException e )
136         {
137             AppLogService.error( "exception :" + e.getMessage( ), e );
138             response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
139 
140             return;
141         }
142 
143         captchaChallengeImage = jpegOutputStream.toByteArray( );
144         request.getSession( ).setAttribute( PARAMETER_SESSION_IMAGE_CAPTCHA, captchaChallengeImage );
145         // flush it in the response
146         response.setHeader( "cache-control", "no-cache, no-store,must-revalidate,max-age=0" );
147         response.setHeader( "pragma", "no-store, no-cache" );
148         response.setHeader( "expires", "1" );
149         response.setContentType( "image/jpeg" );
150 
151         ServletOutputStream responseOutputStream = response.getOutputStream( );
152         responseOutputStream.write( captchaChallengeImage );
153         responseOutputStream.flush( );
154         responseOutputStream.close( );
155         AppLogService.debug( LOGGER, "challenge captcha generation end" );
156     }
157 
158     /**
159      * Destroy the filter
160      */
161     public void destroy( )
162     {
163         // no-op
164     }
165 }