]> source.dussan.org Git - archiva.git/blob
89570523a9ffec0f097bdebfb3477707111f12ca
[archiva.git] /
1 package org.apache.maven.archiva.web.rss;
2
3 /*
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements.  See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership.  The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License.  You may obtain a copy of the License at
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied.  See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.servlet.ServletException;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33
34 import org.apache.archiva.rss.processor.RssFeedProcessor;
35 import org.apache.commons.codec.Decoder;
36 import org.apache.commons.codec.DecoderException;
37 import org.apache.commons.codec.binary.Base64;
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.maven.archiva.database.ArchivaDatabaseException;
40 import org.apache.maven.archiva.security.AccessDeniedException;
41 import org.apache.maven.archiva.security.ArchivaRoleConstants;
42 import org.apache.maven.archiva.security.ArchivaSecurityException;
43 import org.apache.maven.archiva.security.ArchivaXworkUser;
44 import org.apache.maven.archiva.security.PrincipalNotFoundException;
45 import org.apache.maven.archiva.security.ServletAuthenticator;
46 import org.apache.maven.archiva.security.UserRepositories;
47 import org.codehaus.plexus.redback.authentication.AuthenticationException;
48 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
49 import org.codehaus.plexus.redback.authorization.AuthorizationException;
50 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
51 import org.codehaus.plexus.redback.policy.AccountLockedException;
52 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
53 import org.codehaus.plexus.redback.system.SecuritySession;
54 import org.codehaus.plexus.redback.users.UserNotFoundException;
55 import org.codehaus.plexus.redback.xwork.filter.authentication.HttpAuthenticator;
56 import org.codehaus.plexus.spring.PlexusToSpringUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.springframework.web.context.WebApplicationContext;
60 import org.springframework.web.context.support.WebApplicationContextUtils;
61
62 import com.sun.syndication.feed.synd.SyndFeed;
63 import com.sun.syndication.io.FeedException;
64 import com.sun.syndication.io.SyndFeedOutput;
65
66 /**
67  * Servlet for handling rss feed requests.
68  * 
69  * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
70  * @version
71  */
72 public class RssFeedServlet
73     extends HttpServlet
74 {
75     public static final String MIME_TYPE = "application/rss+xml; charset=UTF-8";
76
77     private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
78
79     private static final String COULD_NOT_AUTHENTICATE_USER = "Could not authenticate user";
80
81     private static final String USER_NOT_AUTHORIZED = "User not authorized to access feed.";
82
83     private Logger log = LoggerFactory.getLogger( RssFeedServlet.class );
84
85     private RssFeedProcessor processor;
86
87     private WebApplicationContext wac;
88
89     private UserRepositories userRepositories;
90
91     private ServletAuthenticator servletAuth;
92
93     private HttpAuthenticator httpAuth;
94     
95     private ArchivaXworkUser archivaXworkUser;
96
97     public void init( javax.servlet.ServletConfig servletConfig )
98         throws ServletException
99     {
100         super.init( servletConfig );
101         wac = WebApplicationContextUtils.getRequiredWebApplicationContext( servletConfig.getServletContext() );
102         userRepositories =
103             (UserRepositories) wac.getBean( PlexusToSpringUtils.buildSpringId( UserRepositories.class.getName() ) );
104         servletAuth =
105             (ServletAuthenticator) wac.getBean( PlexusToSpringUtils.buildSpringId( ServletAuthenticator.class.getName() ) );
106         httpAuth =
107             (HttpAuthenticator) wac.getBean( PlexusToSpringUtils.buildSpringId( HttpAuthenticator.ROLE, "basic" ) );
108         archivaXworkUser = (ArchivaXworkUser) wac.getBean( PlexusToSpringUtils.buildSpringId( ArchivaXworkUser.class ) );
109     }
110
111     public void doGet( HttpServletRequest req, HttpServletResponse res )
112         throws ServletException, IOException
113     {
114         String repoId = null;
115         String groupId = null;
116         String artifactId = null;
117         
118         String url = StringUtils.removeEnd( req.getRequestURL().toString(), "/" );          
119         if( StringUtils.countMatches( StringUtils.substringAfter( url, "feeds/" ), "/" ) > 0 )
120         {
121             artifactId = StringUtils.substringAfterLast( url, "/" );
122             groupId = StringUtils.substringBeforeLast( StringUtils.substringAfter( url, "feeds/" ), "/");
123             groupId = StringUtils.replaceChars( groupId, '/', '.' );
124         }
125         else if( StringUtils.countMatches( StringUtils.substringAfter( url, "feeds/" ), "/" ) == 0 )
126         {
127             repoId = StringUtils.substringAfterLast( url, "/" );
128         }
129         else
130         {
131             res.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid request url." );
132             return;
133         }        
134         
135         try
136         {
137             Map<String, String> map = new HashMap<String, String>();
138             SyndFeed feed = null;
139             
140             if ( isAllowed( req, repoId, groupId, artifactId ) )
141             {
142                 if ( repoId != null )
143                 {
144                     // new artifacts in repo feed request
145                     processor =
146                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
147                                                                                            RssFeedProcessor.class.getName(),
148                                                                                            "new-artifacts" ) );
149                     map.put( RssFeedProcessor.KEY_REPO_ID, repoId );
150                 }
151                 else if ( ( groupId != null ) && ( artifactId != null ) )
152                 {
153                     // new versions of artifact feed request
154                     processor =
155                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
156                                                                                            RssFeedProcessor.class.getName(),
157                                                                                            "new-versions" ) );
158                     map.put( RssFeedProcessor.KEY_GROUP_ID, groupId );
159                     map.put( RssFeedProcessor.KEY_ARTIFACT_ID, artifactId );
160                 }
161             }
162             else
163             {
164                 res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
165                 return;
166             }
167
168             feed = processor.process( map );            
169             if( feed == null )
170             {
171                 res.sendError( HttpServletResponse.SC_NO_CONTENT, "No information available." );
172                 return;
173             }
174             
175             res.setContentType( MIME_TYPE );
176                         
177             if ( repoId != null )
178             {   
179                 feed.setLink( req.getRequestURL().toString() );
180             }
181             else if ( ( groupId != null ) && ( artifactId != null ) )
182             {
183                 feed.setLink( req.getRequestURL().toString() );                
184             }
185
186             SyndFeedOutput output = new SyndFeedOutput();
187             output.output( feed, res.getWriter() );
188         }
189         catch ( ArchivaDatabaseException e )
190         {
191             log.debug( COULD_NOT_GENERATE_FEED_ERROR, e );
192             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
193         }
194         catch ( UserNotFoundException unfe )
195         {
196             log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
197             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
198         }
199         catch ( AccountLockedException acce )
200         {            
201             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
202         }
203         catch ( AuthenticationException authe )
204         {   
205             log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
206             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
207         }
208         catch ( FeedException ex )
209         {
210             log.debug( COULD_NOT_GENERATE_FEED_ERROR, ex );
211             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
212         }
213         catch ( MustChangePasswordException e )
214         {            
215             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
216         }
217         catch ( UnauthorizedException e )
218         {
219             log.debug( e.getMessage() );
220             if ( repoId != null )
221             {
222                 res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
223             }
224             else
225             {
226                 res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
227             }
228             
229             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
230         }
231     }
232
233     /**
234      * Basic authentication.
235      * 
236      * @param req
237      * @param repositoryId TODO
238      * @param groupId TODO
239      * @param artifactId TODO
240      * @return
241      */
242     private boolean isAllowed( HttpServletRequest req, String repositoryId, String groupId, String artifactId )
243         throws UserNotFoundException, AccountLockedException, AuthenticationException, MustChangePasswordException,
244         UnauthorizedException
245     {
246         String auth = req.getHeader( "Authorization" );
247         List<String> repoIds = new ArrayList<String>();
248
249         if ( repositoryId != null )
250         {
251             repoIds.add( repositoryId );
252         }
253         else if ( artifactId != null && groupId != null )
254         {
255             if ( auth != null )
256             {
257                 if ( !auth.toUpperCase().startsWith( "BASIC " ) )
258                 {
259                     return false;
260                 }
261
262                 Decoder dec = new Base64();
263                 String usernamePassword = "";
264
265                 try
266                 {
267                     usernamePassword = new String( (byte[]) dec.decode( auth.substring( 6 ).getBytes() ) );
268                 }
269                 catch ( DecoderException ie )
270                 {
271                     log.warn( "Error decoding username and password.", ie.getMessage() );
272                 }
273
274                 if ( usernamePassword == null || usernamePassword.trim().equals( "" ) )
275                 {
276                     repoIds = getObservableRepos( archivaXworkUser.getGuest() );
277                 }
278                 else
279                 {
280                     String[] userCredentials = usernamePassword.split( ":" );
281                     repoIds = getObservableRepos( userCredentials[0] );
282                 }
283             }
284             else
285             {
286                 repoIds = getObservableRepos( archivaXworkUser.getGuest() );
287             }
288         }
289         else
290         {
291             return false;
292         }
293
294         for ( String repoId : repoIds )
295         {
296             try
297             {
298                 AuthenticationResult result = httpAuth.getAuthenticationResult( req, null );
299                 SecuritySession securitySession = httpAuth.getSecuritySession();
300
301                 if ( servletAuth.isAuthenticated( req, result ) &&
302                     servletAuth.isAuthorized( req, securitySession, repoId, false ) )
303                 {
304                     return true;
305                 }
306             }
307             catch ( AuthorizationException e )
308             {
309                 
310             }
311             catch ( UnauthorizedException e )
312             {
313              
314             }
315         }
316
317         throw new UnauthorizedException( "Access denied." );
318     }
319
320     private List<String> getObservableRepos( String principal )
321     {
322         try
323         {
324             return userRepositories.getObservableRepositoryIds( principal );
325         }
326         catch ( PrincipalNotFoundException e )
327         {
328             log.warn( e.getMessage(), e );
329         }
330         catch ( AccessDeniedException e )
331         {
332             log.warn( e.getMessage(), e );
333         }
334         catch ( ArchivaSecurityException e )
335         {
336             log.warn( e.getMessage(), e );
337         }
338
339         return Collections.emptyList();
340     }
341
342 }