View Javadoc

1   /* 
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.jetspeed.security;
18  
19  import java.security.Permission;
20  import java.security.PermissionCollection;
21  import java.security.Principal;
22  import java.util.Enumeration;
23  import java.util.HashSet;
24  import java.util.Iterator;
25  import java.util.LinkedList;
26  import java.util.List;
27  import java.util.Set;
28  
29  import javax.security.auth.Subject;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.jetspeed.security.impl.PrincipalsSet;
34  import org.apache.jetspeed.security.impl.GroupPrincipalImpl;
35  import org.apache.jetspeed.security.impl.RolePrincipalImpl;
36  import org.apache.jetspeed.security.impl.UserPrincipalImpl;
37  
38  /***
39   * <p>
40   * Security helper.
41   * </p>
42   * 
43   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
44   * @version $Id: SecurityHelper.java 517121 2007-03-12 07:45:49Z ate $
45   */
46  public class SecurityHelper
47  {
48      private static final Log log = LogFactory.getLog(SecurityHelper.class);
49  
50      /***
51       * <p>
52       * Given a subject, finds the first principal of the given classe for that subject. If a
53       * principal of the given classe is not found, null is returned.
54       * </p>
55       * 
56       * @param subject The subject supplying the principals.
57       * @param classe A class or interface derived from java.security.InternalPrincipal.
58       * @return The first principal matching a principal classe parameter.
59       */
60      public static Principal getPrincipal(Subject subject, Class classe)
61      {
62          Principal principal = null;
63          Set principalList = subject.getPrincipals();
64          if (principalList != null)
65          { 
66          	Iterator principals = subject.getPrincipals().iterator();
67  	        while (principals.hasNext())
68  	        {
69  	            Principal p = (Principal) principals.next();
70  	            if (classe.isInstance(p))
71  	            {
72  	                principal = p;
73  	                break;
74  	            }
75  	        }
76          }
77          return principal;
78      }
79  
80      /***
81       * <p>
82       * Given a subject, finds the first principal of the given classe for that subject. If a
83       * principal of the given classe is not found, then the first other principal is returned. If
84       * the list is empty, null is returned.
85       * </p>
86       * 
87       * @param subject The subject supplying the principals.
88       * @param classe A class or interface derived from java.security.InternalPrincipal.
89       * @return The first principal matching a principal classe parameter.
90       */
91      public static Principal getBestPrincipal(Subject subject, Class classe)
92      {
93  
94          Principal principal = null;
95          Iterator principals = subject.getPrincipals().iterator();
96          while (principals.hasNext())
97          {
98              Principal p = (Principal) principals.next();
99              if (classe.isInstance(p))
100             {
101                 principal = p;
102                 break;
103             }
104             else
105             {
106                 if (principal == null)
107                 {
108                     principal = p;
109                 }
110             }
111         }
112         return principal;
113     }
114     
115     /***
116      * <p>
117      * Returns the first matching principal of a given type.
118      * </p>
119      * 
120      * @param principals The array of pricinpals
121      * @param classe The class of Principal
122      * @return The principal.
123      */
124     public static Principal getBestPrincipal(Principal[] principals, Class classe)
125     {
126 
127         Principal principal = null;
128         for (int i = 0; i < principals.length; i++)
129         {
130             Principal p = principals[i];
131             if (classe.isInstance(p))
132             {
133                 principal = p;
134                 break;
135             }
136             else
137             {
138                 if (principal == null)
139                 {
140                     principal = p;
141                 }
142             }
143         }
144         return principal;
145     }
146 
147     /***
148      * <p>
149      * Utility method used to retrieve the Preferences API absolute/full path from a given
150      * principal.
151      * </p>
152      * 
153      * @param principal The principal.
154      * @return The Preferences absolute/full path.
155      */
156     public static String getPreferencesFullPath(Principal principal)
157     {
158 
159         if ((UserPrincipal.class).isInstance(principal))
160         {
161             return UserPrincipalImpl.getFullPathFromPrincipalName(principal.getName());
162         }
163         else if ((RolePrincipal.class).isInstance(principal))
164         {
165             return RolePrincipalImpl.getFullPathFromPrincipalName(principal.getName());
166         }
167         else if ((GroupPrincipal.class).isInstance(principal))
168         {
169             return GroupPrincipalImpl.getFullPathFromPrincipalName(principal.getName());
170         }
171         else
172         {
173             return null;
174         }
175     }
176 
177     /***
178      * <p>
179      * Utility method to create a subject.
180      * </p>
181      * 
182      * @param principalName The user principal name.
183      * @return The subject.
184      */
185     public static Subject createSubject(String principalName)
186     {
187         Principal principal = new UserPrincipalImpl(principalName);
188         Set principals = new PrincipalsSet();
189         principals.add(principal);
190         return new Subject(true, principals, new HashSet(), new HashSet());
191     }
192 
193     /***
194      * <p>
195      * Given a subject, finds all principals of the given classe for that subject. If no principals
196      * of the given class is not found, null is returned.
197      * </p>
198      * 
199      * @param subject The subject supplying the principals.
200      * @param classe A class or interface derived from java.security.InternalPrincipal.
201      * @return A List of all principals of type Principal matching a principal classe parameter.
202      */
203     public static List getPrincipals(Subject subject, Class classe)
204     {
205         List result = new LinkedList();
206         Iterator principals = subject.getPrincipals().iterator();
207         while (principals.hasNext())
208         {
209             Principal p = (Principal) principals.next();
210             if (classe.isInstance(p))
211             {
212                 result.add(p);
213             }
214         }
215         return result;
216     }
217 
218     /***
219      * <p>
220      * Given a subject, find the (first) PasswordCredential from the private credentials
221      * </p>
222      * 
223      * @param subject The subject
224      * @return the PasswordCredential or null if not found.
225      */
226     public static PasswordCredential getPasswordCredential(Subject subject)
227     {
228         Iterator iter = subject.getPrivateCredentials().iterator();
229         while (iter.hasNext())
230         {
231             Object o = iter.next();
232             if (o instanceof PasswordCredential)
233             {
234                 return (PasswordCredential) o;
235             }
236         }
237         return null;
238     }
239 
240     /***
241      * <p>
242      * Adds a collection of permsToAdd to a collection of existing permissions.
243      * </p>
244      * 
245      * @param perms The existing permissions.
246      * @param permsToAdd The permissions to add.
247      */
248     public static void addPermissions(PermissionCollection perms, PermissionCollection permsToAdd)
249     {
250         int permsAdded = 0;
251         if (null != permsToAdd)
252         {
253             Enumeration permsToAddEnum = permsToAdd.elements();
254             while (permsToAddEnum.hasMoreElements())
255             {
256                 permsAdded++;
257                 Permission currPerm = (Permission) permsToAddEnum.nextElement();
258                 perms.add(currPerm);
259                 if (log.isDebugEnabled())
260                 {
261                     log.debug("Adding the permission: [class, " + currPerm.getClass().getName() + "], " + "[name, "
262                             + currPerm.getName() + "], " + "[actions, " + currPerm.getActions() + "]");
263                 }
264             }
265         }
266         if ((permsAdded == 0) && log.isDebugEnabled())
267         {
268             log.debug("No permissions to add...");
269         }
270     }
271     
272     public static Principal createPrincipalFromFullPath(String fullPath)
273     {
274         Principal principal = null;
275         if (fullPath.startsWith(BasePrincipal.PREFS_ROLE_ROOT))
276         {
277             String name = RolePrincipalImpl.getPrincipalNameFromFullPath(fullPath);            
278             principal = new RolePrincipalImpl(name);
279         }
280         else if (fullPath.startsWith(BasePrincipal.PREFS_USER_ROOT))
281         {
282             String name = UserPrincipalImpl.getPrincipalNameFromFullPath(fullPath);
283             principal = new UserPrincipalImpl(name);
284         }
285         else if (fullPath.startsWith(BasePrincipal.PREFS_GROUP_ROOT))
286         {
287             String name = GroupPrincipalImpl.getPrincipalNameFromFullPath(fullPath);            
288             principal = new GroupPrincipalImpl(name);
289             
290         }
291         return principal;
292     }
293 }