diff --git a/managed/src/main/java/com/yugabyte/yw/models/Users.java b/managed/src/main/java/com/yugabyte/yw/models/Users.java index f2d4db6f2a8f..94e7f0045632 100644 --- a/managed/src/main/java/com/yugabyte/yw/models/Users.java +++ b/managed/src/main/java/com/yugabyte/yw/models/Users.java @@ -406,6 +406,7 @@ public String upsertApiToken() { } public String upsertApiToken(Long version) { + String apiTokenFormatVersion = "2"; UUID uuidToLock = uuid != null ? uuid : NULL_UUID; usersLock.acquireLock(uuidToLock); try { @@ -420,7 +421,9 @@ public String upsertApiToken(Long version) { apiTokenVersion = apiTokenVersion == null ? 1L : apiTokenVersion + 1; save(); - return apiTokenUnhashed; + // new format of api token = apiTokenFormatVersion$userUUID$apiTokenUnhashed + return apiTokenFormatVersion + "$" + uuid + "$" + apiTokenUnhashed; + } finally { usersLock.releaseLock(uuidToLock); } @@ -472,12 +475,41 @@ public static Users authWithApiToken(String apiToken) { return null; } + // Supporting the 2 formats of api token + // 1. apiTokenFormatVersion$userUUID$apiToken (newer format) + // 2. apiToken (older format) + + // The second format would lead to performance degradation in the case of more than 10 users + // Recommended to reissue the token (which will follow the first format) + try { - List usersList = find.query().where().isNotNull("apiToken").findList(); - for (Users user : usersList) { - if (Users.hasher.isValid(apiToken, user.getApiToken())) { - return user; + if (apiToken.contains("$")) { + // to authenticate new format of api token = apiTokenFormatVersion$userUUID$apiTokenUnhashed + String[] parts = apiToken.split("\\$"); + UUID userUUID = UUID.fromString(parts[1]); + String apiTokenUnhashed = parts[2]; + Users userWithToken = find.query().where().eq("uuid", userUUID).findOne(); + if (userWithToken != null) { + if (Users.hasher.isValid(apiTokenUnhashed, userWithToken.getApiToken())) { + return userWithToken; + } + } + } else { + // to authenticate old format of api token + LOG.warn("Using older API token format. Renew to improve performance."); + List usersList = find.query().where().isNotNull("apiToken").findList(); + long startTime = System.currentTimeMillis(); + for (Users user : usersList) { + if (Users.hasher.isValid(apiToken, user.getApiToken())) { + LOG.info( + "Authentication using API token. Completed time: {} ms", + System.currentTimeMillis() - startTime); + return user; + } } + LOG.info( + "Authentication using API token. Completed time: {} ms", + System.currentTimeMillis() - startTime); } return null; } catch (Exception e) {