KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > admin > AdminModule


1 /*
2 Copyright (c) 2003 eInnovation Inc. All rights reserved
3
4 This library is free software; you can redistribute it and/or modify it under the terms
5 of the GNU Lesser General Public License as published by the Free Software Foundation;
6 either version 2.1 of the License, or (at your option) any later version.
7
8 This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the GNU Lesser General Public License for more details.
11 */

12
13 package com.openedit.modules.admin;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Enumeration JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19
20 import javax.servlet.http.Cookie JavaDoc;
21 import javax.servlet.http.HttpServletRequest JavaDoc;
22 import javax.servlet.http.HttpServletResponse JavaDoc;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27 import com.openedit.OpenEditException;
28 import com.openedit.WebPageRequest;
29 import com.openedit.config.Configuration;
30 import com.openedit.modules.BaseModule;
31 import com.openedit.page.Page;
32 import com.openedit.page.PageRequestKeys;
33 import com.openedit.users.StringEncrypter;
34 import com.openedit.users.User;
35 import com.openedit.util.URLUtilities;
36 import com.openedit.util.strainer.Filter;
37
38 import com.openedit.modules.email.SendMailModule;
39 /**
40  * This module allows the user to view and administer the site.
41  *
42  * @author Eric Galluzzo
43  * @author Matt Avery, mavery@einnovation.com
44  */

45 public class AdminModule extends BaseModule
46 {
47     protected static final String JavaDoc COOKIE = "openedit.usermanager.autologin";
48     protected static final String JavaDoc KEY = "SomeWeirdReallyLongStringYUITYGFNERDF343dfdGDFGSDGGD";
49     protected String JavaDoc fieldImagesRoot; //used by the imagepicker
50
protected String JavaDoc fieldRootFTPURL;
51     protected static final String JavaDoc UNAME = "username";
52     protected static final String JavaDoc EMAIL = "to";
53     private static final Log log = LogFactory.getLog(AdminModule.class);
54     
55     protected SendMailModule sendMailModule;
56     public AdminModule()
57     {
58         super();
59     }
60
61     /**
62      * Sets the root FTP URL.
63      *
64      * @param rootFTPURL The root FTP URL to set
65      */

66     public void setRootFTPURL(String JavaDoc rootFTPURL)
67     {
68         if ((rootFTPURL != null) && rootFTPURL.endsWith("/"))
69         {
70             fieldRootFTPURL = rootFTPURL.substring(0, rootFTPURL.length() - 1);
71         }
72         else
73         {
74             fieldRootFTPURL = rootFTPURL;
75         }
76     }
77
78     /**
79      * Returns the root FTP URL.
80      *
81      * @return A string, which will not end in a slash, or <code>null</code> if FTP support has not
82      * been configured.
83      */

84     public String JavaDoc getRootFTPURL()
85     {
86         return fieldRootFTPURL;
87     }
88     
89     protected PasswordHelper getPasswordHelper(WebPageRequest inReq) throws OpenEditException
90     {
91         PasswordHelper passwordHelper = (PasswordHelper) inReq.getSessionValue("passwordHelper");
92         if (passwordHelper == null)
93         {
94             passwordHelper = new PasswordHelper();
95             passwordHelper.setSendMailModule(sendMailModule);
96             inReq.putSessionValue("passwordHelper", passwordHelper);
97         }
98         
99         return passwordHelper;
100     }
101     
102     public void emailPasswordReminder(WebPageRequest inReq) throws Exception JavaDoc
103     {
104         String JavaDoc e = inReq.getRequestParameter(EMAIL);
105         String JavaDoc u = inReq.getRequestParameter(UNAME);
106         if ( e == null && u == null){
107             inReq.putPageValue("commandSucceeded", "didnotexecute");
108             //log.error("Invalid information");
109
return;
110         }
111
112         User foundUser = null;
113         String JavaDoc username = null;
114         String JavaDoc email = null;
115         String JavaDoc password = null;
116         //if the user provided an email instead of a username, lookup username
117
String JavaDoc emailaddress = inReq.getRequestParameter(EMAIL);
118         if (emailaddress != null && emailaddress.length() > 0){
119             foundUser = (User)getUserManager().getUserByEmail(emailaddress);
120             if (foundUser != null){
121             }
122         }
123         
124         //If the user provided a valid username
125
username = inReq.getRequestParameter(UNAME);
126         if (username != null && foundUser == null){
127             foundUser = (User)getUserManager().getUser(username);
128         }
129         
130         if (foundUser != null){
131             email = foundUser.getEmail();
132             if (email == null || email.equals("")){
133                 inReq.putPageValue("commandSucceeded", "noemail");
134                 return;
135             }
136             //get the user's current password
137
password = foundUser.getClearPassword();
138             username = foundUser.getUserName();
139         }
140         else {
141             inReq.putPageValue("commandSucceeded", "nouser");
142             return;
143         }
144         
145         //let the passwordHelper send the password
146
PasswordHelper passwordHelper = getPasswordHelper(inReq);
147         passwordHelper.emailPasswordReminder(inReq, getPageManager(), username, password, email);
148         
149     }
150     public void allowEditing(WebPageRequest inReq) throws Exception JavaDoc
151     {
152         boolean value = false;
153         if ( inReq.getUser() != null )
154         {
155             Filter filter = inReq.getPage().getEditFilter();
156             value= ((filter == null) || filter.passes( inReq ));
157             
158         }
159         inReq.setEditable(value);
160         //Check that we already have a toolbar generator
161
/*
162         Generator pgen = inReq.getPage().getGenerator();
163         if ( !pgen.hasGenerator(getToolbarGenerator()) )
164         {
165             CompositeGenerator composite = new CompositeGenerator();
166             composite.addGenerator(pgen);
167             composite.addGenerator(getToolbarGenerator());
168             inReq.getPage().setGenerator(composite);
169         }
170         */

171     }
172     
173     public void allowViewing( WebPageRequest inReq ) throws OpenEditException
174     {
175         AllowViewing command = new AllowViewing();
176         command.setPageManager( getPageManager() );
177         
178         command.configure( inReq.getCurrentAction().getConfig(), inReq.getPage().getPageSettings() );
179         command.execute( inReq );
180     }
181     public void enforcePrivilege( WebPageRequest inReq ) throws OpenEditException
182     {
183         EnforcePrivilege command = new EnforcePrivilege();
184         command.setPageManager( getPageManager() );
185         command.configure( inReq.getCurrentAction().getConfig() , inReq.getPage().getPageSettings() );
186         command.execute( inReq );
187     }
188     public void checkForDuplicateByEmail( WebPageRequest inReq) throws Exception JavaDoc
189     {
190         String JavaDoc email = inReq.getRequiredParameter("email");
191         
192         User user = getUserManager().getUserByEmail( email );
193         if ( user != null)
194         {
195             String JavaDoc page = inReq.getCurrentAction().getConfig().getChildValue("redirectpage");
196             if ( page == null)
197             {
198                 inReq.redirect(page);
199             }
200             else
201             {
202                 inReq.putPageValue("oe-exception","Account already exists with address " + email );
203             }
204         }
205     }
206     /*
207     public void loginByEmail( WebPageRequest inReq ) throws Exception
208     {
209         String account = inReq.getRequestParameter("email");
210
211         if ( account != null )
212         {
213             User user = getUserManager().getUserByEmail( account );
214             loginAndRedirect(user,inReq);
215         }
216         else
217         {
218              String referrer = inReq.getRequest().getHeader("REFERER");
219              if ( referrer != null )
220              {
221                  //this is the original page someone might have been on
222                  inReq.putSessionValue("originalEntryPage",referrer );
223              }
224         }
225     }
226     */

227     public void login( WebPageRequest inReq ) throws Exception JavaDoc
228     {
229         String JavaDoc account = inReq.getRequestParameter("accountname");
230         String JavaDoc password = inReq.getRequestParameter("password");
231
232         if ( account != null )
233         {
234             User user = getUserManager().getUser( account );
235             if ( user == null)
236             {
237                 user = getUserManager().getUserByEmail(account);
238             }
239             if( user == null) //Allow guest user
240
{
241                 String JavaDoc groupname = inReq.getPage().get("autologingroup");
242                 if( groupname != null)
243                 {
244                     user = getUserManager().createGuestUser(account, password, groupname);
245                 }
246             }
247
248             loginAndRedirect(user,password, inReq);
249         }
250 // else
251
// {
252
// String referrer = inReq.getRequest().getHeader("REFERER");
253
// if ( referrer != null )
254
// {
255
// //this is the original page someone might have been on
256
// inReq.putSessionValue("originalEntryPage",referrer );
257
// }
258
// }
259
}
260     
261     /**
262      * @param inUser
263      * @param inReq
264      */

265     protected void loginAndRedirect(User user, String JavaDoc inPassword, WebPageRequest inReq) throws Exception JavaDoc
266     {
267         boolean userok = false;
268         String JavaDoc sendTo = inReq.getRequestParameter("loginokpage");
269
270         if ( user != null )
271         {
272             // Save our logged-in user in the session,
273
// because we use it again later.
274
if ( inPassword != null )
275             {
276                 userok = getUserManager().authenticate( user, inPassword );
277             }
278         }
279         
280         if ( userok == false )
281         {
282             //System.out.println( "User " + account + " could not be logged in" );
283
inReq.getRequest().setAttribute("oe-exception","Invalid Logon");
284             inReq.putPageValue("oe-exception","Invalid Logon");
285         }
286         else
287         {
288             inReq.putSessionValue( "user", user );
289             //user is now logged in
290
if ( sendTo == null || sendTo.trim().length() == 0)
291             {
292                 String JavaDoc sendToOld = (String JavaDoc)inReq.getSessionValue("originalEntryPage");
293                 String JavaDoc referrer = inReq.getRequest().getHeader("REFERER");
294                 if ( sendToOld != null && !sendToOld.equals(referrer))
295                 {
296                     sendTo = sendToOld;
297                 }
298                 inReq.removeSessionValue( "originalEntryPage" );
299             }
300             if ( sendTo == null )
301             {
302                 sendTo = "/index.html";
303             }
304             savePasswordAsCookie(user, inReq);
305             inReq.redirect( sendTo );
306         }
307
308     }
309
310     public void savePasswordAsCookie(User user, WebPageRequest inReq) throws OpenEditException
311     {
312         HttpServletResponse JavaDoc res = inReq.getResponse();
313         if ( res!= null)
314         {
315             String JavaDoc crypt = new StringEncrypter( StringEncrypter.DES_ENCRYPTION_SCHEME, KEY ).encrypt(user.getPassword());
316             //String home = (String)inReq.getPageValue("home");
317
Cookie JavaDoc cookie = new Cookie JavaDoc(createCookieName(inReq),user.getUserName() + "OEWITHOE" + crypt);
318             cookie.setMaxAge(Integer.MAX_VALUE);
319             cookie.setPath("/"); //http://www.unix.org.ua/orelly/java-ent/servlet/ch07_04.htm
320
res.addCookie(cookie);
321         }
322     }
323
324     public void logout( WebPageRequest inReq ) throws OpenEditException
325     {
326         User user = (User)inReq.getSessionValue("user");
327         getUserManager().logout(user);
328         
329         Enumeration JavaDoc enumeration = inReq.getSession().getAttributeNames();
330         List JavaDoc toremove = new ArrayList JavaDoc();
331         while( enumeration.hasMoreElements())
332         {
333             String JavaDoc id = (String JavaDoc)enumeration.nextElement();
334             toremove.add(id);
335         }
336         for (Iterator JavaDoc iter = toremove.iterator(); iter.hasNext();)
337         {
338             String JavaDoc id = (String JavaDoc) iter.next();
339             inReq.removeSessionValue(id);
340         }
341         
342
343 // inReq.removeSessionValue("editMode"); //legacy
344
// inReq.removeSessionValue("username"); //legacy
345
// inReq.removeSessionValue("user");
346

347         String JavaDoc referrer = inReq.getRequestParameter("editingPath");
348         Page epath = getPageManager().getPage(referrer);
349         if ( referrer == null
350                 || referrer.indexOf( "/openedit") >= 0
351                 || !epath.isHtml()
352                 || !epath.exists())
353         {
354             referrer = "/index.html";
355         }
356         removeCookie(inReq);
357         inReq.redirect( referrer );
358     }
359     
360     protected void removeCookie(WebPageRequest inReq)
361     {
362         HttpServletResponse JavaDoc res = inReq.getResponse();
363         if ( res!= null)
364         {
365             String JavaDoc home = (String JavaDoc)inReq.getPageValue("home");
366             Cookie JavaDoc cookie = new Cookie JavaDoc(createCookieName(inReq),"none");
367             cookie.setMaxAge(0);
368             cookie.setPath("/"); //http://www.unix.org.ua/orelly/java-ent/servlet/ch07_04.htm
369
res.addCookie(cookie);
370         }
371     }
372
373     public void autoLogin(WebPageRequest inReq) throws OpenEditException
374     {
375         if ( inReq.getUser() != null)
376         {
377             return;
378         }
379         if (!inReq.getPage().isHtml() )
380         {
381             return; //only deal with html requests
382
}
383         readPasswordFromCookie(inReq);
384     }
385
386     public void autoLoginFromRequest(WebPageRequest inRequest) throws OpenEditException
387     {
388         // Add the currently logged-in user (which may be null).
389
String JavaDoc username = inRequest.getRequest().getRemoteUser();
390         if( username != null)
391         {
392             User user = getUserManager().getUser(username);
393             if (user != null)
394             {
395                 inRequest.putProtectedPageValue(PageRequestKeys.USER, user);
396             }
397         }
398     }
399     
400     String JavaDoc createCookieName(WebPageRequest inReq)
401     {
402         String JavaDoc home = (String JavaDoc)inReq.getPageValue("home");
403         return COOKIE+home+"Un1qu3_str1ng";
404     }
405     
406     boolean verifyCookieName(WebPageRequest inReq, Cookie JavaDoc inCookie)
407     {
408         return inCookie.getName().startsWith(createCookieName(inReq));
409     }
410
411     protected void readPasswordFromCookie(WebPageRequest inReq) throws OpenEditException
412     {
413         //see if we have a coookie for this person with their encrypted password in it
414
HttpServletRequest JavaDoc req = inReq.getRequest();
415         if ( req != null)
416         {
417             Cookie JavaDoc[] cookies = req.getCookies();
418             if ( cookies != null)
419             {
420                 for (int i = 0; i < cookies.length; i++)
421                 {
422                     Cookie JavaDoc cook = cookies[i];
423                     if ( cook.getName() != null && verifyCookieName(inReq, cook) )
424                     {
425                         String JavaDoc uandpass = cook.getValue();
426                         if ( uandpass != null)
427                         {
428                             String JavaDoc[] units = uandpass.split("OEWITHOE");
429                             User user = getUserManager().getUser( units[0] );
430                             if ( user == null)
431                             {
432                                 log.info("User " + units[0] + " not found.");
433                                 //removeCookie(inReq);
434
cook.setMaxAge(0); //remove the cookie
435
inReq.getResponse().addCookie(cook);
436                             }
437                             else
438                             {
439                                     String JavaDoc encoded = units[1];
440                                     //String password = new String( new BASE64Decoder().decodeBuffer(encoded) );
441
String JavaDoc password = new StringEncrypter(StringEncrypter.DES_ENCRYPTION_SCHEME, KEY ).decrypt(encoded);
442                                     boolean ok = getUserManager().authenticate(user,password);
443                                     if ( ok )
444                                     {
445                                         inReq.putSessionValue( "user", user );
446                                         return;
447                                     }
448                                     else
449                                     {
450                                         log.info("Auto login did not work " + units[0] + " password " + password);
451                                         cook.setMaxAge(0); //remove the cookie
452
inReq.getResponse().addCookie(cook);
453                                     }
454                             }
455                             
456                         }
457                     }
458                 }
459             }
460         }
461     }
462
463     //These are deprecated
464
public void wrapDecoration(WebPageRequest inreq)
465     {
466         log.error("Please remove Decorate.wrapDecoration from your _site.xconf");
467     }
468     public void insertDecoration(WebPageRequest inReq) throws Exception JavaDoc
469     {
470         log.error("Please remove Decorate.insertDecoration from your _site.xconf");
471         /*
472         Page layout = inReq.getPage();
473     
474         if ( !layout.getGenerator().hasGenerator(getSearchAndReplaceGenerator()) )
475         {
476             //wrap the content with our search generator
477             CompositeGenerator composite = new CompositeGenerator();
478             composite.addGenerator(inReq.getPage().getGenerator());
479             composite.addGenerator(getSearchAndReplaceGenerator());
480             layout.setGenerator(composite);
481         }
482         */

483     }
484
485     public void forwardToSecureSocketsLayer(WebPageRequest inReq)
486     {
487         String JavaDoc host = inReq.getPage().get("hostName");
488         String JavaDoc useSecure = inReq.getPage().get("useshttps");
489         
490         if (Boolean.parseBoolean(useSecure) && host != null && inReq.getRequest() != null)
491         {
492             if ( !inReq.getRequest().isSecure() )
493             {
494                 String JavaDoc path = "https://" + host + inReq.getPathUrl();
495                 log.info("Forward to address " + path);
496                 inReq.redirect(path);
497             }
498         }
499     }
500
501     public void redirect(WebPageRequest inReq)
502     {
503         String JavaDoc path = inReq.getCurrentAction().getChildValue("redirectpath");
504         if( path == null)
505         {
506             path = inReq.getPage().get("redirectpath");
507         }
508         if (path != null && inReq.getRequest() != null)
509         {
510             URLUtilities utils = (URLUtilities)inReq.getPageValue(PageRequestKeys.URL_UTILITIES);
511             if( path.endsWith("/"))
512             {
513                 path = path.substring(0,path.length()-1);
514             }
515             List JavaDoc host = inReq.getCurrentAction().getConfig().getChildren("host");
516             if( host.size() > 0)
517             {
518                 String JavaDoc server = utils.buildRoot(); //http://localhost:8080/
519
boolean found = false;
520                 for (Iterator JavaDoc iterator = host.iterator(); iterator.hasNext();)
521                 {
522                     Configuration conf = (Configuration) iterator.next();
523                     //verify the host
524
String JavaDoc hostval = conf.getValue();
525                     log.debug("Checking [" + server + "] starts with [" + hostval + "]");
526                     if( server.startsWith(hostval))
527                     {
528                         found = true;
529                         break;
530                     }
531                 }
532                 if( !found)
533                 {
534                     log.info("Host did not match, was [" + server + "]");
535                     return;
536                 }
537             }
538             int indestpath = path.indexOf("*"); //http://xyz/*
539
if (indestpath > -1 )
540             {
541                 //this is a dynamic redirect path
542
//http://xyz/* -> http://xyz/somepage.html
543
//take off a part of the path before the *?
544
String JavaDoc begin = path.substring(0,indestpath);
545                 String JavaDoc ending = inReq.getContentPage().getName();
546
547                 String JavaDoc redirectPath = begin + ending; //this does not handle subdirectory redirects
548
if( !inReq.getPath().equals(redirectPath))
549                 {
550                     inReq.redirectPermanently(redirectPath);
551                 }
552             }
553             else if( path.startsWith("http"))
554             {
555                 String JavaDoc fixedpath = path;
556                 String JavaDoc domain = utils.siteRoot();
557                 if( domain.startsWith("https://") && !fixedpath.startsWith("https://") )
558                 {
559                     fixedpath = "https://" + path.substring("https://".length()-1, path.length());
560                 }
561                 if( !fixedpath.startsWith(domain) )
562                 {
563                     //see if it exists locally
564
if ( inReq.getContentPage().exists() )
565                     {
566                         String JavaDoc newurl = fixedpath + utils.requestPathWithArguments();
567                         inReq.redirectPermanently(newurl);
568                     }
569                     else
570                     {
571                         inReq.redirectPermanently(fixedpath);
572                     }
573                 }
574             }
575             else
576             {
577                 if( !inReq.getPath().equals(path))
578                 {
579                     inReq.redirectPermanently(path);
580                 }
581             }
582         }
583     }
584
585     public void redirectToOriginal(WebPageRequest inReq )
586     {
587         String JavaDoc editPath = inReq.getRequestParameter("editPath");
588         String JavaDoc orig = inReq.getRequestParameter("origURL");
589         if( orig != null)
590         {
591             if ( orig.indexOf("?") == -1 && editPath != null)
592             {
593                 inReq.redirect(orig + "?path=" + editPath + "&cache=false");
594             }
595             else
596             {
597                 inReq.redirect(orig);
598             }
599         }
600         else
601         {
602             //log.error("No origURL specified");
603
}
604     }
605
606     public SendMailModule getSendMailModule() {
607         return sendMailModule;
608     }
609
610     public void setSendMailModule(SendMailModule sendMailModule) {
611         this.sendMailModule = sendMailModule;
612     }
613
614
615
616 }
617
Popular Tags