KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > MMUsers


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10
11 package org.mmbase.module;
12
13 import java.util.*;
14
15 import org.mmbase.module.core.*;
16 import org.mmbase.module.builders.Properties;
17 import org.mmbase.util.*;
18
19 import org.mmbase.util.logging.Logger;
20 import org.mmbase.util.logging.Logging;
21
22 /**
23  * @javadoc
24  * @application SCAN
25  * @author Arjan Houtman
26  * @author Daniel Ockeloen
27  * @version $Id: MMUsers.java,v 1.13 2004/10/01 08:42:46 pierre Exp $
28  */

29 public class MMUsers extends ProcessorModule {
30
31     private static Logger log = Logging.getLoggerInstance(MMUsers.class.getName());
32
33     private PasswordGeneratorInterface pwgen = new PasswordGenerator ();
34     private MMBase mmbase;
35     private sessionsInterface sessions;
36     private SendMailInterface sendMail;
37
38     private MMObjectBuilder users; // Users
39
private Properties properties;
40
41     //Strings for composing an email
42
private String JavaDoc emailFrom;
43     private String JavaDoc emailReturnPath;
44     private String JavaDoc emailSubject;
45     private String JavaDoc emailBodyBegin;
46     private String JavaDoc emailBodyLogin;
47     private String JavaDoc emailBodyPasswd;
48     private String JavaDoc emailBodyEnd;
49
50     private String JavaDoc error (String JavaDoc msg) {
51         log.error(msg);
52         return "Error-> " + msg;
53     }
54
55     private String JavaDoc cleanupString(String JavaDoc str) { return str; }
56
57     // Keys not cleared by clearSessionInfo. Memo should start and end with ;
58
private static String JavaDoc excludedKeys = ";LID;FIRSTNAME;LASTNAME;EMAIL;";
59
60     private void clearSessionInfo (scanpage sp) {
61         if (sessions==null) sessions = (sessionsInterface)getModule("SESSION");
62
63         String JavaDoc sid = sp.getSessionName();
64         sessionInfo info = sessions.getSession (sp, sp.sname);
65         String JavaDoc userid = sessions.getValue (info, "USERNUMBER");
66
67         if (log.isDebugEnabled()) {
68             log.debug("Clearing session-info of user " + userid);
69         }
70         if (userid!=null) {
71             Hashtable has = getUserProperties (userid);
72             if (has != null) {
73                 for (Enumeration e = has.elements (); e.hasMoreElements (); ) {
74                     MMObjectNode node = (MMObjectNode)e.nextElement ();
75                     String JavaDoc key = node.getStringValue ("key");
76                     if ((key != null) && (excludedKeys.indexOf(";"+key+";")<0)) {
77                         if (log.isDebugEnabled()) {
78                             log.debug ("Clearing key '" + key + "'");
79                         }
80                         sessions.setValue (info, key, "");
81                     }
82                 }
83             }
84             sessions.forgetSession( userid );
85         }
86         deleteSessionSIDs( sid );
87     }
88
89 /*
90     Het creeren van een nieuwe login gaat momenteel nog door het opslaan van de nieuwe gegevens
91     (LID, EMAIL, FIRSTNAME, LASTNAME) in sessie-variabelen en vervolgens $MOD-MMUSERS-CREATELOGIN-...
92     aan te roepen. Dit gaat waarschijnlijk niet goed, omdat de 'nieuwe' sessie-variabelen tussen de
93     sessie-variabelen van de 'oude' gebruiker komen te staan en deze dus niet meer uit elkaar te houden
94     zijn. Nu kan je de nieuwe variabelen wel met een bepaald keywoord beginnen (NEWNAME, NEWEMAIL
95     etc), maar ook dan kunnen er problemen ontstaan (je moet dit dan hard incoderen, wat waarschijnlijk
96     niet gewenst is). Het creeren van de nieuwe login kan daarom het beste gebeuren via PRC-CMD-... in
97     forms. Op deze manier krijg je de nieuwe gegevens binnen en kan je eerst de sessie-gegevens van
98     de oude gebruiker
99     verwijderen alvorens je de nieuwe gegevens invoert.
100     */

101     public String JavaDoc createLogin (String JavaDoc loginname, StringTokenizer tokens, scanpage sp)
102     {
103         String JavaDoc address = getRemainingTokens( tokens );
104         if (address.equals(""))
105             return error ("CREATELOGIN-" + loginname + " needs an e-mail address");
106
107         // Cleanup name/adress
108
loginname=cleanupString(loginname);
109         address=cleanupString(address);
110
111         String JavaDoc rtn="",res;
112
113         // Check if email/account already exists
114
res=doSearchUserNumber(loginname);
115         if (res.length()==0) {
116             res=doSearchUserNumber(address);
117             if (res.length()==0) {
118
119                 // Now first delete any existing session-info, 'cause it is from the
120
// 'old' user under this SID. This is tricky right now, because the 'new'
121
// login info is also stored in the same session-info. Deleteing all the
122
// session-info will delete the new info too.
123
// WH: see clearSessionInfo for comment
124
clearSessionInfo (sp);
125
126                 String JavaDoc password = pwgen.getPassword ();
127                 int userid = createNewUser (sp, loginname, password, address);
128
129                 if (userid < 0) log.error("Couldn't create a new user!");
130                 else sendConfirmationEMail (address, loginname, password);
131                 rtn = rtn+userid;
132             } else {
133                 rtn="EMAIL";
134                 if (log.isDebugEnabled()) {
135                     log.debug("Email address is already in use");
136                 }
137             }
138         } else {
139             rtn="USER";
140             if (log.isDebugEnabled()) {
141                 log.debug("Username is already in use");
142             }
143         }
144         return rtn;
145     }
146
147     private int createNewUser (scanpage sp, String JavaDoc ln, String JavaDoc pw, String JavaDoc ad) {
148         if (users == null) users = mmbase.getMMObject ("users");
149         if (sessions==null) sessions = (sessionsInterface)getModule("SESSION");
150         String JavaDoc sid = sp.getSessionName();
151         // Create a new user-node...
152
MMObjectNode usernode = users.getNewNode ("system");
153         if (usernode == null) return -1;
154         usernode.setValue ("description", "created for SID = " + sid);
155         int id = users.insert ("system", usernode);
156         if (log.isServiceEnabled()) log.service("Created new user " + id + ", SID=" + sid);
157
158         // sessionInfo info = sessions.getSession (sp.req, sid);
159
sessionInfo info = sessions.getSession (sp, sp.sname);
160         sessions.setValue (info, "USERNUMBER", "" + id);
161         sessions.setValue (info, "PASSWD", pw);
162         sessions.setValue (info, "LID", ln);
163
164         storeValue ("" + id, "SID", sid);
165         storeValue ("" + id, "PASSWD", pw);
166         storeValue ("" + id, "LID", ln);
167
168         return id;
169     }
170
171     private boolean deleteSIDs(String JavaDoc usernumber) {
172         if (properties == null) properties = (Properties)mmbase.getMMObject("properties");
173         Enumeration e = properties.search("parent=E"+usernumber+" + key=='SID'");
174         while (e.hasMoreElements()) {
175             MMObjectNode node = (MMObjectNode) e.nextElement();
176             //properties.removeRelations(node);// Beetje overdreven, alleen in theorie kan ie rels hebbe
177
properties.removeNode(node);
178         }
179         return true;
180     }
181
182     private boolean deleteSessionSIDs(String JavaDoc sessionname) {
183         if (properties == null) properties = (Properties)mmbase.getMMObject("properties");
184         Enumeration e = properties.search("key=='SID'+ value=='"+sessionname+"'");
185         while (e.hasMoreElements()) {
186             MMObjectNode node = (MMObjectNode)e.nextElement();
187             //properties.removeRelations(node);// Beetje overdreven, alleen in theorie kan ie rels hebbe
188
properties.removeNode(node);
189         }
190         return true;
191     }
192
193     public String JavaDoc doSearchUserNumber(String JavaDoc value) {
194         if (properties == null) properties = (Properties)mmbase.getMMObject("properties");
195         Enumeration e = properties.search("key=='LID' + value=='"+value+"'");
196         if (e.hasMoreElements()) {
197             MMObjectNode node = (MMObjectNode) e.nextElement();
198             return node.getStringValue("parent");
199         }
200
201         e = properties.search("key=='EMAIL' + value=='"+value+"'");
202         if (e.hasMoreElements()) {
203             MMObjectNode node = (MMObjectNode) e.nextElement();
204             return node.getStringValue("parent");
205         }
206         return "";
207
208
209     }
210
211     private String JavaDoc getRemainingTokens( StringTokenizer tok )
212     {
213         if (!tok.hasMoreTokens())
214             return "";
215         return addRemainingTokens( tok.nextToken(), tok);
216     }
217
218     private String JavaDoc addRemainingTokens( String JavaDoc s, StringTokenizer tok )
219     {
220         while (tok.hasMoreTokens()) { s += "-"+tok.nextToken(); }
221         return s;
222     }
223
224
225     public void init () {
226         super.init ();
227         mmbase = (MMBase)getModule ("MMBASEROOT");
228
229     }
230
231     /*
232      * Store a property in the database.
233      */

234     private String JavaDoc storeValue (String JavaDoc userid, String JavaDoc key, String JavaDoc value) {
235         if (users == null) users = mmbase.getMMObject("users");
236         if (properties == null) properties = (Properties)mmbase.getMMObject("properties");
237
238         MMObjectNode usernode = users.getNode (userid);
239
240         if (usernode != null) {
241             MMObjectNode pnode = usernode.getProperty (key);
242
243             if (pnode == null) {
244                 pnode = properties.getNewNode ("system");
245                 pnode.setValue ("parent", Integer.parseInt (userid));
246                 pnode.setValue ("key", key);
247                 pnode.setValue ("value", value);
248                 pnode.setValue ("ptype", "string");
249                 properties.insert ("system", pnode);
250                 usernode.delPropertiesCache();
251                 if (log.isDebugEnabled()) {
252                     log.debug ("storeValue() storing '" + value + "' in '" + key + "' for user "+userid);
253                 }
254
255             }
256             else
257             {
258                 pnode.setValue ("value", value);
259                 pnode.setValue ("ptype", "string");
260                 pnode.commit();
261                 if (log.isDebugEnabled()) {
262                     log.debug ("storeValue() overwriting '" + value + "' in '" + key + "' for user "+userid);
263                 }
264             }
265         }
266         else {
267             return error ("MOD-MMUSERS-" + userid + "-PUT has invalid user-id");
268         }
269         return "";
270     }
271
272
273     /**
274      * <LIST GETPROPERTY PARENT=[value] FIELD=[values] PROCESSOR="MMUsers">
275      * </LIST>
276      */

277     public Vector getList(scanpage sp, StringTagger tagger, String JavaDoc value) throws ParseException{
278         StringTokenizer tokens = new StringTokenizer (value, "-\n\r");
279         String JavaDoc tok = tokens.nextToken ();
280         Vector res = new Vector ();
281
282         if (tok.equals ("GETPROPERTY") && tokens.hasMoreTokens ()) {
283             tok = tokens.nextToken ();
284
285             if (tok.equals ("PARENT") && tokens.hasMoreTokens ()) {
286                 String JavaDoc userid = tokens.nextToken ();
287                 Hashtable props = getUserProperties (userid);
288                 Vector fields = tagger.Values ("FIELD");
289                 String JavaDoc wanted = (String JavaDoc)fields.firstElement ();
290
291                 res = wanted.equals ("*")
292                     ? getListAll (props, tagger)
293                     : getListSelection (props, fields, tagger);
294             }
295             else {
296                 log.warn("MMUsers can't get property '" + tok + "'");
297             }
298         }
299         else {
300             log.warn("MMUsers can't list '" + value + "'");
301         }
302
303         return res;
304     }
305
306     private Vector getListAll (Hashtable props, StringTagger tagger) {
307         Vector v = new Vector ();
308
309         // Go through all properties...
310
for (Enumeration p = props.elements (); p.hasMoreElements (); ) {
311             MMObjectNode n = (MMObjectNode)p.nextElement ();
312             String JavaDoc key = (String JavaDoc)n.getStringValue ("key");
313             String JavaDoc type = (String JavaDoc)n.getStringValue ("ptype");
314
315             v.addElement (key);
316
317             if (type.equals ("string")) v.addElement ((String JavaDoc)n.getStringValue ("value"));
318             // Place for more types...
319
else v.addElement ("<NON-PRINTABLE>");
320         }
321
322         tagger.setValue ("ITEMS", "2"); // Both key and value
323

324         return v;
325     }
326
327     private Vector getListSelection (Hashtable props, Vector fields, StringTagger tagger)
328     {
329         Vector v = new Vector ();
330
331         // Go through all wanted-fields, and get the right property from the hashtable...
332
for (Enumeration field = fields.elements (); field.hasMoreElements (); ) {
333             String JavaDoc f = (String JavaDoc)field.nextElement ();
334             MMObjectNode node = (MMObjectNode)props.get (f);
335
336             if (node != null) {
337                 String JavaDoc type = node.getStringValue ("ptype");
338
339                 if (type.equals ("string")) v.addElement ((String JavaDoc)node.getStringValue("value"));
340                 // Place for more types...
341
else v.addElement ("<NON-PRINTABLE>");
342             }
343         }
344
345         tagger.setValue ("ITEMS", "" + fields.size ());
346
347         return v;
348     }
349
350     /**
351      * Handle a $MOD command
352      */

353     public String JavaDoc replace (scanpage sp, String JavaDoc command) {
354         StringTokenizer tokens = new StringTokenizer (command, "-\n\r");
355
356         if (tokens.hasMoreTokens ()) {
357             String JavaDoc param1 = tokens.nextToken ();
358
359             if (tokens.hasMoreTokens ()) {
360                 String JavaDoc param2 = tokens.nextToken ();
361                 if (param2.equals ("GET")) return replaceGet(param1, tokens);
362                 else if (param2.equals ("PUT")) return replacePut(param1, tokens);
363                 else if (param1.equals ("SWITCH")) return replaceSwitch(sp, param2);
364                 else if (param1.equals ("SEARCHUSERNUMBER"))
365                     return doSearchUserNumber(addRemainingTokens(param2, tokens));
366                 else if (param1.equals ("CREATELOGIN")) return createLogin (param2, tokens, sp);
367
368                 // Everything else is an error:
369
else return error ("MMUSERS-" + param1 + " has illegal parameter " + param2 + " following");
370             }
371             else return error ("MMUSERS-" + param1 + " missing parameter");
372         }
373         else return error ("MMUSERS missing parameter");
374     }
375
376     private void sendConfirmationEMail (String JavaDoc address, String JavaDoc loginname, String JavaDoc password)
377     {
378
379         // get email config and check it
380
emailFrom = getInitParameter("from");
381         if (emailFrom == null || emailFrom.equals(""))
382             log.debug ("missing init param from");
383         if (emailFrom.equals("youremail@yourcompany.nl"))
384             log.debug ("from init parameter is still default, please change!!!!");
385         emailReturnPath = getInitParameter("returnpath");
386         if (emailReturnPath == null || emailReturnPath.equals(""))
387             log.debug (" missing init param returnpath");
388         if (emailReturnPath.equals("youremail@yourcompany.nl"))
389             log.debug (" returnpath init parameter is still default, please change!!!!");
390         emailSubject = getInitParameter("subject");
391         if (emailSubject == null || emailSubject.equals(""))
392             log.debug ("missing init param subject");
393         emailBodyBegin = getInitParameter("bodybegin");
394         if (emailBodyBegin == null || emailBodyBegin.equals(""))
395             log.debug ("missing init param bodybegin");
396         emailBodyLogin = getInitParameter("bodylogin");
397         if (emailBodyLogin == null || emailBodyBegin.equals(""))
398             log.debug ("missing init param bodylogin");
399         emailBodyPasswd = getInitParameter("bodypasswd");
400         if (emailBodyPasswd == null || emailBodyPasswd.equals(""))
401             log.debug ("missing init param bodypasswd");
402         emailBodyEnd = getInitParameter("bodyend");
403         if (emailBodyEnd == null || emailBodyEnd.equals(""))
404             log.debug ("missing init param bodyend");
405
406         if (log.isServiceEnabled()) {
407             log.service("Sending e-mail to " + address + " concerning login '" + loginname + "' and password '" + password + "'");
408         }
409         if (sendMail == null) sendMail = (SendMailInterface)getModule("sendmail");
410         if (sendMail == null) {
411             log.error("MMUsers ERROR CANNOT GET MODULE SendMail!");
412             log.error("MMUsers could not send mail to " + address + " for login name " + loginname
413                                +" with password "+ password);
414             return;
415         }
416
417         Hashtable headers = new Hashtable( 3 );
418
419         headers.put("From", emailFrom);
420         headers.put("Return-path", emailReturnPath);
421         headers.put("Subject", emailSubject);
422         String JavaDoc body = emailBodyBegin + "\n\n" + emailBodyLogin + loginname + "\n" + emailBodyPasswd + password + "\n\n" + emailBodyEnd;
423         sendMail.sendMail(emailFrom, address, body, headers);
424
425
426         }
427
428     // new version from daniel, now uses the getproperties in each node
429
// and uses its cache (general mmobjectnode cache).
430

431     private Hashtable getUserProperties (String JavaDoc userid) {
432         // need a builder to obtain the usernode and its properties
433
if (users == null) users = mmbase.getMMObject ("users");
434
435         // obtain the correct node so we can get its hashtable of properties nodes
436
MMObjectNode usernode = (MMObjectNode)users.getNode(userid);
437
438         if (usernode!=null) {
439             Hashtable properties = usernode.getProperties();
440             return properties;
441         } else {
442             log.warn("MMUsers -> getUserProperties not a valid user = " + userid);
443             return null;
444         }
445     }
446
447     private String JavaDoc replaceGet (String JavaDoc userid, StringTokenizer tokens) {
448         String JavaDoc res = "";
449
450         if (!tokens.hasMoreTokens())
451             return error("MOD-MMUSERS-" + userid + "-GET missing KEY param");
452         String JavaDoc key = tokens.nextToken();
453         // obtain the users builder
454
if (users==null) users = mmbase.getMMObject ("users");
455         // obtain the user node
456
MMObjectNode usernode=users.getNode(userid);
457         if (usernode == null)
458             return error("MOD-MMUSERS-" + userid + "-GET: usernode not found");
459
460         usernode.getProperties();
461         // we have the user node, get the properties node for this key
462
MMObjectNode pnode=usernode.getProperty(key);
463         if (pnode == null)
464         {
465             if (log.isDebugEnabled()) {
466                 log.debug( "MOD-MMUSERS-" + userid + "-GET-"+key+": key not found");
467             }
468             return "";
469         }
470         String JavaDoc type = pnode.getStringValue ("ptype");
471         String JavaDoc value = pnode.getStringValue ("value");
472         if (type.equals ("string")) res = value; else res = "<NON-PRINTABLE>";
473         if (log.isDebugEnabled()) {
474             log.debug( "" + userid + " " + res);
475         }
476         return res;
477     }
478
479     private String JavaDoc replacePut (String JavaDoc userid, StringTokenizer tokens) {
480         if (!tokens.hasMoreTokens ())
481             return error ("MOD-MMUSERS-" + userid + "PUT/ADD missing KEY");
482
483         String JavaDoc key = tokens.nextToken ();
484         String JavaDoc value = getRemainingTokens( tokens );
485         return storeValue (userid, key, value);
486     }
487
488     /*
489         Zoals alles nu geimplementeerd is, moet er voorzichtig worden omgegaan
490         met het verwijderen van sessie-info. Dit omdat bij het creeren van een
491         nieuwe login de nieuwe gegevens in dezelfde sessie-info worden gezet.
492         WH: Added excludedKeys in method clearSessionInfo. Assumptions is that
493         you will set them properly before creating or switching a login
494     */

495     private String JavaDoc replaceSwitch(scanpage sp, String JavaDoc newUserID) {
496         if (sessions==null) sessions = (sessionsInterface)getModule("SESSION");
497
498         // $MOD-MMUSERS-SWITCH-1211212 (number is user to switch too)
499
String JavaDoc sid = sp.getSessionName();
500         // sessionInfo info = sessions.getSession (sp.req, sid);
501
sessionInfo info = sessions.getSession (sp,sp.sname);
502         String JavaDoc oldUserID = sessions.getValue (info, "USERNUMBER");
503
504         if (log.isDebugEnabled()) {
505             log.debug("Switch Info from " + oldUserID +" to "+newUserID);
506         }
507
508         if (!newUserID.equals(oldUserID))
509             clearSessionInfo( sp );
510
511         // remove all the linked SID's from the new usernode
512
deleteSIDs( newUserID );
513
514         // link the current SID to this user
515
storeValue( newUserID, "SID", sid );
516         // oke now lets set the new values
517
sessions.setValue(info,"USERNUMBER",newUserID);
518
519         Hashtable has2=getUserProperties(newUserID);
520         if (has2 == null) {
521             log.warn("SWITCH: newuser " + newUserID + " has no properties!");
522             return "";
523         }
524         for (Enumeration e = has2.elements(); e.hasMoreElements (); ) {
525             sessions.setValueFromNode( info, (MMObjectNode)e.nextElement());
526         }
527         return "";
528     }
529
530     /**
531      */

532     public String JavaDoc getModuleInfo () {
533         return "Support routines for MMUsers, by Daniel Ockeloen & Arjan Houtman";
534     }
535
536     public void reload () {
537         mmbase = (MMBase)getModule ("MMBASEROOT");
538     }
539
540 }
541
542
Popular Tags