KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jguard > example > struts > admin > actions > UserDispatchAction


1 /*
2 jGuard is a security framework based on top of jaas (java authentication and authorization security).
3 it is written for web applications, to resolve simply, access control problems.
4 version $Name: v080_step3_beta2 $
5 http://sourceforge.net/projects/jguard/
6
7 Copyright (C) 2004 Charles GAY
8
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
13
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
23
24 jGuard project home page:
25 http://sourceforge.net/projects/jguard/
26
27 */

28 package net.sf.jguard.example.struts.admin.actions;
29
30
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.HashSet JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Set JavaDoc;
37
38 import javax.security.auth.Subject JavaDoc;
39 import javax.servlet.http.HttpServletRequest JavaDoc;
40 import javax.servlet.http.HttpServletResponse JavaDoc;
41
42 import net.sf.jguard.core.authentication.credentials.JGuardCredential;
43 import net.sf.jguard.core.principals.RolePrincipal;
44 import net.sf.jguard.example.struts.actions.BaseAction;
45 import net.sf.jguard.ext.SecurityConstants;
46 import net.sf.jguard.ext.authentication.AuthenticationException;
47 import net.sf.jguard.ext.authentication.manager.AuthenticationManager;
48 import net.sf.jguard.ext.registration.RegistrationException;
49 import net.sf.jguard.ext.registration.SubjectTemplate;
50 import net.sf.jguard.jee.authentication.http.HttpAuthenticationUtils;
51 import net.sf.jguard.jee.authentication.http.HttpConstants;
52
53 import org.apache.commons.lang.StringUtils;
54 import org.apache.log4j.Logger;
55 import org.apache.struts.action.ActionForm;
56 import org.apache.struts.action.ActionForward;
57 import org.apache.struts.action.ActionMapping;
58 import org.apache.struts.action.DynaActionForm;
59
60
61 /**
62  * @author <a HREF="mailto:tandilero@users.sourceforge.net">Maximiliano Batelli</a>
63  */

64 public class UserDispatchAction extends BaseAction{
65
66     private static Logger logger = Logger.getLogger(UserDispatchAction.class);
67
68     /**
69      * list users.
70      * @param mapping
71      * @param form
72      * @param request
73      * @param response
74      * @return
75      */

76     public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
77         DynaActionForm dyna = (DynaActionForm)form;
78         Set JavaDoc users = null;
79
80         AuthenticationManager am = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
81         try {
82         users = am.getUsers();
83             if(logger.isDebugEnabled()){
84                 logger.debug(" listing users");
85                 Iterator JavaDoc usersIt = users.iterator();
86                 while(usersIt.hasNext()){
87                     Subject JavaDoc user = (Subject JavaDoc)usersIt.next();
88                     logger.debug(user);
89                 }
90             }
91         } catch (AuthenticationException e) {
92             e.printStackTrace();
93         }
94         List JavaDoc usersList = new ArrayList JavaDoc(users);
95         dyna.set("users",usersList);
96
97         return mapping.findForward("listUsersOK");
98     }
99
100     /**
101      * read an user.
102      * @param mapping
103      * @param form
104      * @param request
105      * @param response
106      * @return
107      */

108     public ActionForward read(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
109         DynaActionForm dyna = (DynaActionForm)form;
110         AuthenticationManager authenticationManager = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
111         Iterator JavaDoc itCred;
112         JGuardCredential jcred;
113         Subject JavaDoc user = authenticationManager.findUser((String JavaDoc)dyna.get("login"));
114
115         resetForm(dyna);
116
117         Set JavaDoc privCred = user.getPrivateCredentials();
118         itCred = privCred.iterator();
119         while(itCred.hasNext()) {
120             jcred = (JGuardCredential)itCred.next();
121             dyna.set(jcred.getId(), jcred.getValue());
122         }
123         Set JavaDoc pubCred = user.getPublicCredentials();
124         itCred = pubCred.iterator();
125         while(itCred.hasNext()) {
126             jcred = (JGuardCredential)itCred.next();
127             dyna.set(jcred.getId(), jcred.getValue());
128         }
129         dyna.set("oldLogin", (String JavaDoc)dyna.get("login"));
130         Set JavaDoc principals =new HashSet JavaDoc(user.getPrincipals());
131         Set JavaDoc localPrincipals = authenticationManager.getLocalPrincipals();
132         //we remove all the principals which are not owned by this appplication
133
principals.retainAll(localPrincipals);
134         dyna.set("principals", new ArrayList JavaDoc(principals));
135
136         Collection JavaDoc tempCol = new HashSet JavaDoc(authenticationManager.getLocalPrincipals());
137         tempCol.removeAll(user.getPrincipals());
138         request.setAttribute("allPrincipals", tempCol);
139         request.setAttribute("action", "update");
140         return mapping.findForward("readUserOK");
141     }
142
143     /**
144      * called when you click on the button to create a user.
145      * @param mapping
146      * @param form
147      * @param request
148      * @param response
149      * @return
150      */

151     public ActionForward newUser(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
152         AuthenticationManager authenticationManager = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
153         DynaActionForm dyna = (DynaActionForm)form;
154
155         resetForm(dyna);
156
157         request.setAttribute("allPrincipals", authenticationManager.getLocalPrincipals());
158         request.setAttribute("action", "create");
159         return mapping.findForward("readUserOK");
160     }
161
162     /**
163      * create a new user.
164      * @param mapping
165      * @param form
166      * @param request
167      * @param response
168      * @return
169      */

170     public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
171         logger.debug(" into UserDispatchAction.create");
172
173         DynaActionForm dyna = (DynaActionForm)form;
174         AuthenticationManager am = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
175
176         SubjectTemplate st = new SubjectTemplate();
177
178         // Private required credentials
179
Set JavaDoc privRequiredCred = new HashSet JavaDoc();
180         addCredential(privRequiredCred, "login", (String JavaDoc)dyna.get("login"));
181         addCredential(privRequiredCred, "password", (String JavaDoc)dyna.get("password"));
182         // add private required credentials to user
183
st.setPrivateRequiredCredentials(privRequiredCred);
184
185
186         // Public required creadentials
187
Set JavaDoc publicRequiredCred = new HashSet JavaDoc();
188         addCredential(publicRequiredCred, "firstname", (String JavaDoc)dyna.get("firstname"));
189         addCredential(publicRequiredCred, "lastname", (String JavaDoc)dyna.get("lastname"));
190         addCredential(publicRequiredCred, "location", (String JavaDoc)dyna.get("location"));
191         // add public required credentials to user
192
st.setPublicRequiredCredentials(publicRequiredCred);
193
194
195         // Private optional credentials
196
Set JavaDoc privOptionalCred = new HashSet JavaDoc();
197         addCredential(privOptionalCred, "country", (String JavaDoc)dyna.get("country"));
198         addCredential(privOptionalCred, "religion", (String JavaDoc)dyna.get("religion"));
199         // add private optional credentials to user
200
st.setPrivateOptionalCredentials(privOptionalCred);
201
202
203         // Public optional credentials
204
Set JavaDoc publicOptionalCred = new HashSet JavaDoc();
205         addCredential(publicOptionalCred, "hobbies", (String JavaDoc)dyna.get("hobbies"));
206         // add public optional credentials to user
207
st.setPublicOptionalCredentials(publicOptionalCred);
208
209         // add principals
210
st.getPrincipals().clear();
211         String JavaDoc principalsNames = (String JavaDoc)dyna.get("userPrincipalsNames");
212         logger.debug(" create user: principalsNames from form ="+principalsNames);
213
214         try {
215             SubjectTemplate stClone = (SubjectTemplate)am.getDefaultSubjectTemplate().clone();
216             stClone.getPrincipals().clear();
217             addPrincipals(principalsNames, stClone.getPrincipals(), am);
218             Subject JavaDoc userCreated = am.createUser(st,stClone);
219             logger.debug("user created ="+userCreated);
220         } catch (RegistrationException e) {
221             logger.error(e.getMissingPrivateCredential());
222             logger.error(e.getMissingPublicCredential());
223             logger.error(e);
224         } catch (AuthenticationException e) {
225             logger.error(e);
226         } catch (CloneNotSupportedException JavaDoc e) {
227             logger.error(e);
228         }
229
230         return mapping.findForward("createUserOK");
231     }
232
233     /**
234      * update an user.
235      * @param mapping
236      * @param form
237      * @param request
238      * @param response
239      * @return
240      */

241     public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
242
243         DynaActionForm dyna = (DynaActionForm)form;
244         AuthenticationManager am = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
245         Subject JavaDoc user = new Subject JavaDoc();
246
247         // Private credentials
248
Set JavaDoc privCred = user.getPrivateCredentials();
249
250         addCredential(privCred, "login", (String JavaDoc)dyna.get("login"));
251         addCredential(privCred, "password", (String JavaDoc)dyna.get("password"));
252         addCredential(privCred, "country", (String JavaDoc)dyna.get("country"));
253         addCredential(privCred, "religion", (String JavaDoc)dyna.get("religion"));
254
255
256         // Public credentials
257
Set JavaDoc publicCred = user.getPublicCredentials();
258
259         addCredential(publicCred, "firstname", (String JavaDoc)dyna.get("firstname"));
260         addCredential(publicCred, "lastname", (String JavaDoc)dyna.get("lastname"));
261         addCredential(publicCred, "location", (String JavaDoc)dyna.get("location"));
262         addCredential(publicCred, "hobbies", (String JavaDoc)dyna.get("hobbies"));
263
264         // add principals
265
user.getPrincipals().clear();
266         String JavaDoc principalsNames = (String JavaDoc)dyna.get("userPrincipalsNames");
267         logger.debug("update user :principalsNames from form ="+principalsNames);
268         addPrincipals(principalsNames, user.getPrincipals(), am);
269
270         // Set identity credential
271
JGuardCredential jcred = new JGuardCredential();
272         jcred.setId("login");
273         jcred.setValue((String JavaDoc)dyna.get("oldLogin"));
274         try {
275             am.updateUser(jcred, user);
276             logger.debug("after update user content="+user);
277         } catch (AuthenticationException e) {
278             e.printStackTrace();
279         }
280
281
282         return mapping.findForward("updateUserOK");
283
284     }
285
286     /**
287      * delete an user.
288      * @param mapping
289      * @param form
290      * @param request
291      * @param response
292      * @return
293      */

294     public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
295         DynaActionForm dyna = (DynaActionForm)form;
296         AuthenticationManager am = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
297
298         Subject JavaDoc user = am.findUser((String JavaDoc)dyna.get("login"));
299
300         try {
301             am.deleteUser(user);
302         } catch (AuthenticationException e) {
303             logger.error(e.getMessage());
304         }
305
306         return mapping.findForward("deleteUserOK");
307     }
308
309     
310
311     /**
312      * reset form.
313      * @param dyna
314      */

315     private void resetForm(DynaActionForm dyna) {
316         dyna.set("login", "");
317         dyna.set("password", "");
318         dyna.set("firstname", "");
319         dyna.set("lastname", "");
320         dyna.set("location", "");
321         dyna.set("country", "");
322         dyna.set("religion", "");
323         dyna.set("hobbies", "");
324         Collection JavaDoc tempCol = (Collection JavaDoc)dyna.get("principals");
325         tempCol.clear();
326         dyna.set("principals", tempCol);
327     }
328
329     /**
330      * adds a credential to the Set.
331      * @param credentials
332      * @param id
333      * @param value
334      */

335     private void addCredential(Set JavaDoc credentials, String JavaDoc id, String JavaDoc value) {
336         if(StringUtils.isNotEmpty(value)) {
337             JGuardCredential jcred = new JGuardCredential();
338             jcred.setId(id);
339             jcred.setValue(value);
340             credentials.add(jcred);
341         }
342     }
343
344     /**
345      * adds principals to the set referenced by the String with the help of authenticationmanager.
346      * @param principalsSet
347      * @param am
348      */

349     private void addPrincipals(String JavaDoc principalNames, Set JavaDoc principalsSet, AuthenticationManager am) {
350         logger.debug("principalNames="+principalNames);
351         if(!"".equals(principalNames)) {
352             String JavaDoc[] prinNames = principalNames.split("#");
353             for(int i=0;i<prinNames.length;i++) {
354                 try {
355                     logger.debug("current principal name="+prinNames[i]);
356                     RolePrincipal principal = (RolePrincipal) am.getLocalPrincipal(prinNames[i]);
357                     if(principal == null){
358                         logger.info("local principal not found");
359                         return;
360                     }
361                     logger.debug("local principal found="+principal);
362                     principalsSet.add(principal);
363                 } catch (AuthenticationException e) {
364                     logger.error(e.getMessage());
365                 }
366             }
367         }
368     }
369     
370     public ActionForward setActiveOnRolePrincipal(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
371           String JavaDoc roleName = request.getParameter("roleName");
372           String JavaDoc applicationName = request.getParameter("applicationName");
373           boolean active = Boolean.valueOf(request.getParameter("active")).booleanValue();
374           AuthenticationManager authenticationManager = (AuthenticationManager) request.getSession().getServletContext().getAttribute(SecurityConstants.AUTHENTICATION_MANAGER);
375           HttpAuthenticationUtils auth= (HttpAuthenticationUtils)request.getSession(true).getAttribute(HttpConstants.AUTHN_UTILS);
376           try {
377             authenticationManager.setActiveOnRolePrincipal(auth.getSubject(),roleName,applicationName,active);
378         } catch (AuthenticationException e) {
379             logger.error(e.getMessage());
380         }
381           return mapping.findForward("welcome");
382      }
383 }
384
Popular Tags