KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > repository > SecurityRepository


1 /*
2  * Copyright (c) Rafael Steil
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms,
6  * with or without modification, are permitted provided
7  * that the following conditions are met:
8  *
9  * 1) Redistributions of source code must retain the above
10  * copyright notice, this list of conditions and the
11  * following disclaimer.
12  * 2) Redistributions in binary form must reproduce the
13  * above copyright notice, this list of conditions and
14  * the following disclaimer in the documentation and/or
15  * other materials provided with the distribution.
16  * 3) Neither the name of "Rafael Steil" nor
17  * the names of its contributors may be used to endorse
18  * or promote products derived from this software without
19  * specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
22  * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
27  * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
32  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
34  * IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
37  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
38  *
39  * This file creation date: 18/11/2003 / 23:09:15
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.repository;
44
45 import net.jforum.JForumExecutionContext;
46 import net.jforum.SessionFacade;
47 import net.jforum.cache.CacheEngine;
48 import net.jforum.cache.Cacheable;
49 import net.jforum.dao.DataAccessDriver;
50 import net.jforum.dao.UserDAO;
51 import net.jforum.dao.security.GroupSecurityDAO;
52 import net.jforum.entities.User;
53 import net.jforum.entities.UserSession;
54 import net.jforum.exceptions.SecurityLoadException;
55 import net.jforum.security.PermissionControl;
56
57 import org.apache.log4j.Logger;
58
59 /**
60  * @author Rafael Steil
61  * @version $Id: SecurityRepository.java,v 1.19 2006/01/29 15:07:19 rafaelsteil Exp $
62  */

63 public class SecurityRepository implements Cacheable
64 {
65     private static final Logger logger = Logger.getLogger(SecurityRepository.class);
66     private static CacheEngine cache;
67     private static final String JavaDoc FQN = "security";
68
69     /**
70      * @see net.jforum.cache.Cacheable#setCacheEngine(net.jforum.cache.CacheEngine)
71      */

72     public void setCacheEngine(CacheEngine engine)
73     {
74         cache = engine;
75     }
76
77     /***
78      * Load user's roles.
79      *
80      * @param userId The user's id
81      * @param force If <code>true</code>, forces a reload. If <code>false</code>, the call
82      * will be ignored if the roles are already loaded.
83      *
84      * @see SecurityRepository#load(int)
85      * @see SecurityRepository#load(User)
86      * @see SecurityRepository#load(User, boolean)
87      * @throws Exception
88      */

89     public static PermissionControl load(int userId, boolean force) throws Exception JavaDoc
90     {
91         if (force || cache.get(FQN, Integer.toString(userId)) == null) {
92             UserDAO um = DataAccessDriver.getInstance().newUserDAO();
93             
94             return SecurityRepository.load(um.selectById(userId), force);
95         }
96         
97         return SecurityRepository.get(userId);
98     }
99
100     /**
101      * Load user's roles.
102      *
103      * @param userId The users's id
104      *
105      * @see SecurityRepository#load(int, boolean)
106      * @see SecurityRepository#load(User)
107      * @see SecurityRepository#load(User, boolean)
108      * @throws Exception
109      */

110     public static PermissionControl load(int userId) throws Exception JavaDoc
111     {
112         return SecurityRepository.load(userId, false);
113     }
114     
115     /**
116      * Load user's roles.
117      *
118      * @param user The <code>User</code> to load.
119      *
120      * @see SecurityRepository#load(int)
121      * @see SecurityRepository#load(int, boolean),
122      * @see SecurityRepository#load(User, boolean)
123      * @throws Exception
124      */

125     public static PermissionControl load(User user) throws Exception JavaDoc
126     {
127         return SecurityRepository.load(user, false);
128     }
129
130     /**
131      * Load user's roles.
132      *
133      * @param user The <code>User</code> to load
134      * @param force If <code>true</code>, forces a reload. If <code>false</code>, the call
135      * will be ignored if the roles are already loaded.
136      *
137      * @see SecurityRepository#load(int)
138      * @see SecurityRepository#load(int, boolean)
139      * @see SecurityRepository#load(User)
140      * @throws Exception
141      */

142     public static PermissionControl load(User user, boolean force) throws Exception JavaDoc
143     {
144         String JavaDoc userId = Integer.toString(user.getId());
145         if (force || cache.get(FQN, userId) == null) {
146             PermissionControl pc = new PermissionControl();
147             
148             // load roles
149
GroupSecurityDAO dao = DataAccessDriver.getInstance().newGroupSecurityDAO();
150             pc.setRoles(dao.loadRolesByUserGroups(user));
151             
152             cache.add(FQN, userId, pc);
153             
154             return pc;
155         }
156         
157         return SecurityRepository.get(user.getId());
158     }
159     
160     /**
161      * Check if the logged user has access to the role.
162      * This method gets user's id from its session.
163      *
164      * @param roleName The role name to verity
165      * @return <code>true</code> if the user has access to the role, <code>false</code> if access is denied
166      * @throws SecurityLoadException if case of erros while trying
167      * to load the roles
168      * @see #canAccess(String, String)
169      * @see #canAccess(int, String, String)
170      */

171     public static boolean canAccess(String JavaDoc roleName)
172     {
173         return canAccess(roleName, null);
174     }
175     
176     public static boolean canAccess(int userId, String JavaDoc roleName)
177     {
178         return canAccess(userId, roleName, null);
179     }
180
181     /**
182      * Check if the logged user has access to the role.
183      * This method gets user's id from its session.
184      *
185      * @param roleName The role name to verify
186      * @param value The value relacted to the role to verify for access
187      * @return <code>true</code> if the user has access to the role, <code>false</code> if access is denied
188      */

189     public static boolean canAccess(String JavaDoc roleName, String JavaDoc value)
190     {
191         UserSession us = SessionFacade.getUserSession();
192         if (us == null) {
193             logger.warn("Found null userSession. Going anonymous. Session id #"
194                     + JForumExecutionContext.getRequest().getSession().getId());
195             us = new UserSession();
196             us.makeAnonymous();
197         }
198         
199         return canAccess(us.getUserId(), roleName, value);
200     }
201     
202     public static boolean canAccess(int userId, String JavaDoc roleName, String JavaDoc value)
203     {
204         PermissionControl pc = SecurityRepository.get(userId);
205         
206         if (pc == null) {
207             throw new SecurityLoadException("Failed to load security roles for userId " + userId + " (null PermissionControl returned). "
208                 + "roleName=" + roleName + ", roleValue=" + value);
209         }
210         
211         return (value != null ? pc.canAccess(roleName, value) : pc.canAccess(roleName));
212     }
213
214     /**
215      * Gets the permssion schema of some specific user.
216      * If the roles of the user aren't loaded yet, a call
217      * to {@link #load(int)} will be made.
218      *
219      * @param userId The user's id to get the permissions
220      * @return The <code>PermissionControl</code> instance related
221      * to the user id passed as argument
222      * @throws SecurityLoadException if case of erros while trying
223      * to load the roles
224      */

225     public static PermissionControl get(int userId)
226     {
227         PermissionControl pc = (PermissionControl)cache.get(FQN, Integer.toString(userId));
228         
229         if (pc == null) {
230             try {
231                 pc = load(userId);
232             }
233             catch (Exception JavaDoc e) {
234                 throw new SecurityLoadException(e);
235             }
236         }
237         
238         return pc;
239     }
240
241     /**
242      * Adds a new permission control schema to the cache
243      *
244      * @param userId The user's id to associate with the schema
245      * @param pc The <code>PermissionControl</code> instance to add
246      */

247     public static synchronized void add(int userId, PermissionControl pc)
248     {
249         cache.add(FQN, Integer.toString(userId), pc);
250     }
251     
252     /**
253      * Remove the cached roles from a specific user.
254      *
255      * @param userId The id of the user to remove from the cache
256      */

257     public static synchronized void remove(int userId)
258     {
259         cache.remove(FQN, Integer.toString(userId));
260     }
261     
262     /**
263      * Clear all cached security entries.
264      */

265     public static synchronized void clean()
266     {
267         cache.remove(FQN);
268     }
269 }
270
Popular Tags