KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > authentication > impl > DaisyAuthenticationFactory


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.outerj.daisy.authentication.impl;
17
18 import org.outerj.daisy.authentication.AuthenticationScheme;
19 import org.outerj.daisy.authentication.AuthenticationException;
20 import org.outerj.daisy.authentication.AuthenticationSchemeRegistrar;
21 import org.outerj.daisy.authentication.CachingAuthenticationScheme;
22 import org.outerj.daisy.repository.Credentials;
23 import org.outerj.daisy.repository.user.User;
24 import org.outerj.daisy.repository.user.UserManager;
25 import org.outerj.daisy.jdbcutil.JdbcHelper;
26 import org.apache.avalon.framework.service.Serviceable;
27 import org.apache.avalon.framework.service.ServiceManager;
28 import org.apache.avalon.framework.service.ServiceException;
29 import org.apache.avalon.framework.activity.Disposable;
30 import org.apache.avalon.framework.activity.Initializable;
31 import org.apache.avalon.framework.logger.LogEnabled;
32 import org.apache.avalon.framework.logger.Logger;
33 import org.apache.avalon.framework.configuration.Configurable;
34 import org.apache.avalon.framework.configuration.Configuration;
35 import org.apache.avalon.framework.configuration.ConfigurationException;
36
37 import javax.sql.DataSource JavaDoc;
38 import java.sql.Connection JavaDoc;
39 import java.sql.PreparedStatement JavaDoc;
40 import java.sql.ResultSet JavaDoc;
41 import java.security.MessageDigest JavaDoc;
42
43 /**
44  * Responsible for creating and registering the DaisyAuthenticationScheme with the UserAuthenticator.
45  *
46  * @avalon.component version="1.0" name="daisy-authentication-scheme" lifestyle="singleton"
47  */

48 public class DaisyAuthenticationFactory implements Serviceable, Disposable, Initializable, LogEnabled, Configurable {
49     private ServiceManager serviceManager;
50     private AuthenticationSchemeRegistrar authenticationSchemeRegistrar;
51     private DataSource JavaDoc dataSource;
52     private Logger logger;
53     private JdbcHelper jdbcHelper;
54     private boolean enableCaching;
55     private long maxCacheDuration;
56     private int maxCacheSize;
57     private AuthenticationScheme authScheme;
58
59     /**
60      * @avalon.dependency key="datasource" type="javax.sql.DataSource"
61      * @avalon.dependency key="auth-scheme-registrar" type="org.outerj.daisy.authentication.AuthenticationSchemeRegistrar"
62      */

63     public void service(ServiceManager serviceManager) throws ServiceException {
64         this.serviceManager = serviceManager;
65         this.authenticationSchemeRegistrar = (AuthenticationSchemeRegistrar)serviceManager.lookup("auth-scheme-registrar");
66         this.dataSource = (DataSource JavaDoc)serviceManager.lookup("datasource");
67     }
68
69     public void configure(Configuration configuration) throws ConfigurationException {
70         Configuration cacheConf = configuration.getChild("cache");
71         if (cacheConf.getAttributeAsBoolean("enabled")) {
72             enableCaching = true;
73             maxCacheSize = cacheConf.getAttributeAsInteger("maxCacheSize", 3000);
74             maxCacheDuration = cacheConf.getAttributeAsLong("maxCacheDuration", 30 * 60 * 1000); // default: half an hour
75
}
76     }
77
78     public void initialize() throws Exception JavaDoc {
79         jdbcHelper = JdbcHelper.getInstance(dataSource, logger);
80         if (enableCaching) {
81             authScheme = new CachingAuthenticationScheme(new DaisyAuthenticationScheme(), maxCacheDuration, maxCacheSize);
82         } else {
83             authScheme = new DaisyAuthenticationScheme();
84         }
85         authenticationSchemeRegistrar.registerAuthenticationScheme(authScheme);
86     }
87
88     public void enableLogging(Logger logger) {
89         this.logger = logger;
90     }
91
92     public void dispose() {
93         authenticationSchemeRegistrar.unregisterAuthenticationScheme(authScheme);
94         serviceManager.release(dataSource);
95         serviceManager.release(authenticationSchemeRegistrar);
96     }
97
98     class DaisyAuthenticationScheme implements AuthenticationScheme {
99
100         public String JavaDoc getName() {
101             return "daisy";
102         }
103
104         public String JavaDoc getDescription() {
105             return "Daisy built-in";
106         }
107
108         public void clearCaches() {
109             // do nothing
110
}
111
112         public boolean check(Credentials credentials) throws AuthenticationException {
113             Connection JavaDoc conn = null;
114             PreparedStatement JavaDoc stmt = null;
115             ResultSet JavaDoc rs = null;
116             try {
117                 conn = dataSource.getConnection();
118                 stmt = conn.prepareStatement("select password, default_role, id from users where login = ?");
119                 stmt.setString(1, credentials.getLogin());
120                 rs = stmt.executeQuery();
121
122                 if (!rs.next())
123                     return false;
124
125                 String JavaDoc password = rs.getString("password");
126
127                 if (password == null || !password.equals(hashPassword(credentials.getPassword())))
128                     return false;
129
130                 return true;
131             } catch (Exception JavaDoc e) {
132                 throw new AuthenticationException("Error trying to authenticate user with Daisy Authentication Scheme.", e);
133             } finally {
134                 jdbcHelper.closeStatement(stmt);
135                 jdbcHelper.closeConnection(conn);
136             }
137         }
138
139         public User createUser(Credentials crendentials, UserManager userManager) throws AuthenticationException {
140             return null;
141         }
142     }
143
144     private static String JavaDoc hashPassword(String JavaDoc password) {
145         if (password == null)
146             return null;
147         try {
148             byte[] data = password.getBytes("UTF-8");
149             MessageDigest JavaDoc digest = MessageDigest.getInstance("SHA-1");
150             digest.update(data);
151             byte[] result = digest.digest();
152             return toHexString(result);
153         } catch (Exception JavaDoc e) {
154             throw new RuntimeException JavaDoc("Problem calculating password hash.", e);
155         }
156     }
157
158     private static String JavaDoc toHexString(byte[] b) {
159         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(b.length * 2);
160         for (int i = 0; i < b.length; i++) {
161             sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
162             sb.append(hexChar[b[i] & 0x0f]);
163         }
164         return sb.toString();
165     }
166
167     static char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
168 }
169
Popular Tags