]> source.dussan.org Git - archiva.git/blob
22c2b081a9916d5733a4e20b7ab717cfda6e15e9
[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.security.AccessDeniedException;
39 import org.apache.maven.archiva.security.ArchivaRoleConstants;
40 import org.apache.maven.archiva.security.ArchivaSecurityException;
41 import org.apache.maven.archiva.security.PrincipalNotFoundException;
42 import org.apache.maven.archiva.security.UserRepositories;
43 import org.codehaus.plexus.redback.authentication.AuthenticationDataSource;
44 import org.codehaus.plexus.redback.authentication.AuthenticationException;
45 import org.codehaus.plexus.redback.authentication.PasswordBasedAuthenticationDataSource;
46 import org.codehaus.plexus.redback.authorization.AuthorizationException;
47 import org.codehaus.plexus.redback.policy.AccountLockedException;
48 import org.codehaus.plexus.redback.system.SecuritySession;
49 import org.codehaus.plexus.redback.system.SecuritySystem;
50 import org.codehaus.plexus.redback.users.UserNotFoundException;
51 import org.codehaus.plexus.spring.PlexusToSpringUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.web.context.WebApplicationContext;
55 import org.springframework.web.context.support.WebApplicationContextUtils;
56
57 import com.sun.syndication.feed.synd.SyndFeed;
58 import com.sun.syndication.io.FeedException;
59 import com.sun.syndication.io.SyndFeedOutput;
60
61 /**
62  * Servlet for handling rss feed requests.
63  * 
64  * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
65  * @version
66  */
67 public class RssFeedServlet
68     extends HttpServlet
69 {
70     public static final String MIME_TYPE = "application/xml; charset=UTF-8";
71
72     private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
73
74     private static final String COULD_NOT_AUTHENTICATE_USER = "Could not authenticate user";
75
76     private static final String USER_NOT_AUTHORIZED = "User not authorized to access feed.";
77
78     private Logger log = LoggerFactory.getLogger( RssFeedServlet.class );
79
80     private RssFeedProcessor processor;
81
82     private WebApplicationContext wac;
83
84     private SecuritySystem securitySystem;
85
86     private UserRepositories userRepositories;
87
88     public void init( javax.servlet.ServletConfig servletConfig )
89         throws ServletException
90     {
91         super.init( servletConfig );
92         wac = WebApplicationContextUtils.getRequiredWebApplicationContext( servletConfig.getServletContext() );
93         securitySystem =
94             (SecuritySystem) wac.getBean( PlexusToSpringUtils.buildSpringId( SecuritySystem.class.getName() ) );
95         userRepositories =
96             (UserRepositories) wac.getBean( PlexusToSpringUtils.buildSpringId( UserRepositories.class.getName() ) );
97     }
98
99     public void doGet( HttpServletRequest req, HttpServletResponse res )
100         throws ServletException, IOException
101     {       
102         try
103         {
104             Map<String, String> map = new HashMap<String, String>();
105             SyndFeed feed = null;
106             String repoId = req.getParameter( "repoId" );
107             String groupId = req.getParameter( "groupId" );
108             String artifactId = req.getParameter( "artifactId" );
109             
110             if ( isAuthorized( req ) )
111             {
112                 if ( repoId != null )
113                 {                   
114                     // new artifacts in repo feed request
115                     processor =
116                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
117                                                                                            RssFeedProcessor.class.getName(),
118                                                                                            "new-artifacts" ) );
119                     map.put( RssFeedProcessor.KEY_REPO_ID, repoId );                    
120                 }
121                 else if ( ( groupId != null ) && ( artifactId != null ) )
122                 {
123                     // new versions of artifact feed request
124                     processor =
125                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
126                                                                                            RssFeedProcessor.class.getName(),
127                                                                                            "new-versions" ) );
128                     map.put( RssFeedProcessor.KEY_GROUP_ID, groupId );
129                     map.put( RssFeedProcessor.KEY_ARTIFACT_ID, artifactId );                    
130                 }
131                 else
132                 {
133                     res.sendError( HttpServletResponse.SC_BAD_REQUEST, "Required fields not found in request." );
134                     return;
135                 }
136             }
137             else
138             {
139                 res.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Request is not authorized." );
140                 return;
141             }
142             
143             feed = processor.process( map );
144             res.setContentType( MIME_TYPE );
145             
146             if ( repoId != null )
147             {
148                 feed.setLink( req.getRequestURL() + "?repoId=" + repoId );
149             }
150             else if ( ( groupId != null ) && ( artifactId != null ) )
151             {
152                 feed.setLink( req.getRequestURL() + "?groupId=" + groupId + "&artifactId=" + artifactId );
153             }
154
155             SyndFeedOutput output = new SyndFeedOutput();
156             output.output( feed, res.getWriter() );
157         }
158         catch ( AuthorizationException ae )
159         {
160             log.error( USER_NOT_AUTHORIZED, ae );
161             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
162         }
163         catch ( UserNotFoundException unfe )
164         {
165             log.error( COULD_NOT_AUTHENTICATE_USER, unfe );
166             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
167         }
168         catch ( AccountLockedException acce )
169         {
170             log.error( COULD_NOT_AUTHENTICATE_USER, acce );
171             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
172         }
173         catch ( AuthenticationException authe )
174         {
175             log.error( COULD_NOT_AUTHENTICATE_USER, authe );
176             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
177         }
178         catch ( FeedException ex )
179         {
180             log.error( COULD_NOT_GENERATE_FEED_ERROR, ex );
181             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
182         }
183     }
184
185     /**
186      * Basic authentication.
187      * 
188      * @param req
189      * @return
190      */
191     private boolean isAuthorized( HttpServletRequest req )
192         throws UserNotFoundException, AccountLockedException, AuthenticationException, AuthorizationException
193     {
194         String auth = req.getHeader( "Authorization" );
195         
196         if ( auth == null )
197         {
198             return false;
199         }
200
201         if ( !auth.toUpperCase().startsWith( "BASIC " ) )
202         {
203             return false;
204         }
205
206         Decoder dec = new Base64();        
207         String usernamePassword = "";
208
209         try
210         {
211             usernamePassword = new String( ( byte[] ) dec.decode( auth.substring( 6 ).getBytes() ) );
212         }
213         catch ( DecoderException ie )
214         {
215             log.error( "Error decoding username and password.", ie.getMessage() );
216         }
217         
218         String[] userCredentials = usernamePassword.split( ":" );
219         String username = userCredentials[0];
220         String password = userCredentials[1];
221         
222         AuthenticationDataSource dataSource = new PasswordBasedAuthenticationDataSource( username, password );
223         SecuritySession session = null;
224
225         List<String> repoIds = new ArrayList<String>();
226         if ( req.getParameter( "repoId" ) != null )
227         {
228             repoIds.add( req.getParameter( "repoId" ) );
229         }
230         else
231         {
232             repoIds = getObservableRepos( username );
233         }
234
235         session = securitySystem.authenticate( dataSource );
236
237         for ( String repoId : repoIds )
238         {            
239             if ( securitySystem.isAuthorized( session, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS, repoId ) )
240             {
241                 return true;
242             }
243         }
244
245         return false;
246     }
247
248     private List<String> getObservableRepos( String principal )
249     {
250         try
251         {
252             return userRepositories.getObservableRepositoryIds( principal );
253         }
254         catch ( PrincipalNotFoundException e )
255         {
256             log.warn( e.getMessage(), e );
257         }
258         catch ( AccessDeniedException e )
259         {
260             log.warn( e.getMessage(), e );
261         }
262         catch ( ArchivaSecurityException e )
263         {
264             log.warn( e.getMessage(), e );
265         }
266
267         return Collections.emptyList();
268     }
269 }