Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Howto abstract an LDAP layer to resolve permissions
/**
* PLEASE AVOID THIS IMPLEMENTATION BECAUSE OF...
* - a cache should be garbage collectable (on low memory)
* (see Soft Reference, Weak Reference etc.)
* - a cache should be thread safe (this is not)
*/
class CachedLdapPermissionResolver extends LdapPermissionResolver {
private static final long MAX_TIME = 1000 * 60 * 10; // = 10 min.
@Override boolean hasPermission(String userId, String role) {
long time = System.currentTimeMillis();
Key key = new Key(userId, role);
Entry entry = cache.get(key);
if (entry == null) {
boolean hasPermission = super.hasPermission(user, role);
entry = new Entry(hasPermission, time);
cache.put(key, entry);
} else if (time - entry.retrievedAt > MAX_TIME) {
entry.hasPermission = super.hasPermission(user, role);
entry.retrievedAt = time;
}
return entry.hasPermission;
}
Map<Key, Entry> cache = new WeakHashMap<Key, Entry>(); // TODO: WeakHashMap is not viable here
class Key {
String userId;
String role;
Key(String userId, String role) {
this.userId = userId;
this.role = role;
}
@Override public boolean equals(Object o) {
return o != null && o instanceOf Key && hashCode() == o.hashCode();
}
@Override public int hashCode() {
return 31 * (userId == null ? 0 : userId.hashCode()) + (role == null ? 0 : role.hashCode());
}
}
class Entry {
boolean hasPermission;
long retrievedAt;
Entry(boolean hasPermission, long retrievedAt) {
this.hasPermission = hasPermission;
this.retrievedAt = retrievedAt;
}
}
}
/**
* Concrete LDAP implementation (exemplary)
*/
class LdapPermissionResolver implements PermissionResolver {
@Inject LdapContext ctx;
@Override boolean hasPermission(String userId, String role) {
final String name = ...
final String filter = ...
final Object o = ctx.search(name, filter, null);
final boolean result = doSomethingWith(o);
return result;
}
}
/**
* Here go all business methods needed to resolve permissions
*/
interface PermissionResolver {
boolean hasPermission(String userId, String role);
// TODO: more services
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.