1 package com.atlassian.sal.core.permission;
2
3 import com.atlassian.sal.api.permission.AuthorisationException;
4 import com.atlassian.sal.api.permission.NotAuthenticatedException;
5 import com.atlassian.sal.api.permission.PermissionEnforcer;
6 import com.atlassian.sal.api.user.UserKey;
7 import com.atlassian.sal.api.user.UserManager;
8
9 public class DefaultPermissionEnforcer implements PermissionEnforcer {
10
11 private final UserManager userManager;
12
13 public DefaultPermissionEnforcer(UserManager userManager) {
14 this.userManager = userManager;
15 }
16
17 @Override
18 public void enforceAdmin() throws AuthorisationException {
19 if (!userManager.isAdmin(getRemoteUserOrThrow())) {
20 throw new AuthorisationException("You must be an administrator to access this resource");
21 }
22 }
23
24 @Override
25 public void enforceAuthenticated() throws AuthorisationException {
26 getRemoteUserOrThrow();
27 }
28
29 @Override
30 public void enforceSystemAdmin() throws AuthorisationException {
31 if (!userManager.isSystemAdmin(getRemoteUserOrThrow())) {
32 throw new AuthorisationException("You must be an administrator to access this resource");
33 }
34 }
35
36 @Override
37 public boolean isAdmin() {
38 UserKey key = userManager.getRemoteUserKey();
39 return key != null && userManager.isAdmin(key);
40 }
41
42 @Override
43 public boolean isAuthenticated() {
44 return userManager.getRemoteUserKey() != null;
45 }
46
47 @Override
48 public boolean isSystemAdmin() {
49 UserKey key = userManager.getRemoteUserKey();
50 return key != null && userManager.isSystemAdmin(key);
51 }
52
53 private UserKey getRemoteUserOrThrow() {
54 UserKey key = userManager.getRemoteUserKey();
55 if (key == null) {
56 throw new NotAuthenticatedException();
57 }
58 return key;
59 }
60 }