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