View Javadoc

1   /*
2    * $Id: TestMultiuserSecurityProvider.java 21939 2011-05-18 13:32:09Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.tck.security;
12  
13  import org.mule.api.lifecycle.InitialisationException;
14  import org.mule.api.security.Authentication;
15  import org.mule.api.security.SecurityException;
16  
17  import java.util.HashMap;
18  import java.util.Map;
19  import java.util.concurrent.ConcurrentHashMap;
20  
21  /**
22   * A security provider which holds authentications for multiple users concurrently.
23   */
24  public class TestMultiuserSecurityProvider extends TestSingleUserSecurityProvider
25  {
26      private Map <String, Authentication> authentications;
27      
28      public TestMultiuserSecurityProvider()
29      {
30          super("multi-user-test");
31      }
32      
33      protected void doInitialise() throws InitialisationException
34      {
35          authentications = new ConcurrentHashMap();
36      }
37      
38      public Authentication authenticate(Authentication authentication) throws SecurityException
39      {
40          String user = (String) authentication.getPrincipal();
41          logger.debug("Authenticating user: " + user);
42          
43          // Check to see if user has already been authenticated
44          Authentication oldAuth = authentications.get(user);
45          if (oldAuth != null)
46          {
47              authentication = oldAuth;
48              Map props = authentication.getProperties();
49              int numberLogins = (Integer) props.get(PROPERTY_NUMBER_LOGINS);
50              String favoriteColor = (String) props.get(PROPERTY_FAVORITE_COLOR);
51              props.put(PROPERTY_NUMBER_LOGINS, numberLogins + 1);
52              authentication.setProperties(props);
53              authentications.put(user, authentication);
54              logger.info("Welcome back " + user + " (" + numberLogins+1 + " logins), we remembered your favorite color: " + favoriteColor);
55          }
56          else
57          {
58              String favoriteColor = getFavoriteColor(user);
59              logger.info("First login for user: " + user + ", favorite color is " + favoriteColor);
60              Map props = new HashMap();
61              props.put(PROPERTY_NUMBER_LOGINS, 1);
62              props.put(PROPERTY_FAVORITE_COLOR, favoriteColor);
63              authentication.setProperties(props);
64              authentications.put(user, authentication);
65          }
66          return authentication;
67      }
68  }