001    //$HeadURL: svn+ssh://jwilden@svn.wald.intevation.org/deegree/base/branches/2.5_testing/src/org/deegree/portal/standard/security/control/ClientHelper.java $
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 by:
005       Department of Geography, University of Bonn
006     and
007       lat/lon GmbH
008    
009     This library is free software; you can redistribute it and/or modify it under
010     the terms of the GNU Lesser General Public License as published by the Free
011     Software Foundation; either version 2.1 of the License, or (at your option)
012     any later version.
013     This library is distributed in the hope that it will be useful, but WITHOUT
014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
016     details.
017     You should have received a copy of the GNU Lesser General Public License
018     along with this library; if not, write to the Free Software Foundation, Inc.,
019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020    
021     Contact information:
022    
023     lat/lon GmbH
024     Aennchenstr. 19, 53177 Bonn
025     Germany
026     http://lat-lon.de/
027    
028     Department of Geography, University of Bonn
029     Prof. Dr. Klaus Greve
030     Postfach 1147, 53001 Bonn
031     Germany
032     http://www.geographie.uni-bonn.de/deegree/
033    
034     e-mail: info@deegree.org
035    ----------------------------------------------------------------------------*/
036    package org.deegree.portal.standard.security.control;
037    
038    import java.util.HashSet;
039    import java.util.Iterator;
040    import java.util.Set;
041    
042    import javax.servlet.http.HttpServletRequest;
043    import javax.servlet.http.HttpSession;
044    
045    import org.deegree.enterprise.control.AbstractListener;
046    import org.deegree.i18n.Messages;
047    import org.deegree.security.GeneralSecurityException;
048    import org.deegree.security.UnauthorizedException;
049    import org.deegree.security.drm.SecurityAccess;
050    import org.deegree.security.drm.SecurityAccessManager;
051    import org.deegree.security.drm.SecurityTransaction;
052    import org.deegree.security.drm.model.RightType;
053    import org.deegree.security.drm.model.Role;
054    import org.deegree.security.drm.model.User;
055    
056    /**
057     * Helper class that performs common security access tasks and checks used in the
058     * <code>Listener</code> classes.
059     *
060     * @author <a href="mschneider@lat-lon.de">Markus Schneider </a>
061     * @author last edited by: $Author: mschneider $
062     *
063     * @version $Revision: 18195 $, $Date: 2009-06-18 17:55:39 +0200 (Do, 18 Jun 2009) $
064     */
065    public class ClientHelper {
066    
067        public static final String KEY_USERNAME = "USERNAME";
068    
069        public static final String KEY_PASSWORD = "PASSWORD";
070    
071        public static final String TYPE_LAYER = "Layer";
072    
073        public static final String TYPE_FEATURETYPE = "Featuretype";
074    
075        public static final String TYPE_METADATASCHEMA = "MetadataSchema";
076    
077        /**
078         * Tries to acquire a <code>SecurityAccess</code> for the credentials (username, password)
079         * stored in the associated <code>HttpSesssion</code> of the given
080         * <code>AbstractListener</code>.
081         *
082         * @param listener
083         * @throws GeneralSecurityException
084         * @return SecurityAccess
085         */
086        public static SecurityAccess acquireAccess( AbstractListener listener )
087                                throws GeneralSecurityException {
088            // get USERNAME and PASSWORD from HttpSession
089            HttpSession session = ( (HttpServletRequest) listener.getRequest() ).getSession( false );
090            if ( session == null ) {
091                throw new UnauthorizedException( Messages.getMessage( "IGEO_STD_SEC_ERROR_UNAUTHORIZED_ACCESS" ) );
092            }
093            String userName = (String) session.getAttribute( KEY_USERNAME );
094            String password = (String) session.getAttribute( KEY_PASSWORD );
095    
096            // perform access check
097            SecurityAccessManager manager = SecurityAccessManager.getInstance();
098            User user = manager.getUserByName( userName );
099            user.authenticate( password );
100            return manager.acquireAccess( user );
101        }
102    
103        /**
104         * Tries to acquire a <code>SecurityTransaction</code> for the credentials (username,
105         * password) stored in the associated <code>HttpSesssion</code>.
106         *
107         * @param listener
108         * @throws GeneralSecurityException
109         * @return SecurityTransaction
110         */
111        public static SecurityTransaction acquireTransaction( AbstractListener listener )
112                                throws GeneralSecurityException {
113            // get USERNAME and PASSWORD from HttpSession
114            HttpSession session = ( (HttpServletRequest) listener.getRequest() ).getSession( false );
115            String userName = (String) session.getAttribute( KEY_USERNAME );
116            String password = (String) session.getAttribute( KEY_PASSWORD );
117    
118            // perform access check
119            SecurityAccessManager manager = SecurityAccessManager.getInstance();
120            User user = manager.getUserByName( userName );
121            user.authenticate( password );
122            return manager.acquireTransaction( user );
123        }
124    
125        /**
126         * Returns the administrator (the 'Administrator'- or a 'SUBADMIN:'-role) for the given role.
127         *
128         * @param access
129         * @param role
130         * @throws GeneralSecurityException
131         * @return Role
132         */
133        public static Role findAdminForRole( SecurityAccess access, Role role )
134                                throws GeneralSecurityException {
135            Role[] allRoles = access.getAllRoles();
136            Role admin = access.getRoleById( Role.ID_SEC_ADMIN );
137            for ( int i = 0; i < allRoles.length; i++ ) {
138                if ( allRoles[i].getName().startsWith( "SUBADMIN:" ) ) {
139                    // if a subadmin-role has the update right, it is
140                    // considered to be administrative for the role
141                    if ( allRoles[i].hasRight( access, RightType.UPDATE, role ) ) {
142                        admin = allRoles[i];
143                    }
144                }
145            }
146            return admin;
147        }
148    
149        /**
150         * Returns the associated 'Administrator'- or 'SUBADMIN:'-role of the token holder.
151         *
152         * @param access
153         * @throws GeneralSecurityException
154         * @return Role
155         */
156        public static Role checkForAdminOrSubadminRole( SecurityAccess access )
157                                throws GeneralSecurityException {
158            Role adminOrSubadminRole = null;
159            Role[] roles = access.getUser().getRoles( access );
160            for ( int i = 0; i < roles.length; i++ ) {
161                if ( roles[i].getID() == Role.ID_SEC_ADMIN
162                     || roles[i].getName().startsWith( "SUBADMIN:" ) ) {
163                    if ( adminOrSubadminRole == null ) {
164                        adminOrSubadminRole = roles[i];
165                    } else {
166                        throw new GeneralSecurityException( Messages.getMessage( "IGEO_STD_SEC_WRONG_ROLE",
167                                                                                 access.getUser().getTitle(),
168                                                                                 adminOrSubadminRole.getTitle(),
169                                                                                 roles[i].getTitle() ) );
170                    }
171                }
172            }
173            if ( adminOrSubadminRole == null ) {
174                throw new UnauthorizedException( Messages.getMessage( "IGEO_STD_SEC_MISSING_SUBADMIN_ROLE" ) );
175            }
176            return adminOrSubadminRole;
177        }
178    
179        /**
180         * Tests if the given token is associated with the 'Administrator'-role.
181         *
182         * @param access
183         * @throws GeneralSecurityException,
184         *             this is an UnauthorizedException if the user does not have the
185         *             'Administrator'-role
186         */
187        public static void checkForAdminRole( SecurityAccess access )
188                                throws GeneralSecurityException {
189            Role[] roles = access.getUser().getRoles( access );
190            for ( int i = 0; i < roles.length; i++ ) {
191                if ( roles[i].getID() == Role.ID_SEC_ADMIN ) {
192                    return;
193                }
194            }
195            throw new UnauthorizedException( Messages.getMessage( "IGEO_STD_SEC_MISSING_ADMIN_ROLE" ) );
196        }
197    
198        /**
199         * Tests if the 'SUBADMIN:' and 'Administrator'-roles are all disjoint (so that there are no
200         * users that have more than 1 role).
201         *
202         * @param access
203         * @throws GeneralSecurityException
204         *             if there is a user with more than one role
205         */
206        public static void checkSubadminRoleValidity( SecurityAccess access )
207                                throws GeneralSecurityException {
208    
209            Role[] subadminRoles = access.getRolesByNS( "SUBADMIN" );
210            Set<User>[] rolesAndUsers = new Set[subadminRoles.length + 1];
211    
212            String[] roleNames = new String[subadminRoles.length + 1];
213    
214            // admin role
215            User[] users = access.getRoleById( Role.ID_SEC_ADMIN ).getAllUsers( access );
216            rolesAndUsers[0] = new HashSet<User>();
217            roleNames[0] = "Administrator";
218            for ( int i = 0; i < users.length; i++ ) {
219                rolesAndUsers[0].add( users[i] );
220            }
221    
222            // subadmin roles
223            for ( int i = 1; i < rolesAndUsers.length; i++ ) {
224                users = subadminRoles[i - 1].getAllUsers( access );
225                rolesAndUsers[i] = new HashSet<User>();
226                roleNames[i] = subadminRoles[i - 1].getTitle();
227                for ( int j = 0; j < users.length; j++ ) {
228                    rolesAndUsers[i].add( users[j] );
229                }
230            }
231    
232            // now check if all usersets are disjoint
233            for ( int i = 0; i < rolesAndUsers.length - 1; i++ ) {
234                Set userSet1 = rolesAndUsers[i];
235                for ( int j = i + 1; j < rolesAndUsers.length; j++ ) {
236                    Set userSet2 = rolesAndUsers[j];
237                    Iterator it = userSet2.iterator();
238                    while ( it.hasNext() ) {
239                        User user = (User) it.next();
240                        if ( userSet1.contains( user ) ) {
241                            throw new GeneralSecurityException( Messages.getMessage( "IGEO_STD_SEC_INVALID_SUBADMIN_ROLE",
242                                                                                     user.getTitle(),
243                                                                                     roleNames[i],
244                                                                                     roleNames[j] ) );
245                        }
246                    }
247                }
248            }
249        }
250    }