- anti-abuse features created
[mir.git] / source / Mir.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.lang.reflect.Method;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Locale;
40 import java.util.Map;
41 import java.util.Vector;
42
43 import javax.servlet.ServletException;
44 import javax.servlet.UnavailableException;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import javax.servlet.http.HttpSession;
48
49 import mir.config.MirPropertiesConfiguration;
50 import mir.generator.FreemarkerGenerator;
51 import mir.log.LoggerWrapper;
52 import mir.misc.HTMLTemplateProcessor;
53 import mir.misc.StringUtil;
54 import mir.servlet.AbstractServlet;
55 import mir.servlet.ServletModule;
56 import mir.servlet.ServletModuleDispatch;
57 import mir.servlet.ServletModuleExc;
58 import mir.servlet.ServletModuleUserExc;
59 import mir.util.ExceptionFunctions;
60 import mir.util.StringRoutines;
61 import mircoders.entity.EntityUsers;
62 import mircoders.global.MirGlobal;
63 import mircoders.module.ModuleMessage;
64 import mircoders.module.ModuleUsers;
65 import mircoders.storage.DatabaseArticleType;
66 import mircoders.storage.DatabaseMessages;
67 import mircoders.storage.DatabaseUsers;
68
69 import org.apache.struts.util.MessageResources;
70
71 import freemarker.template.SimpleHash;
72 import freemarker.template.SimpleList;
73 import freemarker.template.SimpleScalar;
74 import freemarker.template.TemplateModel;
75
76
77
78
79 /**
80  * Mir.java - main servlet, that dispatches to servletmodules
81  *
82  * @author $Author: zapata $
83  * @version $Id: Mir.java,v 1.40 2003/03/15 15:35:56 zapata Exp $
84  *
85  */
86 public class Mir extends AbstractServlet {
87   private static ModuleUsers usersModule = null;
88   private static ModuleMessage messageModule = null;
89   private final static Map servletModuleInstanceHash = new HashMap();
90
91   //I don't know about making this static cause it removes the
92   //possibility to change the config on the fly.. -mh
93   private static List loginLanguages = null;
94   public HttpSession session;
95
96   protected TemplateModel getLoginLanguages() throws ServletException {
97     synchronized (Mir.class) {
98       try {
99         if (loginLanguages == null) {
100           MessageResources messageResources2 =
101             MessageResources.getMessageResources("bundles.admin");
102           MessageResources messageResources =
103             MessageResources.getMessageResources("bundles.adminlocal");
104           List languages =
105             StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
106
107           loginLanguages = new Vector();
108
109           Iterator i = languages.iterator();
110
111           while (i.hasNext()) {
112             String code = (String) i.next();
113             Locale locale = new Locale(code, "");
114             String name = messageResources.getMessage(locale, "languagename");
115
116             if (name == null) {
117               name = messageResources2.getMessage(locale, "languagename");
118             }
119
120             if (name == null) {
121               name = code;
122             }
123
124             Map record = new HashMap();
125             record.put("name", name);
126             record.put("code", code);
127             loginLanguages.add(record);
128           }
129         }
130
131         return FreemarkerGenerator.makeAdapter(loginLanguages);
132       }
133       catch (Throwable t) {
134         throw new ServletException(t.getMessage());
135       }
136     }
137   }
138
139   // FIXME: this should probalby go into AbstractServlet so it can be used in
140   // OpenMir as well -mh
141   protected String getDefaultLanguage(HttpServletRequest aRequest) {
142     String defaultlanguage =
143       MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
144
145     if (defaultlanguage.length() == 0) {
146       Locale locale = aRequest.getLocale();
147       defaultlanguage = locale.getLanguage();
148     }
149
150     return defaultlanguage;
151   }
152
153   public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
154     throws ServletException, IOException, UnavailableException {
155     long startTime = System.currentTimeMillis();
156     long sessionConnectTime = 0;
157     EntityUsers userEntity;
158     String http = "";
159
160     configuration.addProperty("ServletName", getServletName());
161
162     session = aRequest.getSession(true);
163     userEntity = (EntityUsers) session.getAttribute("login.uid");
164
165     if (aRequest.getServerPort() == 443) {
166       http = "https";
167     } else {
168       http = "http";
169     }
170
171     //make sure client browsers don't cache anything
172     setNoCaching(aResponse);
173
174     //FIXME: this seems kind of hackish and only here because we can have
175     // default other than the one that the browser is set to.
176     Locale locale = new Locale(getDefaultLanguage(aRequest), "");
177     MessageResources messageResources =
178       MessageResources.getMessageResources("bundles.admin");
179     String htmlcharset = messageResources.getMessage(locale, "htmlcharset");
180
181     aResponse.setContentType("text/html; charset=" + htmlcharset);
182
183     String moduleName = aRequest.getParameter("module");
184     checkLanguage(session, aRequest);
185
186     /** @todo for cleanup and readability this should be moved to
187      *  method loginIfNecessary() */
188     if ((moduleName != null) && moduleName.equals("direct")) {
189       //...
190     }
191
192     // Authentication
193     if (((moduleName != null) && moduleName.equals("login")) ||
194         (userEntity == null)) {
195       String user = aRequest.getParameter("login");
196       String passwd = aRequest.getParameter("password");
197       logger.debug("--login: evaluating for user: " + user);
198       userEntity = allowedUser(user, passwd);
199
200       if (userEntity == null) {
201         // login failed: redirecting to login
202         logger.warn("--login: failed!");
203         _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
204
205         return;
206       } else if ((moduleName != null) && moduleName.equals("login")) {
207         // login successful
208         logger.info("--login: successful! setting uid: " + userEntity.getId());
209         session.setAttribute("login.uid", userEntity);
210         logger.debug("--login: trying to retrieve login.target");
211
212         String target = (String) session.getAttribute("login.target");
213
214         if (target != null) {
215           logger.debug("Redirect: " + target);
216
217           int serverPort = aRequest.getServerPort();
218           String redirect = "";
219           String redirectString = "";
220
221           if (serverPort == 80) {
222             redirect =
223               aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);
224             redirectString =
225               "<html><head><meta http-equiv=refresh content=\"1;URL=" +
226               redirect + "\"></head><body>going <a href=\"" + redirect +
227               "\">Mir</a></body></html>";
228           } else {
229             redirect =
230               aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +
231                 aRequest.getServerPort() + target);
232             redirectString =
233               "<html><head><meta http-equiv=refresh content=\"1;URL=" +
234               redirect + "\"></head><body>going <a href=\"" + redirect +
235               "\">Mir</a></body></html>";
236           }
237
238           aResponse.getWriter().println(redirectString);
239
240           //aResponse.sendRedirect(redirect);
241         } else {
242           // redirecting to default target
243           logger.debug("--login: no target - redirecting to default");
244           _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
245         }
246
247         return;
248       }
249        // if login succesful
250     }
251      // if login
252
253     if ((moduleName != null) && moduleName.equals("logout")) {
254       logger.info("--logout");
255       session.invalidate();
256
257       //session = aRequest.getSession(true);
258       //checkLanguage(session, aRequest);
259       _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
260
261       return;
262     }
263
264     // Check if authed!
265     if (userEntity == null) {
266       // redirect to loginpage
267       String redirectString = aRequest.getRequestURI();
268       String queryString = aRequest.getQueryString();
269
270       if ((queryString != null) && !queryString.equals("")) {
271         redirectString += ("?" + aRequest.getQueryString());
272         logger.debug("STORING: " + redirectString);
273         session.setAttribute("login.target", redirectString);
274       }
275
276       _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
277
278       return;
279     }
280
281     // If no module is specified goto standard startpage
282     if ((moduleName == null) || moduleName.equals("")) {
283       logger.debug("no module: redirect to standardpage");
284       _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
285
286       return;
287     }
288
289     // end of auth
290     // From now on regular dispatching...
291     try {
292       // get servletmodule by parameter and continue with dispacher
293       ServletModule smod = getServletModuleForName(moduleName);
294       ServletModuleDispatch.dispatch(smod, aRequest, aResponse);
295     }
296     catch (Throwable e) {
297       Throwable cause = ExceptionFunctions.traceCauseException(e);
298
299       if (cause instanceof ServletModuleUserExc)
300         handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
301       else
302         handleError(aRequest, aResponse, aResponse.getWriter(), cause);
303
304     }
305
306     // timing...
307     sessionConnectTime = System.currentTimeMillis() - startTime;
308     logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
309   }
310
311   /**
312    *  Private method getServletModuleForName returns ServletModule
313    *  from Cache
314    *
315    * @param moduleName
316    * @return ServletModule
317    *
318    */
319   private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {
320     // Instance in Map ?
321     if (!servletModuleInstanceHash.containsKey(moduleName)) {
322       // was not found in hash...
323       try {
324         Class theServletModuleClass = null;
325
326         try {
327           // first we try to get ServletModule from stern.che3.servlet
328           theServletModuleClass =
329             Class.forName("mircoders.servlet.ServletModule" + moduleName);
330         } catch (ClassNotFoundException e) {
331           // on failure, we try to get it from lib-layer
332           theServletModuleClass =
333             Class.forName("mir.servlet.ServletModule" + moduleName);
334         }
335
336         Method m = theServletModuleClass.getMethod("getInstance", null);
337         ServletModule smod = (ServletModule) m.invoke(null, null);
338
339         // we put it into map for further reference
340         servletModuleInstanceHash.put(moduleName, smod);
341
342         return smod;
343       }
344       catch (Exception e) {
345         throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
346       }
347     }
348     else {
349       return (ServletModule) servletModuleInstanceHash.get(moduleName);
350     }
351   }
352
353   private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
354                                PrintWriter out, ServletModuleUserExc anException) {
355     try {
356       logger.info("user error: " + anException.getMessage());
357       SimpleHash modelRoot = new SimpleHash();
358       MessageResources messages = MessageResources.getMessageResources("bundles.admin");
359       modelRoot.put("errorstring",
360           new SimpleScalar(
361               messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())
362           ));
363       modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
364       HTMLTemplateProcessor.process(
365           aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
366           modelRoot, out, getLocale(aRequest));
367       out.close();
368     }
369     catch (Exception e) {
370       logger.error("Error in UserErrorTemplate");
371     }
372
373   }
374
375   private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
376
377     try {
378       logger.error("error: " + anException);
379       SimpleHash modelRoot = new SimpleHash();
380       modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
381       modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(
382                                                new GregorianCalendar())));
383       HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
384                                     modelRoot,out, getLocale(aRequest));
385       out.close();
386     }
387     catch (Exception e) {
388       logger.error("Error in ErrorTemplate");
389     }
390   }
391
392   /**
393    *  evaluate login for user / password
394    */
395   protected EntityUsers allowedUser(String user, String password) {
396     try {
397       if (usersModule == null) {
398         usersModule = new ModuleUsers(DatabaseUsers.getInstance());
399       }
400
401       return usersModule.getUserForLogin(user, password);
402     }
403     catch (Exception e) {
404       logger.debug(e.getMessage());
405       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
406
407       return null;
408     }
409   }
410
411   // Redirect-methods
412   private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
413     PrintWriter out) {
414     String loginTemplate = configuration.getString("Mir.LoginTemplate");
415     String sessionUrl = aResponse.encodeURL("");
416
417     try {
418       SimpleHash mergeData = new SimpleHash();
419       SimpleList languages = new SimpleList();
420
421       mergeData.put("session", sessionUrl);
422
423       mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
424       mergeData.put("languages", getLoginLanguages());
425
426       HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out,
427         getLocale(aRequest));
428     }
429     catch (Throwable e) {
430       handleError(aRequest, aResponse, out, e);
431     }
432   }
433
434   private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
435     PrintWriter out, EntityUsers userEntity) {
436     String startTemplate = "templates/admin/start_admin.template";
437     String sessionUrl = aResponse.encodeURL("");
438
439     try {
440       // merge with logged in user and messages
441       SimpleHash mergeData = new SimpleHash();
442       mergeData.put("session", sessionUrl);
443       mergeData.put("login_user", userEntity);
444
445       if (messageModule == null) {
446         messageModule = new ModuleMessage(DatabaseMessages.getInstance());
447       }
448
449       mergeData.put("messages",
450         messageModule.getByWhereClause(null, "webdb_create desc", 0, 10));
451
452       mergeData.put("articletypes",
453         DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20));
454
455       HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out,
456         getLocale(aRequest));
457     }
458     catch (Exception e) {
459       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
460       handleError(aRequest, aResponse, out, e);
461     }
462   }
463
464   public String getServletInfo() {
465     return "Mir " + configuration.getString("Mir.Version");
466   }
467
468   private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {
469     // a lang parameter always sets the language
470     String lang = aRequest.getParameter("language");
471
472     if (lang != null) {
473       logger.info("selected language " + lang + " overrides accept-language");
474       setLanguage(session, lang);
475       setLocale(session, new Locale(lang, ""));
476     }
477     // otherwise store language from accept header in session
478     else if (session.getAttribute("Language") == null) {
479       logger.info("accept-language is " + aRequest.getLocale().getLanguage());
480       setLanguage(session, aRequest.getLocale().getLanguage());
481       setLocale(session, aRequest.getLocale());
482     }
483   }
484 }