1 /*
2 * Copyright 2008 :torweg free software group
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */18 package org.torweg.pulse.accesscontrol.authentication;
19 20 import javax.servlet.http.HttpServletRequest;
21 22 import org.hibernate.Session;
23 import org.hibernate.Transaction;
24 import org.hibernate.criterion.Restrictions;
25 importorg.torweg.pulse.accesscontrol.User;
26 importorg.torweg.pulse.invocation.lifecycle.Lifecycle;
27 importorg.torweg.pulse.service.PulseException;
28 importorg.torweg.pulse.service.request.HttpBoundSession;
29 30 /**
31 * is an {@code AuthenticationAdapter} to allow a login to <em>pulse</em>
32 * from an external source.
33 *
34 * @author Thomas Weber
35 * @version $Revision: 1380 $
36 */37 publicfinalclass AuthenticationAdapter {
38 39 /**
40 * hidden constructor.
41 */42 private AuthenticationAdapter() {
43 super();
44 }
45 46 /**
47 * tries to authenticate the given user.
48 *
49 * @param request
50 * the request
51 * @param username
52 * the name of the user
53 * @param password
54 * the user's password
55 * @return {@code true}, if the user could be authenticated. Otherwise
56 * {@code false}.
57 */58 publicstaticboolean authenticate(final HttpServletRequest request,
59 final String username, final String password) {
60 Session s = Lifecycle.getHibernateDataSource().createNewSession();
61 Transaction tx = s.beginTransaction();
62 HttpBoundSession httpSession = HttpBoundSession.getSession(request);
63 try {
64 User user = (User) s.createCriteria(User.class).add(
65 Restrictions.eq("name", username)).uniqueResult();
66 tx.commit();
67 /* no user found --> no login */68 if (user == null) {
69 returnfalse;
70 }
71 /* wrong password --> no login */72 if (!user.checkPassword(password)) {
73 returnfalse;
74 }
75 /* update last login */76 user.setLastLoginTime();
77 tx = s.beginTransaction();
78 s.update(user);
79 tx.commit();
80 httpSession.setAttribute(User.class.getCanonicalName(), user
81 .getId());
82 } catch (Exception e) {
83 tx.rollback();
84 httpSession.removeAttribute(User.class.getCanonicalName());
85 thrownewPulseException("Error: " + e.getLocalizedMessage(), e);
86 } finally {
87 s.close();
88 }
89 returntrue;
90 }
91 }
92