View Javadoc
1   package com.atlassian.refapp.auth.internal;
2   
3   import com.atlassian.seraph.auth.AuthenticationContext;
4   import com.atlassian.user.EntityException;
5   import com.atlassian.user.Group;
6   import com.atlassian.user.GroupManager;
7   import com.atlassian.user.User;
8   import com.atlassian.user.UserManager;
9   
10  import java.security.Principal;
11  
12  public class UserContextHelper {
13      private final AuthenticationContext authenticationContext;
14      private final UserManager userManager;
15      private final GroupManager groupManager;
16  
17      public UserContextHelper(AuthenticationContext authenticationContext, UserManager userManager,
18                               GroupManager groupManager) {
19          this.authenticationContext = authenticationContext;
20          this.userManager = userManager;
21          this.groupManager = groupManager;
22      }
23  
24      public User getRemoteUser() {
25          Principal principal = authenticationContext.getUser();
26          if (principal == null) {
27              return null;
28          }
29          try {
30              return userManager.getUser(principal.getName());
31          } catch (EntityException ee) {
32              return null;
33          }
34      }
35  
36      public boolean isRemoteUserAdministrator() {
37          return isRemoteUserRole("administrators");
38      }
39  
40      public boolean isRemoteUserSystemAdministrator() {
41          return isRemoteUserRole("system_administrators");
42      }
43  
44      private boolean isRemoteUserRole(String role) {
45          User user = getRemoteUser();
46          if (user == null) {
47              return false;
48          }
49          try {
50              Group group = groupManager.getGroup(role);
51              if (group == null) {
52                  return false;
53              }
54              return groupManager.hasMembership(group, user);
55          } catch (EntityException ee) {
56              return false;
57          }
58      }
59  
60  }