KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > za > org > coefficient > modules > user > UserAdmin


1 /*
2  * Coefficient - facilitates project based collaboration
3  * Copyright (C) 2003, Dylan Etkin, CSIR icomtek
4  * PO Box 395
5  * Pretoria 0001, RSA
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19
20 package za.org.coefficient.modules.user;
21
22 import net.sf.hibernate.Hibernate;
23 import net.sf.hibernate.HibernateException;
24 import net.sf.hibernate.StaleObjectStateException;
25 import net.sf.hibernate.type.Type;
26
27 import za.org.coefficient.authentication.CoefficientUser;
28 import za.org.coefficient.authentication.Role;
29 import za.org.coefficient.core.Constants;
30 import za.org.coefficient.interfaces.CoefficientContext;
31 import za.org.coefficient.modules.BaseModule;
32 import za.org.coefficient.util.common.HibernatePager;
33 import za.org.coefficient.util.common.MailUtil;
34 import za.org.coefficient.util.common.InvokerFactory;
35 import net.sf.hibernate.util.HibernateUtil;
36 import za.org.coefficient.util.ejb.SecurityUtil;
37 import za.org.coefficient.util.ejb.VelocityScreenUtil;
38
39 import java.util.ArrayList JavaDoc;
40 import java.util.Arrays JavaDoc;
41 import java.util.HashMap JavaDoc;
42 import java.util.TreeSet JavaDoc;
43 import java.util.List JavaDoc;
44 import java.util.Locale JavaDoc;
45 import java.util.Random JavaDoc;
46 import java.util.TimeZone JavaDoc;
47
48 /**
49  * @pojo2ejb.class
50  * name="UserAdmin"
51  * jndi-prefix="za/org/coefficient/admin/"
52  * interface-extends="za.org.coefficient.interfaces.Module"
53  * interface-local-extends="za.org.coefficient.interfaces.ModuleLocal"
54  *
55  * @web.resource-env-ref
56  * name="za/org/coefficient/admin/UserAdmin"
57  * type="za.org.coefficient.modules.user.UserAdmin"
58  * @web.resource-env-ref
59  * name="UserAdmin"
60  * type="za.org.coefficient.modules.user.UserAdmin"
61  */

62 public class UserAdmin extends BaseModule {
63     //~ Static fields/initializers =============================================
64

65     public static final String JavaDoc CONFIRMED_USER = "__confirmed_user_sess_str";
66
67     private static final String JavaDoc USER_PAGER = "__site_user_pager_";
68     private static final String JavaDoc MESSAGE_1 =
69         "Thank you for registering on the " + Constants.CFG_SITENAME
70         + " web site. You have account with username '";
71     private static final String JavaDoc MESSAGE_2 =
72         "' created for you. In order to complete your registration, visit the following url:\n \n ";
73     private static final String JavaDoc SUBJECT =
74         Constants.CFG_SITENAME + " Account Registration";
75
76     //~ Methods ================================================================
77

78     public List JavaDoc getAllUsers() {
79         List JavaDoc users = null;
80         try {
81             users =
82                 HibernateUtil.find("from " + CoefficientUser.class.getName()
83                     + " as pe_user where pe_user.active = ? "
84                     + "order by pe_user.userName", new Boolean JavaDoc(true),
85                     Hibernate.BOOLEAN);
86         } catch (HibernateException he) {
87             he.printStackTrace();
88         }
89
90         return users;
91     }
92
93     public String JavaDoc getMainMethod() {
94         return "editUsers";
95
96         //return "enterUserInfo";
97
}
98
99     public String JavaDoc getModuleDescription() {
100         return "This module allows for user creation, editing, and deletion";
101     }
102
103     public String JavaDoc getModuleDisplayName() {
104         return "User Administration";
105     }
106
107     public List JavaDoc getUsersWithSystemRole(Role role) {
108         List JavaDoc users = null;
109         try {
110             Object JavaDoc [] vals = new Object JavaDoc [] {new Long JavaDoc(role.getRoleValue()),
111                                             new Boolean JavaDoc(true)};
112             Type [] types = new Type[] {Hibernate.LONG, Hibernate.BOOLEAN};
113             users =
114                 HibernateUtil.find("from " + CoefficientUser.class.getName()
115                     + " as pe_user where "
116                     + "pe_user.systemRole.roleValue = ? and pe_user.active = ? "
117                     + "order by pe_user.userName",
118                     vals, types);
119         } catch (HibernateException he) {
120             he.printStackTrace();
121         }
122
123         return users;
124     }
125
126     public String JavaDoc canExecuteForRole(CoefficientContext ctx, String JavaDoc methodName,
127         Role usersHighestRole) {
128         if ((usersHighestRole.getRoleValue() == SecurityUtil.GUEST_ROLE_VAL)
129             && (methodName.equals("savePassword")
130             || methodName.equals("changePassword"))) {
131             return "You must be logged in to change a password";
132         } else if ((usersHighestRole.getRoleValue() != SecurityUtil.SITE_ADMIN_ROLE_VAL)
133             && (methodName.equals("editUsers")
134             || methodName.equals("removeUser")
135             || methodName.equals("changeUserRole"))) {
136             return "Only a site administrator can admin site members";
137         } else {
138             return null;
139         }
140     }
141
142     public CoefficientContext changePassword(CoefficientContext ctx) {
143         HashMap JavaDoc map = new HashMap JavaDoc();
144         map.put("user", ctx.getCurrentUser());
145         StringBuffer JavaDoc sb =
146             VelocityScreenUtil.getProcessedScreen("password.vm", map);
147
148         // Set the html into the context
149
ctx.setModuleContent(sb.toString(), getModuleDisplayName());
150         return ctx;
151     }
152
153     public CoefficientContext changeUserRole(CoefficientContext ctx)
154         throws HibernateException {
155         Long JavaDoc userId = ctx.getParameterAsLong("userId");
156         long version = ctx.getParameterAsLongPrimitive("version", -1);
157         if (userId == null) {
158             ctx.setError("userId is required to change roles");
159         }
160         if (!ctx.isError()) {
161             CoefficientUser user =
162                 (CoefficientUser) HibernateUtil.load(CoefficientUser.class,
163                     userId);
164
165             if (user.getSystemRole()
166                     .getRoleValue() == SecurityUtil.SITE_ADMIN_ROLE_VAL) {
167                 // do a check to make sure this is not the last site admin
168
if (SecurityUtil.getUsersWithSystemRole(user.getSystemRole())
169                                 .size() > 1) {
170                     if (user.getVersion() == version) {
171                         user.setSystemRole(SecurityUtil.getRoleForValue(
172                                 SecurityUtil.SITE_MEMBER_ROLE_VAL));
173                     } else {
174                         throw new StaleObjectStateException(user.getClass(),
175                             user.getId());
176                     }
177                 } else {
178                     ctx.setError(
179                         "There must be at least one site administrator");
180                 }
181             } else if (user.getSystemRole()
182                            .getRoleValue() == SecurityUtil.SITE_MEMBER_ROLE_VAL) {
183                 if (user.getVersion() == version) {
184                     user.setSystemRole(SecurityUtil.getRoleForValue(
185                             SecurityUtil.SITE_ADMIN_ROLE_VAL));
186                 } else {
187                     throw new StaleObjectStateException(user.getClass(),
188                         user.getId());
189                 }
190             }
191
192             if (!ctx.isError()) {
193                 // Save the user
194
HibernateUtil.saveOrUpdate(user);
195                 ctx.setForward("userAdmin");
196             }
197         }
198         return ctx;
199     }
200
201     public CoefficientContext confirmUser(CoefficientContext ctx) {
202         Long JavaDoc confId = ctx.getParameterAsLong("confId", -1);
203         if (confId.longValue() > 0) {
204             try {
205                 ArrayList JavaDoc users =
206                     new ArrayList JavaDoc(HibernateUtil.find("from "
207                             + CoefficientUser.class.getName()
208                             + " as pe_user where pe_user.confirmationId = ? ",
209                             confId, Hibernate.LONG));
210                 if (users.size() == 1) {
211                     CoefficientUser user = (CoefficientUser) users.get(0);
212                     user.setActive(true);
213                     HibernateUtil.saveOrUpdate(user);
214                     ctx.setModuleContent("Authorization complete, you may now login",
215                         getModuleDisplayName());
216                     ctx.setSessionAttribute(CONFIRMED_USER, user);
217                 } else {
218                     ctx.setError("Could not find the confirmation id");
219                 }
220             } catch (HibernateException he) {
221                 he.printStackTrace();
222             }
223         } else {
224             ctx.setError("No confirmation id provided");
225         }
226         return ctx;
227     }
228
229     public CoefficientContext editUsers(CoefficientContext ctx) throws Exception JavaDoc {
230         HibernatePager hp = null;
231         if ((ctx.getParameter("userName") != null)
232             && !ctx.getParameter("userName")
233                    .trim()
234                    .equals("")) {
235             hp = (HibernatePager) ctx.getSessionAttribute(USER_PAGER);
236             if (hp == null) {
237                 ctx.setError("Invalid operation");
238             } else {
239                 HashMap JavaDoc searchParams = new HashMap JavaDoc();
240                 searchParams.put("active", new Boolean JavaDoc(true));
241                 searchParams.put("userName", ctx.getParameter("userName"));
242                 searchParams.put("systemRole.roleValue",
243                     new Long JavaDoc(SecurityUtil.SITE_MEMBER_ROLE_VAL));
244                 hp.setAndSearchParams(searchParams);
245             }
246         } else if (ctx.getParameter("next") != null) {
247             hp = (HibernatePager) ctx.getSessionAttribute(USER_PAGER);
248             if (hp == null) {
249                 ctx.setError("Invalid operation");
250             } else {
251                 hp.next();
252             }
253         } else if (ctx.getParameter("previous") != null) {
254             hp = (HibernatePager) ctx.getSessionAttribute(USER_PAGER);
255             if (hp == null) {
256                 ctx.setError("Invalid operation");
257             } else {
258                 hp.previous();
259             }
260         } else if (ctx.getParameter("page") != null) {
261             hp = (HibernatePager) ctx.getSessionAttribute(USER_PAGER);
262             if (hp == null) {
263                 ctx.setError("pager does not exist");
264             } else {
265                 hp.goToPage(ctx.getParameterAsInteger("page").intValue());
266             }
267         } else {
268             HashMap JavaDoc searchParams = new HashMap JavaDoc();
269             searchParams.put("active", new Boolean JavaDoc(true));
270             searchParams.put("systemRole.roleValue",
271                 new Long JavaDoc(SecurityUtil.SITE_MEMBER_ROLE_VAL));
272             hp = new HibernatePager(CoefficientUser.class, "userName",
273                     Constants.MAX_ELEMENTS_PER_PAGE, searchParams);
274         }
275
276         if (!ctx.isError()) {
277             HashMap JavaDoc map = new HashMap JavaDoc();
278             map.put("module", this);
279             map.put("admins",
280                 SecurityUtil.getUsersWithSystemRole(
281                     SecurityUtil.getRoleForDescription(
282                         SecurityUtil.SITE_ADMIN_ROLE_DESC)));
283             map.put("userPager", hp);
284             StringBuffer JavaDoc sb =
285                 VelocityScreenUtil.getProcessedScreen("selectUser.vm", map);
286             ctx.setSessionAttribute(USER_PAGER, hp);
287
288             // Return the html since we are a child of the project module
289
ctx.setModuleContent(sb.toString(), getModuleDisplayName());
290         }
291         return ctx;
292     }
293
294     public CoefficientContext enterUserInfo(CoefficientContext ctx) {
295         HashMap JavaDoc map = new HashMap JavaDoc();
296         if (ctx.getCurrentUser() != null) {
297             map.put("user", ctx.getCurrentUser());
298         }
299         TreeSet JavaDoc languages = new TreeSet JavaDoc();
300         Locale JavaDoc [] locales = Locale.getAvailableLocales();
301         for(int i = 0; i < locales.length; i++) {
302             languages.add(locales[i].getDisplayLanguage());
303         }
304         map.put("languages", languages);
305         map.put("defaultLang", Locale.getDefault().getDisplayLanguage());
306         TreeSet JavaDoc timezones = new TreeSet JavaDoc();
307         String JavaDoc [] zones = TimeZone.getAvailableIDs();
308         for(int i = 0; i < zones.length; i++) {
309             timezones.add(zones[i]);
310         }
311         map.put("timezones", timezones);
312         map.put("defaultTimeZone", TimeZone.getDefault().getID());
313         StringBuffer JavaDoc sb =
314             VelocityScreenUtil.getProcessedScreen("userInfoPrompt.vm", map);
315
316         // Set the html into the context
317
ctx.setModuleContent(sb.toString(), getModuleDisplayName());
318         return ctx;
319     }
320
321     public CoefficientUser findWorkflowUser() throws Exception JavaDoc {
322         CoefficientUser workflowUser = null;
323         List JavaDoc users =
324             HibernateUtil.find("FROM " + CoefficientUser.class.getName()
325                 + " as pe_user where pe_user.fullName = ?", "Workflow User",
326                 Hibernate.STRING);
327         if (users.size() == 1) {
328             workflowUser = (CoefficientUser) users.get(0);
329         }
330
331         return workflowUser;
332     }
333
334     public CoefficientUser findUserForName(String JavaDoc userName)
335         throws Exception JavaDoc
336     {
337         CoefficientUser workflowUser = null;
338         List JavaDoc users =
339             HibernateUtil.find("FROM " + CoefficientUser.class.getName()
340                 + " as pe_user where pe_user.fullName = ?", userName,
341                 Hibernate.STRING);
342         if (users.size() == 1) {
343             workflowUser = (CoefficientUser) users.get(0);
344         }
345
346         return workflowUser;
347     }
348
349     public CoefficientContext removeUser(CoefficientContext ctx) throws HibernateException {
350         Long JavaDoc userId = ctx.getParameterAsLong("userId");
351         long version = ctx.getParameterAsLongPrimitive("version", -1);
352         if (userId == null) {
353             ctx.setError("userId is required to delete a member");
354         }
355         if (!ctx.isError()) {
356             CoefficientUser user =
357                 (CoefficientUser) HibernateUtil.load(CoefficientUser.class,
358                     userId);
359
360             // do a check to make sure this is not the last site admin
361
if ((user.getSystemRole()
362                      .getRoleValue() == SecurityUtil.SITE_ADMIN_ROLE_VAL)
363                 && (SecurityUtil.getUsersWithSystemRole(user.getSystemRole())
364                                 .size() == 1)) {
365                 ctx.setError("There must be at least one site administrator");
366             } else {
367                 if (user.getVersion() == version) {
368                     user.setActive(false);
369                 } else {
370                     throw new StaleObjectStateException(user.getClass(),
371                         user.getId());
372                 }
373             }
374             if (!ctx.isError()) {
375                 HibernateUtil.saveOrUpdate(user);
376                 // find any project memeberships for the user and delete them
377
try {
378                     InvokerFactory.getInvoker()
379                         .invokeMethodOnModule("MemberAdmin",
380                                               "removeAllProjectMembershipFor",
381                                               new Object JavaDoc[]{user});
382                 } catch (Exception JavaDoc e) {
383                     // not much we can do about this
384
e.printStackTrace();
385                 }
386                 ctx.setForward("userAdmin");
387             }
388         }
389         return ctx;
390     }
391
392     public CoefficientContext savePassword(CoefficientContext ctx) throws HibernateException {
393         CoefficientUser user = ctx.getCurrentUser();
394         String JavaDoc oldPassword =
395             new String JavaDoc(SecurityUtil.md5AsHexString(ctx.getParameter(
396                         "oldPassword")));
397         if (oldPassword.equals(user.getPassword())) {
398             String JavaDoc password =
399                 new String JavaDoc(SecurityUtil.md5AsHexString(ctx.getParameter(
400                             "password1")));
401             user.setPassword(password);
402             HibernateUtil.saveOrUpdate(user);
403             ctx.setSessionAttribute(Constants.USER_SESSION_STRING, user);
404             ctx.setModuleContent("password successfully changed!",
405                 getModuleDisplayName());
406         } else {
407             ctx.setError("The old password is not correct");
408             this.changePassword(ctx);
409         }
410         return ctx;
411     }
412
413     public CoefficientContext saveUser(CoefficientContext ctx) throws HibernateException {
414         CoefficientUser user = null;
415         Long JavaDoc id = ctx.getParameterAsLong("id", -1);
416         long confId = -1;
417         if (ctx.getCurrentUser() != null) {
418             user = ctx.getCurrentUser();
419         } else {
420             user = new CoefficientUser();
421
422             // A user always should start out false until confirmed by email
423
user.setActive(false);
424
425             // Generate the unique conf id and fire off and email
426
confId =
427                 Math.abs(new Random JavaDoc(System.currentTimeMillis()).nextLong());
428             user.setConfirmationId(confId);
429             
430             
431
432             // Handle password stuff our self
433
String JavaDoc password =
434                 new String JavaDoc(SecurityUtil.md5AsHexString(ctx.getParameter(
435                             "password1")));
436             user.setPassword(password);
437
438             // set the roles correctly
439
user.setSystemRole(SecurityUtil.getRoleForDescription(
440                     SecurityUtil.SITE_MEMBER_ROLE_DESC));
441         }
442
443         // populate the object from the request
444
ctx.setProperties(user);
445         
446         //pvz: set the aliasEmail address using the userName and the MAIL_DOMAIN_NAME from the admin configuration.
447
user.setAliasEmail(user.getUserName()+"@"+Constants.ALIAS_MAIL_HOST_ADDRESS);
448         
449
450         if (ctx.getParameter("hideInformation") != null) {
451             user.setHideInformation(true);
452         } else {
453             user.setHideInformation(false);
454         }
455
456         try {
457             HibernateUtil.saveOrUpdate(user);
458         } catch (HibernateException he) {
459             if (he instanceof StaleObjectStateException) {
460                 throw he;
461             } else {
462                 he.printStackTrace();
463                 ctx.setError(user.getUserName() + ", username is already in use, we could not create the new user.");
464             }
465         }
466
467         if (id.longValue() > 0) {
468             ctx.setSessionAttribute(Constants.USER_SESSION_STRING, user);
469         }
470
471         if (!ctx.isError()) {
472             boolean success = true;
473             if (confId > 0) {
474                 // Send the confirmation email
475
String JavaDoc link =
476                     ctx.getRequestURL()
477                     + "?module=userAdmin&op=confirmUser&confId=" + confId;
478                 success =
479                     MailUtil.sendEmail(MESSAGE_1 + user.getUserName()
480                         + MESSAGE_2 + "<a target='_blank' HREF='" + link + "'>"
481                         + link + "</a>", SUBJECT, user.getEmail(), null);
482             }
483
484             // Set the html into the context
485
if (success) {
486                 if (ctx.getCurrentUser() != null) {
487                     ctx.setModuleContent("The user was successfully saved",
488                         getModuleDisplayName());
489                 } else {
490                     ctx.setModuleContent("Your user request has been submitted, you will receive an email confirmation with instructions you must follow before your account is enabled",
491                         getModuleDisplayName());
492                 }
493             } else {
494                 ctx.setError("unable to send an email confirmation");
495
496                 // TODO: Rollback
497
}
498         }
499         return ctx;
500     }
501
502     public CoefficientContext viewUserInfo(CoefficientContext ctx) throws Exception JavaDoc {
503         HashMap JavaDoc map = new HashMap JavaDoc();
504         Long JavaDoc userId = ctx.getParameterAsLong("user", -1);
505         if (userId.longValue() > 0) {
506             CoefficientUser user =
507                 (CoefficientUser) HibernateUtil.load(CoefficientUser.class,
508                     userId);
509             map.put("user", user);
510             if (ctx.getProject() != null) {
511                 map.put("project", ctx.getProject());
512             }
513             if (!user.getHideInformation()) {
514                 StringBuffer JavaDoc sb =
515                     VelocityScreenUtil.getProcessedScreen("viewUserInfo.vm", map);
516                 ctx.setModuleContent(sb.toString(), getModuleDisplayName());
517             } else {
518                 StringBuffer JavaDoc sb =
519                     VelocityScreenUtil.getProcessedScreen("privacy.vm", map);
520                 ctx.setModuleContent(sb.toString(), getModuleDisplayName());
521             }
522         } else {
523             ctx.setError("You must provide a userId to view a user");
524         }
525         return ctx;
526     }
527 }
528
Popular Tags