package ca.uhnresearch.pughlab.tracker.restlets;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.restlet.Component;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.security.Authenticator;
import org.restlet.security.User;

public class CustomSpringSessionAuthenticator extends Authenticator {

	public CustomSpringSessionAuthenticator(Component component) {
		super(component.getContext());
	}
	
    public CustomSpringSessionAuthenticator(Restlet parent) {
        super(parent.getContext());
    }

	@Override
	protected boolean authenticate(Request request, Response response) {
		
		Subject currentUser = SecurityUtils.getSubject();
		
		if (currentUser == null) {
			throw new IllegalStateException("Invalid subject: SecurityUtils.getSubject returned null");
		}
		
		Object principal = currentUser.getPrincipals().getPrimaryPrincipal(); 
		if (principal != null) {
			User user = new User(principal.toString());
			request.getClientInfo().setUser(user);
			
			ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.CUSTOM);
			challenge.setIdentifier(user.getIdentifier());
			request.setChallengeResponse(challenge);
			return true;
			
		} else {
			return false;
		}
	}
}

@@ -82,16 +82,69 @@
 yUtils;%0A
+import org.apache.shiro.subject.PrincipalCollection;%0A
 import o
@@ -976,16 +976,18 @@
 tSubject
+()
  returne
@@ -1009,14 +1009,85 @@
 %09%0A%09%09
-Object
+%0A%09%09// If we have no principals, we're not authenticated%0A%09%09PrincipalCollection
  pri
@@ -1092,16 +1092,17 @@
 rincipal
+s
  = curre
@@ -1123,16 +1123,99 @@
 cipals()
+;%0A%09%09if (principals == null) %7B%0A%09%09%09return false;%0A%09%09%7D%0A%0A%09%09Object principal = principals
 .getPrim

Handle absence of authentication more sensibly, without an NPE