1   // 
2   //Copyright (c) 2003, Caltha - Gajda, Krzewski, Mach, Potempski Sp.J. 
3   //All rights reserved. 
4   //   
5   //Redistribution and use in source and binary forms, with or without modification,  
6   //are permitted provided that the following conditions are met: 
7   //   
8   //* Redistributions of source code must retain the above copyright notice,  
9   //this list of conditions and the following disclaimer. 
10  //* Redistributions in binary form must reproduce the above copyright notice,  
11  //this list of conditions and the following disclaimer in the documentation  
12  //and/or other materials provided with the distribution. 
13  //* Neither the name of the Caltha - Gajda, Krzewski, Mach, Potempski Sp.J.  
14  //nor the names of its contributors may be used to endorse or promote products  
15  //derived from this software without specific prior written permission. 
16  // 
17  //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"  
18  //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED  
19  //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
20  //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,  
21  //INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,  
22  //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
23  //OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,  
24  //WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)  
25  //ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  
26  //POSSIBILITY OF SUCH DAMAGE. 
27  //
28  
29  package org.objectledge.authentication;
30  
31  import java.io.IOException;
32  import java.io.Reader;
33  import java.security.Principal;
34  
35  import javax.naming.InvalidNameException;
36  import javax.sql.DataSource;
37  import javax.xml.parsers.DocumentBuilder;
38  import javax.xml.parsers.DocumentBuilderFactory;
39  
40  import org.apache.log4j.LogManager;
41  import org.hsqldb.jdbc.jdbcDataSource;
42  import org.jcontainer.dna.Configuration;
43  import org.jcontainer.dna.Logger;
44  import org.jcontainer.dna.impl.Log4JLogger;
45  import org.objectledge.context.Context;
46  import org.objectledge.database.Database;
47  import org.objectledge.database.DatabaseUtils;
48  import org.objectledge.database.DefaultDatabase;
49  import org.objectledge.database.IdGenerator;
50  import org.objectledge.database.JotmTransaction;
51  import org.objectledge.database.persistence.DefaultPersistence;
52  import org.objectledge.database.persistence.Persistence;
53  import org.objectledge.filesystem.FileSystem;
54  import org.objectledge.logging.LedgeDOMConfigurator;
55  import org.objectledge.naming.ContextFactory;
56  import org.objectledge.parameters.DefaultParameters;
57  import org.objectledge.parameters.Parameters;
58  import org.objectledge.parameters.directory.DirectoryParameters;
59  import org.objectledge.utils.LedgeTestCase;
60  import org.picocontainer.defaults.DefaultPicoContainer;
61  import org.w3c.dom.Document;
62  import org.xml.sax.InputSource;
63  
64  /**
65   * @author <a href="mailto:pablo@caltha.pl">Pawel Potempski</a>
66   *
67   * To change the template for this generated type comment go to
68   * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
69   */
70  public class DirectoryUserManagerTest extends LedgeTestCase
71  {
72      private FileSystem fs = null;
73  
74      private ContextFactory contextFactory;
75  
76      private UserManager userManager;
77      
78      public void setUp()
79          throws Exception
80      {
81          fs = FileSystem.getStandardFileSystem("src/test/resources");
82          InputSource source = new InputSource(fs.getInputStream(
83              "config/org.objectledge.logging.LoggingConfigurator.xml"));
84          DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
85          Document logConfig = builder.parse(source);
86          LedgeDOMConfigurator configurator = new LedgeDOMConfigurator(fs);
87          configurator.doConfigure(logConfig.getDocumentElement(), LogManager.getLoggerRepository());
88          Logger logger = new Log4JLogger(org.apache.log4j.Logger.getLogger(ContextFactory.class));
89          DataSource ds = getDataSource();
90          DefaultPicoContainer container = new DefaultPicoContainer();
91          IdGenerator idGenerator = new IdGenerator(ds);
92          JotmTransaction transaction = new JotmTransaction(0, 120, new Context(), logger, null);
93          Database database = new DefaultDatabase(ds, idGenerator, transaction);
94          Persistence persistence = new DefaultPersistence(database, logger);
95          container.registerComponentInstance(Persistence.class, persistence);        
96          
97          Configuration config = getConfig("naming/dbNaming.xml");
98          contextFactory = new ContextFactory(container, config, logger);
99          PasswordGenerator passwordGenerator = new PasswordGenerator();
100         PasswordDigester passwordDigester = new PasswordDigester("md5");
101         config = getConfig("config/org.objectledge.authentication.NamingPolicy.xml");
102         checkSchema("config/org.objectledge.authentication.NamingPolicy.xml", 
103                             "org/objectledge/authentication/NamingPolicy.rng");        
104         NamingPolicy namingPolicy = new NamingPolicy(config);
105         config = getConfig("config/org.objectledge.authentication.LoginVerifier.xml");
106         checkSchema("config/org.objectledge.authentication.LoginVerifier.xml", 
107                     "org/objectledge/authentication/LoginVerifier.rng");
108         LoginVerifier loginVerifier = new LoginVerifier(config);
109         config = getConfig("config/org.objectledge.authentication.DirectoryUserManager.xml");
110         userManager = new DirectoryUserManager(config, logger, namingPolicy, loginVerifier, 
111             passwordGenerator, passwordDigester, contextFactory, new UserManagementParticipant[]{});
112     }
113 
114     public void testUserExists()
115         throws Exception
116     {
117         assertEquals(userManager.userExists("uid=foo,ou=people,dc=objectledge,dc=org"),false);
118         assertEquals(userManager.userExists("uid=foo,ou=people,dc=objectledge2,dc=org"),false);
119         Parameters params = new DefaultParameters();
120         params.add("uid","foo");
121         String dn = userManager.createDN(params);
122         assertEquals(dn,"uid=foo,ou=people,dc=objectledge,dc=org");
123         userManager.createAccount("foo",dn, "bar");
124         assertEquals(userManager.userExists("uid=foo,ou=people,dc=objectledge,dc=org"),true);
125     }
126 
127     public void testCreateAccount()
128         throws Exception
129     {
130         Parameters params = new DefaultParameters();
131         params.set("uid","foo");
132         String dn = userManager.createDN(params);
133         assertEquals(dn,"uid=foo,ou=people,dc=objectledge,dc=org");
134         Principal principal = userManager.createAccount("foo",dn, "bar");
135         assertEquals(principal, userManager.getUserByName(dn));
136         assertEquals(principal.getName(), dn);
137         assertEquals(principal.equals(""), false);
138         principal.toString();
139         try
140         {
141             userManager.createAccount("foo",dn, "bar");
142             fail("should throw the exception");
143         }
144         catch(UserAlreadyExistsException e)
145         {
146             //ok!
147         }
148         params.set("uid","root");
149         dn = userManager.createDN(params);
150         assertEquals(dn,"uid=root,ou=people,dc=objectledge,dc=org");
151         try
152         {
153             userManager.createAccount("root",dn, "bar");
154             fail("should throw the exception");
155         }
156         catch(AuthenticationException e)
157         {
158             //ok!
159         }
160     }
161 
162     public void testRemoveAccount()
163         throws Exception
164     {
165         Parameters params = new DefaultParameters();
166         params.set("uid","foo");
167         String dn = userManager.createDN(params);
168         assertEquals(dn,"uid=foo,ou=people,dc=objectledge,dc=org");
169         Principal principal = userManager.createAccount("foo",dn, "bar");
170         userManager.removeAccount(principal);
171         try
172         {
173             userManager.removeAccount(principal);
174             fail("should throw the exception");
175         }
176         catch(UserUnknownException e)
177         {
178             //ok!
179         }
180     }
181 
182     public void testGetUserByLogin()
183         throws Exception
184     {
185         //TODO test id
186         Parameters params = new DefaultParameters();
187         params.set("uid","foo");
188         String dn = userManager.createDN(params);
189         Principal principal = userManager.createAccount("foo",dn, "bar");
190         Parameters parameters = new DirectoryParameters(userManager.getPersonalData(principal));
191         assertEquals(parameters.get("uid"),"foo");
192         Principal principal2 = userManager.getUserByLogin("foo");
193         try
194         {
195             userManager.getUserByLogin("bar");
196             fail("should throw the exception");
197         }
198         catch(UserUnknownException e)
199         {
200             //ok!
201         }        
202     }
203 
204     public void testGetAnonymousAccount()
205         throws Exception
206     {
207         Principal anonymous = userManager.getAnonymousAccount();
208         assertEquals(anonymous.getName(),"uid=anonymous,ou=people,dc=objectledge,dc=org");
209     }
210 
211     public void testGetSuperuserAccount()
212         throws Exception
213     {
214         Principal root = userManager.getSuperuserAccount();
215         assertEquals(root.getName(),"uid=root,ou=people,dc=objectledge,dc=org");        
216     }
217 
218     public void testChangeUserPassword()
219         throws Exception
220     {
221         Parameters params = new DefaultParameters();
222         params.set("uid","foo");
223         String dn = userManager.createDN(params);
224         Principal principal = userManager.createAccount("foo",dn, "bar");
225         assertEquals(userManager.checkUserPassword(principal, "bar"),true);
226         assertEquals(userManager.checkUserPassword(principal, "foo"),false);
227         userManager.changeUserPassword(principal, "foo");
228         assertEquals(userManager.checkUserPassword(principal, "bar"),false);
229         assertEquals(userManager.checkUserPassword(principal, "foo"),true);
230         try
231         {
232             userManager.checkUserPassword(new DefaultPrincipal("foo"),"bar");
233             fail("should throw the exception");
234         }
235         catch(AuthenticationException e)
236         {
237             //ok!
238         }        
239     }
240 
241     public void testGetPersonalData()
242         throws Exception
243     {
244         Parameters params = new DefaultParameters();
245         params.set("uid","foo");
246         String dn = userManager.createDN(params);
247         Principal principal = userManager.createAccount("foo",dn, "bar");
248         params = new DirectoryParameters(userManager.getPersonalData(principal));
249         assertEquals(params.get("uid"),"foo");
250         try
251         {
252             userManager.getPersonalData(new DefaultPrincipal("foo"));
253             fail("should throw the exception");
254         }
255         catch(AuthenticationException e)
256         {
257             //ok!
258         }        
259     }
260 
261     public void testLookupAccountsStringString()
262         throws Exception
263     {
264         Parameters params = new DefaultParameters();
265         params.set("uid","foo");
266         String dn = userManager.createDN(params);
267         Principal principal = userManager.createAccount("foo",dn, "bar");
268         Principal[] results = userManager.lookupAccounts("foo","bar");
269         assertEquals(results.length,0);
270         results = userManager.lookupAccounts("uid","foo");
271         assertEquals(results.length,1);
272     }
273 
274     public void testLookupAccountsString()
275         throws Exception
276     {
277         Parameters params = new DefaultParameters();
278         params.set("uid","foo");
279         String dn = userManager.createDN(params);
280         Principal principal = userManager.createAccount("foo",dn, "bar");
281         /*
282         Principal[] results = userManager.lookupAccounts("(foo=bar)");
283         assertEquals(results.length,0);
284         results = userManager.lookupAccounts("(uid=foo)");
285         assertEquals(results.length,1);
286         */        
287     }
288 
289     public void testUserManager()
290     {
291         assertNotNull(userManager);
292     }
293 
294     public void testCheckLogin()
295     {
296         assertEquals(userManager.checkLogin(""),true);
297         assertEquals(userManager.checkLogin("foo"),true);
298     }
299 
300     public void testValidateLogin()
301     {
302         assertEquals(userManager.validateLogin(""),false);
303         assertEquals(userManager.validateLogin("foo"),true);
304     }
305 
306     public void testCreateDN()
307     {
308         Parameters params = new DefaultParameters();
309         params.add("uid","foo");
310         String dn = userManager.createDN(params);
311         assertEquals(dn,"uid=foo,ou=people,dc=objectledge,dc=org");
312     }
313 
314     public void testGetLogin()
315         throws Exception
316     {
317         Parameters params = new DefaultParameters();
318         params.set("uid","foo");
319         String dn = userManager.createDN(params);
320         Principal principal = userManager.createAccount("foo",dn, "bar");
321         assertEquals(userManager.getLogin(principal),"foo");
322         assertEquals(userManager.getLogin(dn),"foo");
323         try
324         {
325             userManager.getLogin("bar");
326             fail("should throw the exception");
327         }
328         catch(InvalidNameException e)
329         {
330             //ok!
331         }
332     }
333 
334     public void testCreateRandomPassword()
335     {
336         String pass = userManager.createRandomPassword(6,8);
337         assertEquals(pass.length()>=6,true);
338         assertEquals(pass.length()<=8,true);
339     }
340 
341     public void testDefaultPrincipal()
342     {
343         Principal principal = new DefaultPrincipal(null);
344         principal.toString();
345         assertEquals(principal.hashCode(), 0);
346     }
347 
348     /////////////// private 
349     private DataSource getDataSource()
350         throws Exception
351     {
352         jdbcDataSource ds = new jdbcDataSource();
353         ds.setDatabase("jdbc:hsqldb:.");
354         ds.setUser("sa");
355         ds.setPassword("");
356         if(!DatabaseUtils.hasTable(ds, "ledge_id_table"))
357         {
358             DatabaseUtils.runScript(ds, getScript("sql/database/IdGeneratorTables.sql"));
359         }
360         if(!DatabaseUtils.hasTable(ds, "ledge_naming_context"))
361         {        
362             DatabaseUtils.runScript(ds, getScript("sql/naming/db/DBNamingTables.sql"));
363         }
364         DatabaseUtils.runScript(ds, getScript("sql/naming/db/DBNamingTest.sql"));
365         return ds;
366     }    
367     
368     private Reader getScript(String path)
369         throws IOException
370     {
371         return fs.getReader(path, "UTF-8");
372     }    
373 
374     private Configuration getConfig(String name)
375         throws Exception
376     {
377         return getConfig(fs, name);
378     }
379 }