KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > login > Login_Engine


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 // EV 23.01.20001
14

15 package org.jahia.engines.login;
16
17 import org.jahia.bin.Jahia;
18 import org.jahia.data.JahiaData;
19 import org.jahia.data.events.JahiaEvent;
20 import org.jahia.engines.EngineToolBox;
21 import org.jahia.engines.JahiaEngine;
22 import org.jahia.engines.core.Core_Engine;
23 import org.jahia.exceptions.JahiaException;
24 import org.jahia.exceptions.JahiaSessionExpirationException;
25 import org.jahia.params.ParamBean;
26 import org.jahia.registries.ServicesRegistry;
27 import org.jahia.services.pages.ContentPage;
28 import org.jahia.services.pages.JahiaPage;
29 import org.jahia.services.pages.JahiaPageBaseService;
30 import org.jahia.services.sites.JahiaSite;
31 import org.jahia.services.usermanager.JahiaGroup;
32 import org.jahia.services.usermanager.JahiaGroupManagerService;
33 import org.jahia.services.usermanager.JahiaUser;
34 import org.jahia.services.usermanager.JahiaUserManagerService;
35 import org.jahia.settings.SettingsBean;
36 import org.jahia.utils.JahiaString;
37
38 import javax.servlet.http.Cookie JavaDoc;
39 import javax.servlet.http.HttpServletResponse JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.Properties JavaDoc;
42 import java.util.Set JavaDoc;
43 import java.util.Vector JavaDoc;
44
45 public class Login_Engine implements JahiaEngine {
46
47     /** Engine's name. */
48     public static final String JavaDoc ENGINE_NAME = "login";
49
50     /** Logger instance */
51     private static final org.apache.log4j.Logger logger =
52             org.apache.log4j.Logger.getLogger (Login_Engine.class);
53
54     private static Login_Engine instance = null;
55
56
57     private static final String JavaDoc LOGIN_JSP = "login";
58     private static final String JavaDoc BADLOGIN_JSP = "bad_login";
59     private static final String JavaDoc CLOSE_JSP = "login_close";
60
61     private EngineToolBox toolBox;
62
63
64     /**
65      * constructor
66      */

67     private Login_Engine () {
68         logger.debug ("***** Starting " + Login_Engine.class.getName () + " engine *****");
69         toolBox = EngineToolBox.getInstance ();
70     }
71
72
73     /**
74      * returns a single instance of the object
75      */

76     public static synchronized Login_Engine getInstance () {
77         if (instance == null) {
78             instance = new Login_Engine ();
79         }
80         return instance;
81     }
82
83
84     /**
85      * authorises engine render
86      */

87     public boolean authoriseRender (ParamBean jParams) {
88         return true; // always allowed to render login
89
}
90
91
92     /**
93      * renders link to pop-up window
94      */

95     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
96             throws JahiaException {
97         String JavaDoc theUrl = jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING);
98         return theUrl;
99     }
100
101
102     /**
103      * specifies if the engine needs the JahiaData object
104      */

105     public boolean needsJahiaData (ParamBean jParams) {
106         return false;
107     }
108
109
110     /**
111      * handles the engine actions
112      *
113      * @param jParams a ParamBean object
114      * @param jData a JahiaData object (not mandatory)
115      */

116     public void handleActions (ParamBean jParams, JahiaData jData)
117             throws JahiaException,
118             JahiaSessionExpirationException {
119         // initalizes the hashmap
120
HashMap JavaDoc engineMap = new HashMap JavaDoc ();
121         initEngineMap (jParams, engineMap);
122
123         processScreen (jParams, engineMap);
124
125         // displays the screen
126
toolBox.displayScreen (jParams, engineMap);
127
128     }
129
130     /**
131      * Retrieve the engine name.
132      *
133      * @return the engine name.
134      */

135     public final String JavaDoc getName () {
136         return ENGINE_NAME;
137     }
138
139
140     /**
141      * prepares the screen requested by the user
142      *
143      * @param jParams a ParamBean object
144      */

145     public void processScreen (ParamBean jParams, HashMap JavaDoc engineMap)
146             throws JahiaException,
147             JahiaSessionExpirationException {
148
149         logger.debug ("started");
150
151         // gets the actual screen
152
// screen can be "edit" or "save"
153
String JavaDoc theScreen = jParams.getRequest ().getParameter ("screen");
154         if (theScreen == null) {
155             theScreen = "edit";
156         }
157
158         boolean ok = false;
159         JahiaUser theUser = null;
160
161         String JavaDoc username = jParams.getRequest ().getParameter ("username");
162         String JavaDoc password = jParams.getRequest ().getParameter ("password");
163
164         if ((username == null) || (password == null)) {
165             return;
166         } else {
167             if (theScreen.equals ("save")) {
168                 ServicesRegistry theRegistry = ServicesRegistry.getInstance ();
169                 if (theRegistry != null) {
170                     JahiaUserManagerService theService = theRegistry.getJahiaUserManagerService ();
171                     if (theService != null) {
172
173                         // Check if the user has site access ( even though it is not a user of this site )
174
theUser = ServicesRegistry.getInstance ()
175                                 .getJahiaSiteUserManagerService ()
176                                 .getMember (jParams.getSiteID (), username);
177                         if (theUser != null) {
178                             if (theUser.verifyPassword (password)) {
179                                 ok = true;
180                             } else {
181                                 JahiaException je = new JahiaException ("Login error",
182                                         "User " + username + " entered bad password",
183                                         JahiaException.SECURITY_ERROR,
184                                         JahiaException.WARNING_SEVERITY);
185                                 logger.error (
186                                         "Couldn't validate password for user " +
187                                         theUser.getUserKey () +
188                                         "!");
189                             }
190                         }
191                     }
192                 }
193             }
194         }
195
196         if (ok) {
197             logger.debug ("User " + theUser.getUsername () + " logged in.");
198             // jParams.invalidateSession(); // this is necessary to remove references to old objects
199
jParams.purgeSession ();
200             jParams.setUser (theUser);
201
202             String JavaDoc useCookie = jParams.getRequest ().getParameter ("useCookie");
203             if ((useCookie != null) && ("on".equals(useCookie))) {
204                 // the user has indicated he wants to use cookie authentification
205
// now let's create a random identifier to store in the cookie.
206
SettingsBean settingsBean = Jahia.getSettings();
207                 String JavaDoc cookieUserKey = null;
208                 // now let's look for a free random cookie value key.
209
while (cookieUserKey == null) {
210                     cookieUserKey = JahiaString.generateRandomString(settingsBean.
211                         getCookieAuthIDLength());
212                     Properties JavaDoc searchCriterias = new Properties JavaDoc();
213                     searchCriterias.setProperty(settingsBean.
214                                                 getCookieAuthUserPropertyName(),
215                                                 cookieUserKey);
216                     Set JavaDoc foundUsers = ServicesRegistry.getInstance().
217                                      getJahiaUserManagerService().searchUsers(
218                         jParams.getSiteID(), searchCriterias);
219                     if (foundUsers.size() > 0) {
220                         cookieUserKey = null;
221                     }
222                 }
223                 // let's save the identifier for the user in the database
224
theUser.setProperty(settingsBean.getCookieAuthUserPropertyName(), cookieUserKey);
225                 // now let's save the same identifier in the cookie.
226
Cookie JavaDoc authCookie = new Cookie JavaDoc(settingsBean.getCookieAuthCookieName(), cookieUserKey);
227                 authCookie.setPath(jParams.getRequest().getContextPath());
228                 authCookie.setMaxAge(settingsBean.getCookieAuthMaxAgeInSeconds());
229                 HttpServletResponse JavaDoc realResponse = jParams.getRealResponse();
230                 realResponse.addCookie(authCookie);
231             }
232
233             String JavaDoc loginChoice = jParams.getRequest ().getParameter ("loginChoice");
234             boolean stayAtCurrentPage = (loginChoice != null && loginChoice.equals ("1"));
235             JahiaPage loginPage = null;
236             if (stayAtCurrentPage) {
237                 JahiaPageBaseService pageService = JahiaPageBaseService.getInstance ();
238                 try {
239                     loginPage = (JahiaPage) pageService
240                             .lookupPage (jParams.getPageID (), jParams);
241
242                     if (loginPage != null && !loginPage.checkReadAccess (theUser)) {
243
244                         logger.debug (
245                                 "The user do not have read access to the requested page ( other than GUEST ) !");
246
247                         logger.error ("User " + username + " cannot log in from this page");
248                         engineMap.put ("notAllowedToLoginFromThisPage", new Boolean JavaDoc (true));
249                         engineMap.put ("screen", "edit");
250                         engineMap.put (ENGINE_URL_PARAM, jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING));
251                         engineMap.put ("jspSource", BADLOGIN_JSP);
252                         return;
253                         /*
254                         JahiaUser guestUser = ServicesRegistry.getInstance()
255                                 .getJahiaUserManagerService().lookupUser(jParams.getSiteID(),JahiaUserManagerService.GUEST_USERNAME);
256                         //theSession.setAttribute( jParams.SESSION_USER, guestUser );
257                         loginPage = (JahiaPage)pageService
258                                 .lookupPage (jParams.getPageID(),jParams);
259                         if ( loginPage != null ){
260                             logger.debug("Switch the user to GUEST USER");
261                             theUser = guestUser;
262                             theSession.setAttribute( jParams.SESSION_USER, theUser );
263                         }
264                         */

265                     }
266                 } catch (Throwable JavaDoc t) {
267                     logger.error ("Exception looking at page : " + jParams.getPageID (), t);
268                 }
269             }
270             logger.debug ("Page to log to is null (2) ! :" + jParams.getPageID ());
271
272             if (loginPage == null) {
273                 loginPage = getHomepage (jParams.getSite (), theUser, jParams);
274             }
275             if (loginPage == null) {
276                 loginPage = jParams.getSite ().getHomePage ();
277             }
278
279             engineMap.put (ENGINE_URL_PARAM, jParams.composePageUrl (loginPage.getID ()));
280             logger.debug ("engineUrl=" + jParams.composePageUrl (loginPage.getID ()));
281
282             JahiaEvent theEvent = new JahiaEvent (this, jParams, theUser);
283             ServicesRegistry.getInstance ().getJahiaEventService ().fireLogin (theEvent);
284
285         } else {
286             engineMap.put ("notAllowedToLoginFromThisPage", new Boolean JavaDoc (false));
287             engineMap.put ("screen", "edit");
288             engineMap.put (ENGINE_URL_PARAM, jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING));
289             engineMap.put ("jspSource", BADLOGIN_JSP);
290             //engineMap.put( ENGINE_OUTPUT_FILE_PARAM, TEMPLATE_JSP );
291
}
292
293         logger.debug ("end");
294
295     }
296
297
298     /**
299      * inits the engine map
300      *
301      * @param jParams a ParamBean object (with request and response)
302      */

303     private void initEngineMap (ParamBean jParams, HashMap JavaDoc engineMap)
304             throws JahiaException {
305         // init map
306
String JavaDoc theScreen = jParams.getRequest ().getParameter ("screen");
307         if (theScreen == null) {
308             theScreen = "edit";
309         }
310
311         engineMap.put ("screen", theScreen);
312         if (!theScreen.equals ("save")) {
313             engineMap.put ("jspSource", LOGIN_JSP);
314             engineMap.put (ENGINE_URL_PARAM, jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING));
315             engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
316         } else {
317             engineMap.put (ENGINE_NAME_PARAM, Core_Engine.ENGINE_NAME);
318             engineMap.put (ENGINE_URL_PARAM, jParams.composePageUrl (jParams.getPageID ()));
319             engineMap.put ("jspSource", CLOSE_JSP);
320         }
321         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
322         engineMap.put ("jahiaBuild", new Integer JavaDoc (jParams.settings ().getBuildNumber ()));
323         engineMap.put ("javascriptUrl", jParams.settings ().getJsHttpPath ());
324
325         // JSP Attribute
326
jParams.getRequest().setAttribute("cookieAuthActivated", new Boolean JavaDoc(jParams.settings().isCookieAuthActivated()));
327         jParams.getRequest ().setAttribute ("engineTitle", "Login");
328         //jParams.getRequest().setAttribute( "engineMap", engineMap );
329
}
330
331
332     /**
333      * Return the first available home page for this user. Personal homepage has precedence over
334      * groups' homepage.
335      *
336      * @param site current site.
337      * @param user the user.
338      *
339      * @return JahiaPage the first available home page, null if none.
340      */

341     private JahiaPage getHomepage (JahiaSite site, JahiaUser user, ParamBean jParams) {
342
343         //logger.debug("started");
344

345         JahiaPage page = null;
346         try {
347
348             JahiaPageBaseService pageService = JahiaPageBaseService.getInstance ();
349
350             // get user home page
351
if (user.getHomepageID () >= 0) {
352
353                 try {
354                     ContentPage contentPage =
355                         ContentPage.getPage(user.getHomepageID());
356                     if ( contentPage != null ){
357                         page = contentPage.getPage(jParams);
358                     }
359                     if (page != null) {
360                         //logger.debug("found user homepage " + page.getTitle());
361
return page;
362                     }
363                 } catch (Throwable JavaDoc t) {
364                     t.printStackTrace ();
365                 }
366             }
367
368             // get group homepages
369
JahiaGroupManagerService grpServ = ServicesRegistry.getInstance ()
370                     .getJahiaGroupManagerService ();
371
372             Vector JavaDoc v = grpServ.getUserMembership (user);
373             int size = v.size ();
374             String JavaDoc grpKey = null;
375             JahiaGroup grp = null;
376             for (int i = 0; i < size; i++) {
377                 grpKey = (String JavaDoc) v.get (i);
378                 grp = grpServ.lookupGroup (grpKey);
379                 if (grp != null
380                         && grp.getSiteID () == site.getID ()
381                         && grp.getHomepageID () >= 0) {
382                     //logger.debug("found a group with homepage " + grp.getGroupname() + ", page=" + grp.getHomepageID() );
383
try {
384                         ContentPage contentPage =
385                             ContentPage.getPage(grp.getHomepageID());
386                         if ( contentPage != null ){
387                             page = contentPage.getPage(jParams);
388                         }
389                         if (page != null) {
390                             //logger.debug("found group homepage =" + page.getTitle() );
391
return page;
392                         }
393                     } catch (Throwable JavaDoc t) {
394                         t.printStackTrace ();
395                     }
396                 }
397             }
398
399         } catch (Throwable JavaDoc t) {
400             t.printStackTrace ();
401         }
402
403         return null;
404     }
405
406 }
407
Popular Tags