forked from silb/shiro-jersey
-
Notifications
You must be signed in to change notification settings - Fork 1
/
User.java
44 lines (33 loc) · 1.39 KB
/
User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package org.secnod.example.webapp;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
public class User {
private final Subject subject;
public User(Subject subject) {
super();
if (subject == null)
throw new NullPointerException();
this.subject = subject;
}
public <T> T unwrap(Class<T> type) {
if (Subject.class.equals(type)) return type.cast(subject);
throw new IllegalArgumentException("User " + this + " cannot be unwrapped to " + type);
}
@Override
public String toString() {
String username = subject.getPrincipal() != null ? subject.getPrincipal().toString() : null;
return username != null ? username : "anonymous";
}
public void checkPermissionBySomeRule() throws AuthorizationException {
// Apply domain specific authorization rules based on data found in the user's data, subject principals etc.
if (Math.random() < 0.5) throw new UnauthorizedException();
}
// Convenience delegate methods to the Subject
public void checkPermission(String permission) throws AuthorizationException {
subject.checkPermission(permission);
}
public void checkRole(String roleIdentifier) throws AuthorizationException {
this.subject.checkRole(roleIdentifier);
}
}