
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import uws.UWSException;
import uws.job.user.JobOwner;
import uws.job.user.DefaultJobOwner;
import uws.service.UserIdentifier;
import uws.service.UWSUrl;

import org.json.JSONArray;
import org.json.JSONObject;

public class UWSMCutoutUserIdentifier implements UserIdentifier
{
   // returns null if no security configured
   // throws exception if UserPrincipal not of expected type
   // returns AuthPolicy  (UserName and UserGroups) otherwise
   public JobOwner extractUserId(UWSUrl urlInterpreter, HttpServletRequest request) throws UWSException
   {
      // if security not configured, there is no job-owner

      if(request.getUserPrincipal() == null)
         return null;

      // if security configured, try to get user

      AuthPolicy auth = null; 
      try
      {
         // we need to exec the check inside AuthPolicy-constructor here
         // because this is called before every UWS-action and JobWork only at PHASE=RUN
         // Otherwise we could only pass UserPrincipal and use AuthPolicy in JobWork

         auth = new AuthPolicy(request.getUserPrincipal());
      }
      catch(IllegalArgumentException iae)
      {
         // UserPrincipal of not expected type -> access not allowed on this system
         throw new UWSException(UWSException.BAD_REQUEST, iae);
      }

      UWSMCutoutJobOwner jobOwner = new UWSMCutoutJobOwner(auth);

      return jobOwner;
   }

   public JobOwner restoreUser(final String id, final String pseudo, final Map<String,Object> otherData) throws UWSException
   {
      return new DefaultJobOwner(id,pseudo);
   }

}
