@Override public Pair<User, Account> findUserByApiKey(String apiKey) { return _accountDao.findUserAccountByApiKey(apiKey); }
private String createUserApiKey(long userId) { try { UserVO updatedUser = _userDao.createForUpdate(); String encodedKey = null; Pair<User, Account> userAcct = null; int retryLimit = 10; do { // FIXME: what algorithm should we use for API keys? KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1"); SecretKey key = generator.generateKey(); encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded()); userAcct = _accountDao.findUserAccountByApiKey(encodedKey); retryLimit--; } while ((userAcct != null) && (retryLimit >= 0)); if (userAcct != null) { return null; } updatedUser.setApiKey(encodedKey); _userDao.update(userId, updatedUser); return encodedKey; } catch (NoSuchAlgorithmException ex) { s_logger.error("error generating secret key for user id=" + userId, ex); } return null; }
/** * Validates user API and Secret keys. If a new pair of keys is provided, we update them in the user POJO. * <ul> * <li>When updating the keys, it must be provided a pair (API and Secret keys); otherwise, an {@link InvalidParameterValueException} is thrown. * <li>If a pair of keys is provided, we validate to see if there is an user already using the provided API key. If there is someone else using, we throw an {@link InvalidParameterValueException} because two users cannot have the same API key. * </ul> */ protected void validateAndUpdateApiAndSecretKeyIfNeeded(UpdateUserCmd updateUserCmd, UserVO user) { String apiKey = updateUserCmd.getApiKey(); String secretKey = updateUserCmd.getSecretKey(); boolean isApiKeyBlank = StringUtils.isBlank(apiKey); boolean isSecretKeyBlank = StringUtils.isBlank(secretKey); if (isApiKeyBlank ^ isSecretKeyBlank) { throw new InvalidParameterValueException("Please provide a userApiKey/userSecretKey pair"); } if (isApiKeyBlank && isSecretKeyBlank) { return; } Pair<User, Account> apiKeyOwner = _accountDao.findUserAccountByApiKey(apiKey); if (apiKeyOwner != null) { User userThatHasTheProvidedApiKey = apiKeyOwner.first(); if (userThatHasTheProvidedApiKey.getId() != user.getId()) { throw new InvalidParameterValueException(String.format("The API key [%s] already exists in the system. Please provide a unique key.", apiKey)); } } user.setApiKey(apiKey); user.setSecretKey(secretKey); }