1 /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.springframework.security.acls.sid;
16
17 import org.springframework.security.Authentication;
18
19 import org.springframework.security.userdetails.UserDetails;
20
21 import org.springframework.util.Assert;
22
23
24 /**
25 * Represents an <code>Authentication.getPrincipal()</code> as a <code>Sid</code>.<p>This is a basic implementation
26 * that simply uses the <code>String</code>-based principal for <code>Sid</code> comparison. More complex principal
27 * objects may wish to provide an alternative <code>Sid</code> implementation that uses some other identifier.</p>
28 *
29 * @author Ben Alex
30 * @version $Id: PrincipalSid.java 2644 2008-02-15 18:09:26Z luke_t $
31 */
32 public class PrincipalSid implements Sid {
33 //~ Instance fields ================================================================================================
34
35 private String principal;
36
37 //~ Constructors ===================================================================================================
38
39 public PrincipalSid(String principal) {
40 Assert.hasText(principal, "Principal required");
41 this.principal = principal;
42 }
43
44 public PrincipalSid(Authentication authentication) {
45 Assert.notNull(authentication, "Authentication required");
46 Assert.notNull(authentication.getPrincipal(), "Principal required");
47
48 if (authentication.getPrincipal() instanceof UserDetails) {
49 this.principal = ((UserDetails) authentication.getPrincipal()).getUsername();
50 } else {
51 this.principal = authentication.getPrincipal().toString();
52 }
53 }
54
55 //~ Methods ========================================================================================================
56
57 public boolean equals(Object object) {
58 if ((object == null) || !(object instanceof PrincipalSid)) {
59 return false;
60 }
61
62 // Delegate to getPrincipal() to perform actual comparison (both should be identical)
63 return ((PrincipalSid) object).getPrincipal().equals(this.getPrincipal());
64 }
65
66 public int hashCode() {
67 return this.getPrincipal().hashCode();
68 }
69
70 public String getPrincipal() {
71 return principal;
72 }
73
74 public String toString() {
75 return "PrincipalSid[" + this.principal + "]";
76 }
77 }