Search in sources :

Example 6 with ApiToken

use of edu.harvard.iq.dataverse.authorization.users.ApiToken in project dataverse by IQSS.

the class ConfigureFragmentBean method getConfigurePopupToolHandler.

public ExternalToolHandler getConfigurePopupToolHandler() {
    if (fileId == null) {
        // on first UI load, method is called before fileId is set. There may be a better way to handle this
        return null;
    }
    if (toolHandler != null) {
        return toolHandler;
    }
    datafileService.find(fileId);
    ApiToken apiToken = new ApiToken();
    User user = session.getUser();
    if (user instanceof AuthenticatedUser) {
        apiToken = authService.findApiTokenByUser((AuthenticatedUser) user);
    }
    toolHandler = new ExternalToolHandler(tool, datafileService.find(fileId), apiToken);
    return toolHandler;
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) ExternalToolHandler(edu.harvard.iq.dataverse.externaltools.ExternalToolHandler) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 7 with ApiToken

use of edu.harvard.iq.dataverse.authorization.users.ApiToken in project dataverse by IQSS.

the class ExternalToolHandler method getQueryParam.

private String getQueryParam(String key, String value) {
    ReservedWord reservedWord = ReservedWord.fromString(value);
    switch(reservedWord) {
        case FILE_ID:
            // getDataFile is never null because of the constructor
            return key + "=" + getDataFile().getId();
        case SITE_URL:
            return key + "=" + SystemConfig.getDataverseSiteUrlStatic();
        case API_TOKEN:
            String apiTokenString = null;
            ApiToken theApiToken = getApiToken();
            if (theApiToken != null) {
                apiTokenString = theApiToken.getTokenString();
                return key + "=" + apiTokenString;
            }
            break;
        default:
            break;
    }
    return null;
}
Also used : ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) ReservedWord(edu.harvard.iq.dataverse.externaltools.ExternalTool.ReservedWord)

Example 8 with ApiToken

use of edu.harvard.iq.dataverse.authorization.users.ApiToken in project dataverse by IQSS.

the class AuthenticationServiceBean method generateApiTokenForUser.

// A method for generating a new API token;
// TODO: this is a simple, one-size-fits-all solution; we'll need
// to expand this system, to be able to generate tokens with different
// lifecycles/valid for specific actions only, etc.
// -- L.A. 4.0 beta12
public ApiToken generateApiTokenForUser(AuthenticatedUser au) {
    if (au == null) {
        return null;
    }
    ApiToken apiToken = new ApiToken();
    apiToken.setTokenString(java.util.UUID.randomUUID().toString());
    apiToken.setAuthenticatedUser(au);
    Calendar c = Calendar.getInstance();
    apiToken.setCreateTime(new Timestamp(c.getTimeInMillis()));
    c.roll(Calendar.YEAR, 1);
    apiToken.setExpireTime(new Timestamp(c.getTimeInMillis()));
    save(apiToken);
    actionLogSvc.log(new ActionLogRecord(ActionLogRecord.ActionType.Auth, "generateApiToken").setInfo("user:" + au.getIdentifier() + " token:" + apiToken.getTokenString()));
    return apiToken;
}
Also used : ActionLogRecord(edu.harvard.iq.dataverse.actionlogging.ActionLogRecord) Calendar(java.util.Calendar) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) Timestamp(java.sql.Timestamp)

Example 9 with ApiToken

use of edu.harvard.iq.dataverse.authorization.users.ApiToken in project dataverse by IQSS.

the class BuiltinUsers method getApiToken.

@GET
@Path("{username}/api-token")
public Response getApiToken(@PathParam("username") String username, @QueryParam("password") String password) {
    boolean disabled = true;
    boolean lookupAllowed = settingsSvc.isTrueForKey(SettingsServiceBean.Key.AllowApiTokenLookupViaApi, false);
    if (lookupAllowed) {
        disabled = false;
    }
    if (disabled) {
        return error(Status.FORBIDDEN, "This API endpoint has been disabled.");
    }
    BuiltinUser u = null;
    if (retrievingApiTokenViaEmailEnabled) {
        u = builtinUserSvc.findByUsernameOrEmail(username);
    } else {
        u = builtinUserSvc.findByUserName(username);
    }
    if (u == null)
        return badRequest("Bad username or password");
    boolean passwordOk = PasswordEncryption.getVersion(u.getPasswordEncryptionVersion()).check(password, u.getEncryptedPassword());
    if (!passwordOk)
        return badRequest("Bad username or password");
    AuthenticatedUser authUser = authSvc.lookupUser(BuiltinAuthenticationProvider.PROVIDER_ID, u.getUserName());
    ApiToken t = authSvc.findApiTokenByUser(authUser);
    return (t != null) ? ok(t.getTokenString()) : notFound("User " + username + " does not have an API token");
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 10 with ApiToken

use of edu.harvard.iq.dataverse.authorization.users.ApiToken in project dataverse by IQSS.

the class BuiltinUsers method internalSave.

private Response internalSave(BuiltinUser user, String password, String key) {
    String expectedKey = settingsSvc.get(API_KEY_IN_SETTINGS);
    if (expectedKey == null) {
        return error(Status.SERVICE_UNAVAILABLE, "Dataverse config issue: No API key defined for built in user management");
    }
    if (!expectedKey.equals(key)) {
        return badApiKey(key);
    }
    ActionLogRecord alr = new ActionLogRecord(ActionLogRecord.ActionType.BuiltinUser, "create");
    try {
        if (password != null) {
            user.updateEncryptedPassword(PasswordEncryption.get().encrypt(password), PasswordEncryption.getLatestVersionNumber());
        }
        // Make sure the identifier is unique
        if ((builtinUserSvc.findByUserName(user.getUserName()) != null) || (authSvc.identifierExists(user.getUserName()))) {
            return error(Status.BAD_REQUEST, "username '" + user.getUserName() + "' already exists");
        }
        user = builtinUserSvc.save(user);
        AuthenticatedUser au = authSvc.createAuthenticatedUser(new UserRecordIdentifier(BuiltinAuthenticationProvider.PROVIDER_ID, user.getUserName()), user.getUserName(), user.getDisplayInfo(), false);
        /**
         * @todo Move this to
         * AuthenticationServiceBean.createAuthenticatedUser
         */
        boolean rootDataversePresent = false;
        try {
            Dataverse rootDataverse = dataverseSvc.findRootDataverse();
            if (rootDataverse != null) {
                rootDataversePresent = true;
            }
        } catch (Exception e) {
            logger.info("The root dataverse is not present. Don't send a notification to dataverseAdmin.");
        }
        if (rootDataversePresent) {
            userNotificationSvc.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
        }
        ApiToken token = new ApiToken();
        token.setTokenString(java.util.UUID.randomUUID().toString());
        token.setAuthenticatedUser(au);
        Calendar c = Calendar.getInstance();
        token.setCreateTime(new Timestamp(c.getTimeInMillis()));
        c.roll(Calendar.YEAR, 1);
        token.setExpireTime(new Timestamp(c.getTimeInMillis()));
        authSvc.save(token);
        JsonObjectBuilder resp = Json.createObjectBuilder();
        resp.add("user", json(user));
        resp.add("authenticatedUser", json(au));
        resp.add("apiToken", token.getTokenString());
        alr.setInfo("builtinUser:" + user.getUserName() + " authenticatedUser:" + au.getIdentifier());
        return ok(resp);
    } catch (EJBException ejbx) {
        alr.setActionResult(ActionLogRecord.Result.InternalError);
        alr.setInfo(alr.getInfo() + "// " + ejbx.getMessage());
        if (ejbx.getCausedByException() instanceof IllegalArgumentException) {
            return error(Status.BAD_REQUEST, "Bad request: can't save user. " + ejbx.getCausedByException().getMessage());
        } else {
            logger.log(Level.WARNING, "Error saving user: ", ejbx);
            return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + ejbx.getMessage());
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Error saving user", e);
        alr.setActionResult(ActionLogRecord.Result.InternalError);
        alr.setInfo(alr.getInfo() + "// " + e.getMessage());
        return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + e.getMessage());
    } finally {
        actionLogSvc.log(alr);
    }
}
Also used : UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) Calendar(java.util.Calendar) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) Timestamp(java.sql.Timestamp) EJBException(javax.ejb.EJBException) Date(java.util.Date) ActionLogRecord(edu.harvard.iq.dataverse.actionlogging.ActionLogRecord) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) JsonObjectBuilder(javax.json.JsonObjectBuilder) EJBException(javax.ejb.EJBException)

Aggregations

ApiToken (edu.harvard.iq.dataverse.authorization.users.ApiToken)11 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)6 DataFile (edu.harvard.iq.dataverse.DataFile)3 ActionLogRecord (edu.harvard.iq.dataverse.actionlogging.ActionLogRecord)3 Timestamp (java.sql.Timestamp)3 Calendar (java.util.Calendar)3 Test (org.junit.Test)3 User (edu.harvard.iq.dataverse.authorization.users.User)2 ExternalToolHandler (edu.harvard.iq.dataverse.externaltools.ExternalToolHandler)2 JsonObjectBuilder (javax.json.JsonObjectBuilder)2 DataTable (edu.harvard.iq.dataverse.DataTable)1 Dataverse (edu.harvard.iq.dataverse.Dataverse)1 UserRecordIdentifier (edu.harvard.iq.dataverse.authorization.UserRecordIdentifier)1 BuiltinAuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinAuthenticationProvider)1 BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)1 AbstractOAuth2AuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.oauth2.AbstractOAuth2AuthenticationProvider)1 ShibAuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider)1 ConfirmEmailData (edu.harvard.iq.dataverse.confirmemail.ConfirmEmailData)1 ReservedWord (edu.harvard.iq.dataverse.externaltools.ExternalTool.ReservedWord)1 IOException (java.io.IOException)1