package org.intermine.webservice.server.user;

import java.util.Arrays;
import java.util.Map;

import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileManager;
import org.intermine.webservice.server.core.JSONService;
import org.intermine.webservice.server.exceptions.ServiceForbiddenException;
import org.intermine.webservice.server.output.JSONFormatter;

public class TokenService extends JSONService {


    private static final String DENIAL_MSG = "All token requests must be authenticated.";

    public TokenService(InterMineAPI im) {
        super(im);
    }

    @Override
    protected void execute() throws Exception {
        final ProfileManager pm = im.getProfileManager();
        Profile profile = getPermission().getProfile();

        String token = pm.generate24hrKey(profile);
        output.addResultItem(Arrays.asList("\"" + token + "\""));
    }

    @Override
    protected void validateState() {
        if (!isAuthenticated()) {
            throw new ServiceForbiddenException(DENIAL_MSG);
        }
    }

    @Override
    protected Map<String, Object> getHeaderAttributes() {
        Map<String, Object> retval = super.getHeaderAttributes();
        retval.put(JSONFormatter.KEY_INTRO, "\"token\":");
        return retval;
    }

}

@@ -68,30 +68,8 @@
 ays;
-%0Aimport java.util.Map;
 %0A%0Aim
@@ -253,16 +253,87 @@
 ervice;%0A
+import org.intermine.webservice.server.exceptions.BadRequestException;%0A
 import o
@@ -404,69 +404,8 @@
 ion;
-%0Aimport org.intermine.webservice.server.output.JSONFormatter;
 %0A%0Apu
@@ -792,124 +792,453 @@
 ();%0A
-%0A        String token = pm.generate24hrKey(profile);%0A        output.addResultItem(Arrays.asList(%22%5C%22%22 + token + %22%5C%22%22)
+        String tokenType = getOptionalParameter(%22type%22, %22day%22).toLowerCase();%0A        String token = null;%0A        if (%22day%22.equals(tokenType)) %7B%0A            token = pm.generate24hrKey(profile);%0A        %7D else if (%22perma%22.equals(tokenType)) %7B%0A            token = pm.generateReadOnlyAccessToken(profile);%0A        %7D else %7B%0A            throw new BadRequestException(%22Unknown token type: %22 + tokenType);%0A        %7D%0A        addResultValue(token, false
 );%0A 
@@ -1438,205 +1438,62 @@
 ted 
-Map%3C
 String
-, Object%3E getHeaderAttributes() %7B%0A        Map%3CString, Object%3E retval = super.getHeaderAttributes();%0A        retval.put(JSONFormatter.KEY_INTRO, %22%5C%22token%5C%22:%22);%0A        return retval
+ getResultsKey() %7B%0A        return %22token%22
 ;%0A    %7D%0A
 %0A%7D%0A
@@ -1489,11 +1489,10 @@
 ;%0A    %7D%0A
-%0A
 %7D%0A

Support more than one type of token.