View Javadoc

1   /**
2    * Copyright 2010 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15  
16  package org.kuali.student.common.util.security;
17  
18  import org.springframework.security.core.Authentication;
19  import org.springframework.security.core.context.SecurityContextHolder;
20  import org.springframework.security.core.userdetails.UserDetails;
21  
22  public class SecurityUtils {
23  	
24  	/** 
25  	 * This can be used to get the current user id from security context
26  	 * 
27  	 * @return userId
28  	 */
29  	public static String getCurrentUserId() {
30          String username=null;
31  		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
32          if(auth!=null){
33          	Object obj = auth.getPrincipal();
34          	if(obj instanceof UserWithId){
35          		//This is actually the user Id
36          		username = ((UserWithId)obj).getUserId();
37          	}else if (obj instanceof UserDetails) {
38              	username = ((UserDetails)obj).getUsername();
39              } else {
40              	username = obj.toString();
41              }
42          }
43  		return username;
44  	}
45  	/** 
46  	 * Add this method to use the new method as specified in Enr-1.0 (ks-1.3) as this method is used in CM
47  	 * 
48  	 * @return principal id
49  	 */
50  	@Deprecated
51  	public static String getCurrentPrincipalId() {
52  		return getCurrentUserId();
53  	}
54  	
55  	public static String getPrincipalUserName(){
56  		String username = "unknown";
57  		
58  		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
59  		if (auth != null) {
60  			Object obj = auth.getPrincipal();
61  		    if (obj instanceof UserDetails) {
62  		    	username = ((UserDetails)obj).getUsername();
63  		    } else {
64  		        username = obj.toString();
65  		    }
66  		}
67  
68  	    return username;
69  	}
70  
71  	/**
72  	 * This can be used to get the current user's principal name from security context
73  	 * 
74  	 * @return principal name
75  	 */
76  	@Deprecated
77  	public static String getCurrentPrincipalName(){
78  	    return getPrincipalUserName();
79  	}
80  }