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