From 458c3b62e86f3ef8956c735103696009d2160599 Mon Sep 17 00:00:00 2001 From: Sattvik Chakravarthy Date: Fri, 1 Mar 2024 15:44:20 +0530 Subject: [PATCH] fix: session changes --- .../java/io/supertokens/session/Session.java | 229 +++++++++--------- .../webserver/api/session/HandshakeAPI.java | 8 +- .../webserver/api/session/JWTDataAPI.java | 27 ++- .../api/session/RefreshSessionAPI.java | 18 +- .../webserver/api/session/SessionAPI.java | 34 +-- .../webserver/api/session/SessionDataAPI.java | 27 ++- .../api/session/SessionRegenerateAPI.java | 1 - .../api/session/SessionRemoveAPI.java | 26 +- .../webserver/api/session/SessionUserAPI.java | 10 +- 9 files changed, 199 insertions(+), 181 deletions(-) diff --git a/src/main/java/io/supertokens/session/Session.java b/src/main/java/io/supertokens/session/Session.java index aa41b3ae8..66aea184a 100644 --- a/src/main/java/io/supertokens/session/Session.java +++ b/src/main/java/io/supertokens/session/Session.java @@ -29,6 +29,7 @@ import io.supertokens.multitenancy.Multitenancy; import io.supertokens.pluginInterface.STORAGE_TYPE; import io.supertokens.pluginInterface.Storage; +import io.supertokens.pluginInterface.StorageUtils; import io.supertokens.pluginInterface.authRecipe.AuthRecipeStorage; import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo; import io.supertokens.pluginInterface.authRecipe.LoginMethod; @@ -66,7 +67,7 @@ public class Session { @TestOnly - public static SessionInformationHolder createNewSession(TenantIdentifierWithStorage tenantIdentifierWithStorage, + public static SessionInformationHolder createNewSession(TenantIdentifier tenantIdentifier, Storage storage, Main main, @Nonnull String recipeUserId, @Nonnull JsonObject userDataInJWT, @@ -76,9 +77,8 @@ public static SessionInformationHolder createNewSession(TenantIdentifierWithStor BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException, UnauthorisedException, JWT.JWTException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError { try { - return createNewSession(tenantIdentifierWithStorage, main, recipeUserId, userDataInJWT, userDataInDatabase, - false, - AccessToken.getLatestVersion(), false); + return createNewSession(tenantIdentifier, storage, main, recipeUserId, userDataInJWT, userDataInDatabase, + false, AccessToken.getLatestVersion(), false); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -96,7 +96,7 @@ public static SessionInformationHolder createNewSession(Main main, Storage storage = StorageLayer.getStorage(main); try { return createNewSession( - new TenantIdentifierWithStorage(null, null, null, storage), main, + new TenantIdentifier(null, null, null), storage, main, recipeUserId, userDataInJWT, userDataInDatabase, false, AccessToken.getLatestVersion(), false); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -116,14 +116,14 @@ public static SessionInformationHolder createNewSession(Main main, @Nonnull Stri Storage storage = StorageLayer.getStorage(main); try { return createNewSession( - new TenantIdentifierWithStorage(null, null, null, storage), main, + new TenantIdentifier(null, null, null), storage, main, recipeUserId, userDataInJWT, userDataInDatabase, enableAntiCsrf, version, useStaticKey); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } } - public static SessionInformationHolder createNewSession(TenantIdentifierWithStorage tenantIdentifierWithStorage, + public static SessionInformationHolder createNewSession(TenantIdentifier tenantIdentifier, Storage storage, Main main, @Nonnull String recipeUserId, @Nonnull JsonObject userDataInJWT, @Nonnull JsonObject userDataInDatabase, @@ -134,30 +134,30 @@ public static SessionInformationHolder createNewSession(TenantIdentifierWithStor BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException, AccessTokenPayloadError, UnsupportedJWTSigningAlgorithmException, TenantOrAppNotFoundException { String sessionHandle = UUID.randomUUID().toString(); - if (!tenantIdentifierWithStorage.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID)) { - sessionHandle += "_" + tenantIdentifierWithStorage.getTenantId(); + if (!tenantIdentifier.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID)) { + sessionHandle += "_" + tenantIdentifier.getTenantId(); } String primaryUserId = recipeUserId; - if (tenantIdentifierWithStorage.getStorage().getType().equals(STORAGE_TYPE.SQL)) { - primaryUserId = tenantIdentifierWithStorage.getAuthRecipeStorage() - .getPrimaryUserIdStrForUserId(tenantIdentifierWithStorage.toAppIdentifier(), recipeUserId); + if (storage.getType().equals(STORAGE_TYPE.SQL)) { + primaryUserId = StorageUtils.getAuthRecipeStorage(storage) + .getPrimaryUserIdStrForUserId(tenantIdentifier.toAppIdentifier(), recipeUserId); if (primaryUserId == null) { primaryUserId = recipeUserId; } } String antiCsrfToken = enableAntiCsrf ? UUID.randomUUID().toString() : null; - final TokenInfo refreshToken = RefreshToken.createNewRefreshToken(tenantIdentifierWithStorage, main, + final TokenInfo refreshToken = RefreshToken.createNewRefreshToken(tenantIdentifier, main, sessionHandle, recipeUserId, null, antiCsrfToken); - TokenInfo accessToken = AccessToken.createNewAccessToken(tenantIdentifierWithStorage, main, sessionHandle, + TokenInfo accessToken = AccessToken.createNewAccessToken(tenantIdentifier, main, sessionHandle, recipeUserId, primaryUserId, Utils.hashSHA256(refreshToken.token), null, userDataInJWT, antiCsrfToken, null, version, useStaticKey); - tenantIdentifierWithStorage.getSessionStorage() - .createNewSession(tenantIdentifierWithStorage, sessionHandle, recipeUserId, + StorageUtils.getSessionStorage(storage) + .createNewSession(tenantIdentifier, sessionHandle, recipeUserId, Utils.hashSHA256(Utils.hashSHA256(refreshToken.token)), userDataInDatabase, refreshToken.expiry, userDataInJWT, refreshToken.createdTime, useStaticKey); @@ -165,7 +165,7 @@ public static SessionInformationHolder createNewSession(TenantIdentifierWithStor refreshToken.createdTime); return new SessionInformationHolder( new SessionInfo(sessionHandle, primaryUserId, recipeUserId, userDataInJWT, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), accessToken, refreshToken, idRefreshToken, antiCsrfToken); } @@ -212,13 +212,13 @@ public static SessionInformationHolder regenerateToken(AppIdentifier appIdentifi // We assume the token has already been verified at this point. It may be expired or JWT signing key may have // changed for it... AccessTokenInfo accessToken = AccessToken.getInfoFromAccessTokenWithoutVerifying(appIdentifier, token); - TenantIdentifierWithStorage tenantIdentifierWithStorage = accessToken.tenantIdentifier.withStorage( - StorageLayer.getStorage(accessToken.tenantIdentifier, main)); - io.supertokens.pluginInterface.session.SessionInfo sessionInfo = getSession(tenantIdentifierWithStorage, + TenantIdentifier tenantIdentifier = accessToken.tenantIdentifier; + Storage storage = StorageLayer.getStorage(accessToken.tenantIdentifier, main); + io.supertokens.pluginInterface.session.SessionInfo sessionInfo = getSession(tenantIdentifier, storage, accessToken.sessionHandle); JsonObject newJWTUserPayload = userDataInJWT == null ? sessionInfo.userDataInJWT : userDataInJWT; - updateSession(tenantIdentifierWithStorage, accessToken.sessionHandle, null, newJWTUserPayload, + updateSession(tenantIdentifier, storage, accessToken.sessionHandle, null, newJWTUserPayload, accessToken.version); // if the above succeeds but the below fails, it's OK since the client will get server error and will try @@ -230,11 +230,11 @@ public static SessionInformationHolder regenerateToken(AppIdentifier appIdentifi return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, newJWTUserPayload, - tenantIdentifierWithStorage.getTenantId()), null, null, null, + tenantIdentifier.getTenantId()), null, null, null, null); } - TokenInfo newAccessToken = AccessToken.createNewAccessToken(tenantIdentifierWithStorage, main, + TokenInfo newAccessToken = AccessToken.createNewAccessToken(tenantIdentifier, main, accessToken.sessionHandle, accessToken.recipeUserId, accessToken.primaryUserId, accessToken.refreshTokenHash1, accessToken.parentRefreshTokenHash1, newJWTUserPayload, accessToken.antiCsrfToken, accessToken.expiryTime, accessToken.version, sessionInfo.useStaticKey); @@ -242,7 +242,7 @@ public static SessionInformationHolder regenerateToken(AppIdentifier appIdentifi return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, newJWTUserPayload, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), new TokenInfo(newAccessToken.token, newAccessToken.expiry, newAccessToken.createdTime), null, null, null); } @@ -260,14 +260,14 @@ public static SessionInformationHolder regenerateTokenBeforeCDI2_21(AppIdentifie // We assume the token has already been verified at this point. It may be expired or JWT signing key may have // changed for it... AccessTokenInfo accessToken = AccessToken.getInfoFromAccessTokenWithoutVerifying(appIdentifier, token); - TenantIdentifierWithStorage tenantIdentifierWithStorage = accessToken.tenantIdentifier.withStorage( - StorageLayer.getStorage(accessToken.tenantIdentifier, main)); - io.supertokens.pluginInterface.session.SessionInfo sessionInfo = getSession(tenantIdentifierWithStorage, + TenantIdentifier tenantIdentifier = accessToken.tenantIdentifier; + Storage storage = StorageLayer.getStorage(accessToken.tenantIdentifier, main); + io.supertokens.pluginInterface.session.SessionInfo sessionInfo = getSession(tenantIdentifier, storage, accessToken.sessionHandle); JsonObject newJWTUserPayload = userDataInJWT == null ? sessionInfo.userDataInJWT : userDataInJWT; updateSessionBeforeCDI2_21( - tenantIdentifierWithStorage, + tenantIdentifier, storage, accessToken.sessionHandle, null, newJWTUserPayload); // if the above succeeds but the below fails, it's OK since the client will get server error and will try @@ -279,7 +279,7 @@ public static SessionInformationHolder regenerateTokenBeforeCDI2_21(AppIdentifie return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, newJWTUserPayload, - tenantIdentifierWithStorage.getTenantId()), null, null, null, + tenantIdentifier.getTenantId()), null, null, null, null); } @@ -292,7 +292,7 @@ public static SessionInformationHolder regenerateTokenBeforeCDI2_21(AppIdentifie return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, newJWTUserPayload, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), new TokenInfo(newAccessToken.token, newAccessToken.expiry, newAccessToken.createdTime), null, null, null); } @@ -322,8 +322,8 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M AccessTokenInfo accessToken = AccessToken.getInfoFromAccessToken(appIdentifier, main, token, doAntiCsrfCheck && enableAntiCsrf); - TenantIdentifierWithStorage tenantIdentifierWithStorage = accessToken.tenantIdentifier.withStorage( - StorageLayer.getStorage(accessToken.tenantIdentifier, main)); + TenantIdentifier tenantIdentifier = accessToken.tenantIdentifier; + Storage storage = StorageLayer.getStorage(accessToken.tenantIdentifier, main); if (enableAntiCsrf && doAntiCsrfCheck && (antiCsrfToken == null || !antiCsrfToken.equals(accessToken.antiCsrfToken))) { @@ -332,8 +332,8 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M io.supertokens.pluginInterface.session.SessionInfo sessionInfoForBlacklisting = null; if (checkDatabase) { - sessionInfoForBlacklisting = tenantIdentifierWithStorage.getSessionStorage() - .getSession(tenantIdentifierWithStorage, accessToken.sessionHandle); + sessionInfoForBlacklisting = StorageUtils.getSessionStorage(storage) + .getSession(tenantIdentifier, accessToken.sessionHandle); if (sessionInfoForBlacklisting == null) { throw new UnauthorisedException("Either the session has ended or has been blacklisted"); } @@ -347,25 +347,25 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, accessToken.userData, - tenantIdentifierWithStorage.getTenantId()), null, null, + tenantIdentifier.getTenantId()), null, null, null, null); } ProcessState.getInstance(main).addState(ProcessState.PROCESS_STATE.GET_SESSION_NEW_TOKENS, null); - if (tenantIdentifierWithStorage.getSessionStorage().getType() == STORAGE_TYPE.SQL) { - SessionSQLStorage storage = (SessionSQLStorage) tenantIdentifierWithStorage.getSessionStorage(); + if (StorageUtils.getSessionStorage(storage).getType() == STORAGE_TYPE.SQL) { + SessionSQLStorage sessionStorage = (SessionSQLStorage) StorageUtils.getSessionStorage(storage); try { - CoreConfig config = Config.getConfig(tenantIdentifierWithStorage, main); - return storage.startTransaction(con -> { + CoreConfig config = Config.getConfig(tenantIdentifier, main); + return sessionStorage.startTransaction(con -> { try { - io.supertokens.pluginInterface.session.SessionInfo sessionInfo = storage - .getSessionInfo_Transaction(tenantIdentifierWithStorage, con, + io.supertokens.pluginInterface.session.SessionInfo sessionInfo = sessionStorage + .getSessionInfo_Transaction(tenantIdentifier, con, accessToken.sessionHandle); if (sessionInfo == null) { - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); throw new UnauthorisedException("Session missing in db"); } @@ -375,23 +375,23 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M || sessionInfo.refreshTokenHash2.equals(Utils.hashSHA256(accessToken.refreshTokenHash1)) || JWTPayloadNeedsUpdating) { if (promote) { - storage.updateSessionInfo_Transaction(tenantIdentifierWithStorage, con, + sessionStorage.updateSessionInfo_Transaction(tenantIdentifier, con, accessToken.sessionHandle, Utils.hashSHA256(accessToken.refreshTokenHash1), System.currentTimeMillis() + config.getRefreshTokenValidity()); } - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); TokenInfo newAccessToken; if (AccessToken.getAccessTokenVersion(accessToken) == AccessToken.VERSION.V1) { - newAccessToken = AccessToken.createNewAccessTokenV1(tenantIdentifierWithStorage, + newAccessToken = AccessToken.createNewAccessTokenV1(tenantIdentifier, main, accessToken.sessionHandle, accessToken.recipeUserId, accessToken.refreshTokenHash1, null, sessionInfo.userDataInJWT, accessToken.antiCsrfToken); } else { - newAccessToken = AccessToken.createNewAccessToken(tenantIdentifierWithStorage, main, + newAccessToken = AccessToken.createNewAccessToken(tenantIdentifier, main, accessToken.sessionHandle, accessToken.recipeUserId, accessToken.primaryUserId, accessToken.refreshTokenHash1, null, @@ -402,17 +402,17 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, - sessionInfo.userDataInJWT, tenantIdentifierWithStorage.getTenantId()), + sessionInfo.userDataInJWT, tenantIdentifier.getTenantId()), new TokenInfo(newAccessToken.token, newAccessToken.expiry, newAccessToken.createdTime), null, null, null); } - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, accessToken.userData, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), // here we purposely use accessToken.userData instead of sessionInfo.userDataInJWT // because we are not returning a new access token null, null, null, null); @@ -434,13 +434,13 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M } throw e; } - } else if (tenantIdentifierWithStorage.getSessionStorage().getType() == + } else if (StorageUtils.getSessionStorage(storage).getType() == STORAGE_TYPE.NOSQL_1) { - SessionNoSQLStorage_1 storage = (SessionNoSQLStorage_1) tenantIdentifierWithStorage.getSessionStorage(); + SessionNoSQLStorage_1 sessionStorage = (SessionNoSQLStorage_1) StorageUtils.getSessionStorage(storage); while (true) { try { - io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = storage + io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = sessionStorage .getSessionInfo_Transaction(accessToken.sessionHandle); if (sessionInfo == null) { @@ -452,9 +452,9 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M if (promote || sessionInfo.refreshTokenHash2.equals(Utils.hashSHA256(accessToken.refreshTokenHash1)) || JWTPayloadNeedsUpdating) { if (promote) { - boolean success = storage.updateSessionInfo_Transaction(accessToken.sessionHandle, + boolean success = sessionStorage.updateSessionInfo_Transaction(accessToken.sessionHandle, Utils.hashSHA256(accessToken.refreshTokenHash1), - System.currentTimeMillis() + Config.getConfig(tenantIdentifierWithStorage, main) + System.currentTimeMillis() + Config.getConfig(tenantIdentifier, main) .getRefreshTokenValidity(), sessionInfo.lastUpdatedSign); if (!success) { @@ -464,13 +464,13 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M TokenInfo newAccessToken; if (accessToken.version == AccessToken.VERSION.V1) { - newAccessToken = AccessToken.createNewAccessTokenV1(tenantIdentifierWithStorage, main, + newAccessToken = AccessToken.createNewAccessTokenV1(tenantIdentifier, main, accessToken.sessionHandle, accessToken.recipeUserId, accessToken.refreshTokenHash1, null, sessionInfo.userDataInJWT, accessToken.antiCsrfToken); } else { - newAccessToken = AccessToken.createNewAccessToken(tenantIdentifierWithStorage, main, + newAccessToken = AccessToken.createNewAccessToken(tenantIdentifier, main, accessToken.sessionHandle, accessToken.recipeUserId, accessToken.primaryUserId, accessToken.refreshTokenHash1, null, sessionInfo.userDataInJWT, @@ -480,7 +480,7 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, - sessionInfo.userDataInJWT, tenantIdentifierWithStorage.getTenantId()), + sessionInfo.userDataInJWT, tenantIdentifier.getTenantId()), new TokenInfo(newAccessToken.token, newAccessToken.expiry, newAccessToken.createdTime), null, null, null); } @@ -488,7 +488,7 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M return new SessionInformationHolder( new SessionInfo(accessToken.sessionHandle, accessToken.primaryUserId, accessToken.recipeUserId, accessToken.userData, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), // here we purposely use accessToken.userData instead of sessionInfo.userDataInJWT // because we are not returning a new access token null, null, null, null); @@ -534,13 +534,14 @@ public static SessionInformationHolder refreshSession(AppIdentifier appIdentifie } } - return refreshSessionHelper(refreshTokenInfo.tenantIdentifier.withStorage( - StorageLayer.getStorage(refreshTokenInfo.tenantIdentifier, main)), - main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion); + TenantIdentifier tenantIdentifier = refreshTokenInfo.tenantIdentifier; + Storage storage = StorageLayer.getStorage(refreshTokenInfo.tenantIdentifier, main); + return refreshSessionHelper( + tenantIdentifier, storage, main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion); } private static SessionInformationHolder refreshSessionHelper( - TenantIdentifierWithStorage tenantIdentifierWithStorage, Main main, String refreshToken, + TenantIdentifier tenantIdentifier, Storage storage, Main main, String refreshToken, RefreshToken.RefreshTokenInfo refreshTokenInfo, boolean enableAntiCsrf, AccessToken.VERSION accessTokenVersion) @@ -553,31 +554,31 @@ private static SessionInformationHolder refreshSessionHelper( ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// - if (tenantIdentifierWithStorage.getSessionStorage().getType() == STORAGE_TYPE.SQL) { - SessionSQLStorage storage = (SessionSQLStorage) tenantIdentifierWithStorage.getSessionStorage(); + if (StorageUtils.getSessionStorage(storage).getType() == STORAGE_TYPE.SQL) { + SessionSQLStorage sessionStorage = (SessionSQLStorage) StorageUtils.getSessionStorage(storage); try { - CoreConfig config = Config.getConfig(tenantIdentifierWithStorage, main); - return storage.startTransaction(con -> { + CoreConfig config = Config.getConfig(tenantIdentifier, main); + return sessionStorage.startTransaction(con -> { try { String sessionHandle = refreshTokenInfo.sessionHandle; - io.supertokens.pluginInterface.session.SessionInfo sessionInfo = storage - .getSessionInfo_Transaction(tenantIdentifierWithStorage, con, sessionHandle); + io.supertokens.pluginInterface.session.SessionInfo sessionInfo = sessionStorage + .getSessionInfo_Transaction(tenantIdentifier, con, sessionHandle); if (sessionInfo == null || sessionInfo.expiry < System.currentTimeMillis()) { - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); throw new UnauthorisedException("Session missing in db or has expired"); } if (sessionInfo.refreshTokenHash2.equals(Utils.hashSHA256(Utils.hashSHA256(refreshToken)))) { // at this point, the input refresh token is the parent one. - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); String antiCsrfToken = enableAntiCsrf ? UUID.randomUUID().toString() : null; final TokenInfo newRefreshToken = RefreshToken.createNewRefreshToken( - tenantIdentifierWithStorage, main, sessionHandle, + tenantIdentifier, main, sessionHandle, sessionInfo.recipeUserId, Utils.hashSHA256(refreshToken), antiCsrfToken); - TokenInfo newAccessToken = AccessToken.createNewAccessToken(tenantIdentifierWithStorage, + TokenInfo newAccessToken = AccessToken.createNewAccessToken(tenantIdentifier, main, sessionHandle, sessionInfo.recipeUserId, sessionInfo.userId, Utils.hashSHA256(newRefreshToken.token), @@ -590,7 +591,7 @@ private static SessionInformationHolder refreshSessionHelper( return new SessionInformationHolder( new SessionInfo(sessionHandle, sessionInfo.userId, sessionInfo.recipeUserId, sessionInfo.userDataInJWT, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), newAccessToken, newRefreshToken, idRefreshToken, antiCsrfToken); } @@ -600,18 +601,18 @@ private static SessionInformationHolder refreshSessionHelper( || (refreshTokenInfo.parentRefreshTokenHash1 != null && Utils.hashSHA256(refreshTokenInfo.parentRefreshTokenHash1) .equals(sessionInfo.refreshTokenHash2))) { - storage.updateSessionInfo_Transaction(tenantIdentifierWithStorage, con, sessionHandle, + sessionStorage.updateSessionInfo_Transaction(tenantIdentifier, con, sessionHandle, Utils.hashSHA256(Utils.hashSHA256(refreshToken)), System.currentTimeMillis() + config.getRefreshTokenValidity()); - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); - return refreshSessionHelper(tenantIdentifierWithStorage, main, refreshToken, + return refreshSessionHelper(tenantIdentifier, storage, main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion); } - storage.commitTransaction(con); + sessionStorage.commitTransaction(con); throw new TokenTheftDetectedException(sessionHandle, sessionInfo.recipeUserId, sessionInfo.userId); @@ -644,13 +645,13 @@ private static SessionInformationHolder refreshSessionHelper( ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// - } else if (tenantIdentifierWithStorage.getSessionStorage().getType() == + } else if (StorageUtils.getSessionStorage(storage).getType() == STORAGE_TYPE.NOSQL_1) { - SessionNoSQLStorage_1 storage = (SessionNoSQLStorage_1) tenantIdentifierWithStorage.getSessionStorage(); + SessionNoSQLStorage_1 sessionStorage = (SessionNoSQLStorage_1) StorageUtils.getSessionStorage(storage); while (true) { try { String sessionHandle = refreshTokenInfo.sessionHandle; - io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = storage + io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = sessionStorage .getSessionInfo_Transaction(sessionHandle); if (sessionInfo == null || sessionInfo.expiry < System.currentTimeMillis()) { @@ -662,9 +663,9 @@ private static SessionInformationHolder refreshSessionHelper( String antiCsrfToken = enableAntiCsrf ? UUID.randomUUID().toString() : null; final TokenInfo newRefreshToken = RefreshToken.createNewRefreshToken( - tenantIdentifierWithStorage, main, sessionHandle, + tenantIdentifier, main, sessionHandle, sessionInfo.recipeUserId, Utils.hashSHA256(refreshToken), antiCsrfToken); - TokenInfo newAccessToken = AccessToken.createNewAccessToken(tenantIdentifierWithStorage, main, + TokenInfo newAccessToken = AccessToken.createNewAccessToken(tenantIdentifier, main, sessionHandle, sessionInfo.recipeUserId, sessionInfo.userId, Utils.hashSHA256(newRefreshToken.token), Utils.hashSHA256(refreshToken), sessionInfo.userDataInJWT, antiCsrfToken, @@ -676,7 +677,7 @@ private static SessionInformationHolder refreshSessionHelper( return new SessionInformationHolder( new SessionInfo(sessionHandle, sessionInfo.userId, sessionInfo.recipeUserId, sessionInfo.userDataInJWT, - tenantIdentifierWithStorage.getTenantId()), + tenantIdentifier.getTenantId()), newAccessToken, newRefreshToken, idRefreshToken, antiCsrfToken); } @@ -686,15 +687,15 @@ private static SessionInformationHolder refreshSessionHelper( || (refreshTokenInfo.parentRefreshTokenHash1 != null && Utils.hashSHA256(refreshTokenInfo.parentRefreshTokenHash1) .equals(sessionInfo.refreshTokenHash2))) { - boolean success = storage.updateSessionInfo_Transaction(sessionHandle, + boolean success = sessionStorage.updateSessionInfo_Transaction(sessionHandle, Utils.hashSHA256(Utils.hashSHA256(refreshToken)), System.currentTimeMillis() + - Config.getConfig(tenantIdentifierWithStorage, main).getRefreshTokenValidity(), + Config.getConfig(tenantIdentifier, main).getRefreshTokenValidity(), sessionInfo.lastUpdatedSign); if (!success) { continue; } - return refreshSessionHelper(tenantIdentifierWithStorage, main, refreshToken, refreshTokenInfo, + return refreshSessionHelper(tenantIdentifier, storage, main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion); } @@ -719,7 +720,7 @@ public static String[] revokeSessionUsingSessionHandles(Main main, throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return revokeSessionUsingSessionHandles(main, - new AppIdentifierWithStorage(null, null, storage), + new AppIdentifier(null, null), storage, sessionHandles); } @@ -823,12 +824,12 @@ public static String[] revokeAllSessionsForUser(Main main, AppIdentifier appIden return revokeSessionUsingSessionHandles(main, appIdentifier, storage, sessionHandles); } - public static String[] revokeAllSessionsForUser(Main main, TenantIdentifierWithStorage tenantIdentifierWithStorage, + public static String[] revokeAllSessionsForUser(Main main, TenantIdentifier tenantIdentifier, Storage storage, String userId, boolean revokeSessionsForLinkedAccounts) throws StorageQueryException { - String[] sessionHandles = getAllNonExpiredSessionHandlesForUser(tenantIdentifierWithStorage, userId, + String[] sessionHandles = getAllNonExpiredSessionHandlesForUser(tenantIdentifier, storage, userId, revokeSessionsForLinkedAccounts); - return revokeSessionUsingSessionHandles(main, tenantIdentifierWithStorage.toAppIdentifierWithStorage(), + return revokeSessionUsingSessionHandles(main, tenantIdentifier.toAppIdentifier(), storage, sessionHandles); } @@ -837,7 +838,7 @@ public static String[] getAllNonExpiredSessionHandlesForUser(Main main, String u throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getAllNonExpiredSessionHandlesForUser(main, - new AppIdentifierWithStorage(null, null, storage), userId, true); + new AppIdentifier(null, null), storage, userId, true); } public static String[] getAllNonExpiredSessionHandlesForUser( @@ -908,16 +909,16 @@ public static JsonObject getSessionData(Main main, String sessionHandle) throws StorageQueryException, UnauthorisedException { Storage storage = StorageLayer.getStorage(main); return getSessionData( - new TenantIdentifierWithStorage(null, null, null, storage), + new TenantIdentifier(null, null, null), storage, sessionHandle); } @Deprecated - public static JsonObject getSessionData(TenantIdentifierWithStorage tenantIdentifierWithStorage, + public static JsonObject getSessionData(TenantIdentifier tenantIdentifier, Storage storage, String sessionHandle) throws StorageQueryException, UnauthorisedException { - io.supertokens.pluginInterface.session.SessionInfo session = tenantIdentifierWithStorage.getSessionStorage() - .getSession(tenantIdentifierWithStorage, sessionHandle); + io.supertokens.pluginInterface.session.SessionInfo session = StorageUtils.getSessionStorage(storage) + .getSession(tenantIdentifier, sessionHandle); if (session == null || session.expiry <= System.currentTimeMillis()) { throw new UnauthorisedException("Session does not exist."); } @@ -929,15 +930,15 @@ public static JsonObject getJWTData(Main main, String sessionHandle) throws StorageQueryException, UnauthorisedException { Storage storage = StorageLayer.getStorage(main); return getJWTData( - new TenantIdentifierWithStorage(null, null, null, storage), + new TenantIdentifier(null, null, null), storage, sessionHandle); } @Deprecated - public static JsonObject getJWTData(TenantIdentifierWithStorage tenantIdentifierWithStorage, String sessionHandle) + public static JsonObject getJWTData(TenantIdentifier tenantIdentifier, Storage storage, String sessionHandle) throws StorageQueryException, UnauthorisedException { - io.supertokens.pluginInterface.session.SessionInfo session = tenantIdentifierWithStorage.getSessionStorage() - .getSession(tenantIdentifierWithStorage, sessionHandle); + io.supertokens.pluginInterface.session.SessionInfo session = StorageUtils.getSessionStorage(storage) + .getSession(tenantIdentifier, sessionHandle); if (session == null || session.expiry <= System.currentTimeMillis()) { throw new UnauthorisedException("Session does not exist."); } @@ -949,7 +950,7 @@ public static io.supertokens.pluginInterface.session.SessionInfo getSession(Main throws StorageQueryException, UnauthorisedException { Storage storage = StorageLayer.getStorage(main); return getSession( - new TenantIdentifierWithStorage(null, null, null, storage), + new TenantIdentifier(null, null, null), storage, sessionHandle); } @@ -959,10 +960,10 @@ public static io.supertokens.pluginInterface.session.SessionInfo getSession(Main * - /recipe/session GET */ public static io.supertokens.pluginInterface.session.SessionInfo getSession( - TenantIdentifierWithStorage tenantIdentifierWithStorage, String sessionHandle) + TenantIdentifier tenantIdentifier, Storage storage, String sessionHandle) throws StorageQueryException, UnauthorisedException { - io.supertokens.pluginInterface.session.SessionInfo session = tenantIdentifierWithStorage.getSessionStorage() - .getSession(tenantIdentifierWithStorage, sessionHandle); + io.supertokens.pluginInterface.session.SessionInfo session = StorageUtils.getSessionStorage(storage) + .getSession(tenantIdentifier, sessionHandle); // If there is no session, or session is expired if (session == null || session.expiry <= System.currentTimeMillis()) { @@ -979,11 +980,11 @@ public static void updateSession(Main main, String sessionHandle, AccessToken.VERSION version) throws StorageQueryException, UnauthorisedException, AccessTokenPayloadError { Storage storage = StorageLayer.getStorage(main); - updateSession(new TenantIdentifierWithStorage(null, null, null, storage), + updateSession(new TenantIdentifier(null, null, null), storage, sessionHandle, sessionData, jwtData, version); } - public static void updateSession(TenantIdentifierWithStorage tenantIdentifierWithStorage, + public static void updateSession(TenantIdentifier tenantIdentifier, Storage storage, String sessionHandle, @Nullable JsonObject sessionData, @Nullable JsonObject jwtData, AccessToken.VERSION version) throws StorageQueryException, UnauthorisedException, AccessTokenPayloadError { @@ -992,35 +993,35 @@ public static void updateSession(TenantIdentifierWithStorage tenantIdentifierWit throw new AccessTokenPayloadError("The user payload contains protected field"); } - io.supertokens.pluginInterface.session.SessionInfo session = tenantIdentifierWithStorage.getSessionStorage() - .getSession(tenantIdentifierWithStorage, sessionHandle); + io.supertokens.pluginInterface.session.SessionInfo session = StorageUtils.getSessionStorage(storage) + .getSession(tenantIdentifier, sessionHandle); // If there is no session, or session is expired if (session == null || session.expiry <= System.currentTimeMillis()) { throw new UnauthorisedException("Session does not exist."); } - int numberOfRowsAffected = tenantIdentifierWithStorage.getSessionStorage() - .updateSession(tenantIdentifierWithStorage, sessionHandle, sessionData, jwtData); + int numberOfRowsAffected = StorageUtils.getSessionStorage(storage) + .updateSession(tenantIdentifier, sessionHandle, sessionData, jwtData); if (numberOfRowsAffected != 1) { throw new UnauthorisedException("Session does not exist."); } } @Deprecated - public static void updateSessionBeforeCDI2_21(TenantIdentifierWithStorage tenantIdentifierWithStorage, + public static void updateSessionBeforeCDI2_21(TenantIdentifier tenantIdentifier, Storage storage, String sessionHandle, @Nullable JsonObject sessionData, @Nullable JsonObject jwtData) throws StorageQueryException, UnauthorisedException { - io.supertokens.pluginInterface.session.SessionInfo session = tenantIdentifierWithStorage.getSessionStorage() - .getSession(tenantIdentifierWithStorage, sessionHandle); + io.supertokens.pluginInterface.session.SessionInfo session = StorageUtils.getSessionStorage(storage) + .getSession(tenantIdentifier, sessionHandle); // If there is no session, or session is expired if (session == null || session.expiry <= System.currentTimeMillis()) { throw new UnauthorisedException("Session does not exist."); } - int numberOfRowsAffected = tenantIdentifierWithStorage.getSessionStorage() - .updateSession(tenantIdentifierWithStorage, sessionHandle, sessionData, + int numberOfRowsAffected = StorageUtils.getSessionStorage(storage) + .updateSession(tenantIdentifier, sessionHandle, sessionData, jwtData); if (numberOfRowsAffected != 1) { throw new UnauthorisedException("Session does not exist."); diff --git a/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java b/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java index 7646ef968..f0b177292 100644 --- a/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java @@ -23,6 +23,7 @@ import io.supertokens.pluginInterface.RECIPE_ID; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; +import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.utils.SemVer; import io.supertokens.utils.Utils; @@ -60,14 +61,15 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I Utils.addLegacySigningKeyInfos(this.getAppIdentifier(req), main, result, super.getVersionFromRequest(req).betweenInclusive(SemVer.v2_9, SemVer.v2_21)); + TenantIdentifier tenantIdentifier = getTenantIdentifier(req); result.addProperty("accessTokenBlacklistingEnabled", - Config.getConfig(this.getTenantStorage(req), main) + Config.getConfig(tenantIdentifier, main) .getAccessTokenBlacklisting()); result.addProperty("accessTokenValidity", - Config.getConfig(this.getTenantStorage(req), main) + Config.getConfig(tenantIdentifier, main) .getAccessTokenValidity()); result.addProperty("refreshTokenValidity", - Config.getConfig(this.getTenantStorage(req), main) + Config.getConfig(tenantIdentifier, main) .getRefreshTokenValidity()); super.sendJsonResponse(200, result, resp); } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | UnsupportedJWTSigningAlgorithmException e) { diff --git a/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java b/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java index a4b121496..c87c1eeb5 100644 --- a/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java @@ -23,11 +23,10 @@ import io.supertokens.exceptions.UnauthorisedException; import io.supertokens.output.Logging; import io.supertokens.pluginInterface.RECIPE_ID; +import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.session.Session; import io.supertokens.session.accessToken.AccessToken; @@ -65,11 +64,12 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO JsonObject userDataInJWT = InputParser.parseJsonObjectOrThrowError(input, "userDataInJWT", false); assert userDataInJWT != null; - TenantIdentifierWithStorage tenantIdentifierWithStorage = null; + TenantIdentifier tenantIdentifier; + Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - TenantIdentifier tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); - tenantIdentifierWithStorage = tenantIdentifier.withStorage(StorageLayer.getStorage(tenantIdentifier, main)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); } @@ -77,10 +77,10 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO try { if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v2_21)) { AccessToken.VERSION version = AccessToken.getAccessTokenVersionForCDI(getVersionFromRequest(req)); - Session.updateSession(tenantIdentifierWithStorage, sessionHandle, null, + Session.updateSession(tenantIdentifier, storage, sessionHandle, null, userDataInJWT, version); } else { - Session.updateSessionBeforeCDI2_21(tenantIdentifierWithStorage, sessionHandle, + Session.updateSessionBeforeCDI2_21(tenantIdentifier, storage, sessionHandle, null, userDataInJWT); } @@ -94,7 +94,7 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (AccessTokenPayloadError e) { throw new ServletException(new BadRequestException(e.getMessage())); } catch (UnauthorisedException e) { - Logging.debug(main, tenantIdentifierWithStorage, Utils.exceptionStacktraceToString(e)); + Logging.debug(main, tenantIdentifier, Utils.exceptionStacktraceToString(e)); JsonObject reply = new JsonObject(); reply.addProperty("status", "UNAUTHORISED"); reply.addProperty("message", e.getMessage()); @@ -109,17 +109,18 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO String sessionHandle = InputParser.getQueryParamOrThrowError(req, "sessionHandle", false); assert sessionHandle != null; - TenantIdentifierWithStorage tenantIdentifierWithStorage = null; + TenantIdentifier tenantIdentifier; + Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - TenantIdentifier tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); - tenantIdentifierWithStorage = tenantIdentifier.withStorage(StorageLayer.getStorage(tenantIdentifier, main)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); } try { - JsonElement jwtPayload = Session.getJWTData(tenantIdentifierWithStorage, sessionHandle); + JsonElement jwtPayload = Session.getJWTData(tenantIdentifier, storage, sessionHandle); JsonObject result = new JsonObject(); @@ -130,7 +131,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (StorageQueryException e) { throw new ServletException(e); } catch (UnauthorisedException e) { - Logging.debug(main, tenantIdentifierWithStorage, Utils.exceptionStacktraceToString(e)); + Logging.debug(main, tenantIdentifier, Utils.exceptionStacktraceToString(e)); JsonObject reply = new JsonObject(); reply.addProperty("status", "UNAUTHORISED"); reply.addProperty("message", e.getMessage()); diff --git a/src/main/java/io/supertokens/webserver/api/session/RefreshSessionAPI.java b/src/main/java/io/supertokens/webserver/api/session/RefreshSessionAPI.java index 26d2f7328..1813769a7 100644 --- a/src/main/java/io/supertokens/webserver/api/session/RefreshSessionAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/RefreshSessionAPI.java @@ -26,10 +26,11 @@ import io.supertokens.output.Logging; import io.supertokens.pluginInterface.RECIPE_ID; import io.supertokens.pluginInterface.STORAGE_TYPE; +import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; +import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.useridmapping.UserIdMapping; import io.supertokens.session.Session; @@ -78,19 +79,18 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I SessionInformationHolder sessionInfo = Session.refreshSession(appIdentifier, main, refreshToken, antiCsrfToken, enableAntiCsrf, accessTokenVersion); + TenantIdentifier tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), + appIdentifier.getAppId(), sessionInfo.session.tenantId); + Storage storage = StorageLayer.getStorage(tenantIdentifier, main); - if (StorageLayer.getStorage(this.getTenantStorage(req), main).getType() == - STORAGE_TYPE.SQL) { + if (storage.getType() == STORAGE_TYPE.SQL) { try { UserIdMapping userIdMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping( - this.getTenantStorage(req).toAppIdentifierWithStorage(), - sessionInfo.session.userId, UserIdType.ANY); + appIdentifier, storage, sessionInfo.session.userId, UserIdType.ANY); if (userIdMapping != null) { - ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, - userIdMapping.superTokensUserId); + ActiveUsers.updateLastActive(appIdentifier, main, userIdMapping.superTokensUserId); } else { - ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, - sessionInfo.session.userId); + ActiveUsers.updateLastActive(appIdentifier, main, sessionInfo.session.userId); } } catch (StorageQueryException ignored) { } diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionAPI.java index 5b6ce77b6..7af0fa841 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionAPI.java @@ -27,12 +27,11 @@ import io.supertokens.output.Logging; import io.supertokens.pluginInterface.RECIPE_ID; import io.supertokens.pluginInterface.STORAGE_TYPE; +import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.session.SessionInfo; import io.supertokens.session.Session; @@ -86,7 +85,10 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I assert userDataInDatabase != null; try { - boolean useStaticSigningKey = !Config.getConfig(this.getTenantStorage(req), main) + TenantIdentifier tenantIdentifier = getTenantIdentifier(req); + Storage storage = getTenantStorage(req); + + boolean useStaticSigningKey = !Config.getConfig(tenantIdentifier, main) .getAccessTokenSigningKeyDynamic(); if (version.greaterThanOrEqualTo(SemVer.v2_21)) { Boolean useDynamicSigningKey = InputParser.parseBooleanOrThrowError(input, "useDynamicSigningKey", @@ -99,22 +101,21 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I AccessToken.VERSION accessTokenVersion = AccessToken.getAccessTokenVersionForCDI(version); SessionInformationHolder sessionInfo = Session.createNewSession( - this.getTenantStorage(req), main, userId, userDataInJWT, + tenantIdentifier, storage, main, userId, userDataInJWT, userDataInDatabase, enableAntiCsrf, accessTokenVersion, useStaticSigningKey); - if (StorageLayer.getStorage(this.getTenantStorage(req), main).getType() == - STORAGE_TYPE.SQL) { + if (storage.getType() == STORAGE_TYPE.SQL) { try { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping( - this.getTenantStorage(req).toAppIdentifierWithStorage(), + tenantIdentifier.toAppIdentifier(), storage, sessionInfo.session.userId, UserIdType.ANY); if (userIdMapping != null) { - ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, + ActiveUsers.updateLastActive(tenantIdentifier.toAppIdentifier(), main, userIdMapping.superTokensUserId); } else { - ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, + ActiveUsers.updateLastActive(tenantIdentifier.toAppIdentifier(), main, sessionInfo.session.userId); } } catch (StorageQueryException ignored) { @@ -135,7 +136,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I if (super.getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v2_21)) { result.remove("idRefreshToken"); } else { - Utils.addLegacySigningKeyInfos(this.getTenantStorage(req).toAppIdentifier(), main, result, + Utils.addLegacySigningKeyInfos(tenantIdentifier.toAppIdentifier(), main, result, super.getVersionFromRequest(req).betweenInclusive(SemVer.v2_9, SemVer.v2_21)); } @@ -156,18 +157,19 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO String sessionHandle = InputParser.getQueryParamOrThrowError(req, "sessionHandle", false); assert sessionHandle != null; - TenantIdentifierWithStorage tenantIdentifierWithStorage = null; + TenantIdentifier tenantIdentifier; + Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - TenantIdentifier tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); - tenantIdentifierWithStorage = tenantIdentifier.withStorage(StorageLayer.getStorage(tenantIdentifier, main)); + storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); } try { - SessionInfo sessionInfo = Session.getSession(tenantIdentifierWithStorage, sessionHandle); + SessionInfo sessionInfo = Session.getSession(tenantIdentifier, storage, sessionHandle); JsonObject result = new Gson().toJsonTree(sessionInfo).getAsJsonObject(); result.add("userDataInJWT", Utils.toJsonTreeWithNulls(sessionInfo.userDataInJWT)); @@ -176,7 +178,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO result.addProperty("status", "OK"); if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v3_0)) { - result.addProperty("tenantId", tenantIdentifierWithStorage.getTenantId()); + result.addProperty("tenantId", tenantIdentifier.getTenantId()); } if (getVersionFromRequest(req).lesserThan(SemVer.v4_0)) { result.remove("recipeUserId"); @@ -187,7 +189,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (StorageQueryException e) { throw new ServletException(e); } catch (UnauthorisedException e) { - Logging.debug(main, tenantIdentifierWithStorage, Utils.exceptionStacktraceToString(e)); + Logging.debug(main, tenantIdentifier, Utils.exceptionStacktraceToString(e)); JsonObject reply = new JsonObject(); reply.addProperty("status", "UNAUTHORISED"); reply.addProperty("message", e.getMessage()); diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java index 29971d899..12d512227 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java @@ -22,11 +22,10 @@ import io.supertokens.exceptions.UnauthorisedException; import io.supertokens.output.Logging; import io.supertokens.pluginInterface.RECIPE_ID; +import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.session.Session; import io.supertokens.session.accessToken.AccessToken; @@ -60,17 +59,18 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO String sessionHandle = InputParser.getQueryParamOrThrowError(req, "sessionHandle", false); assert sessionHandle != null; - TenantIdentifierWithStorage tenantIdentifierWithStorage = null; + TenantIdentifier tenantIdentifier; + Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - TenantIdentifier tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); - tenantIdentifierWithStorage = tenantIdentifier.withStorage(StorageLayer.getStorage(tenantIdentifier, main)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); } try { - JsonObject userDataInDatabase = Session.getSessionData(tenantIdentifierWithStorage, sessionHandle); + JsonObject userDataInDatabase = Session.getSessionData(tenantIdentifier, storage, sessionHandle); JsonObject result = new JsonObject(); result.addProperty("status", "OK"); @@ -80,7 +80,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (StorageQueryException e) { throw new ServletException(e); } catch (UnauthorisedException e) { - Logging.debug(main, tenantIdentifierWithStorage, Utils.exceptionStacktraceToString(e)); + Logging.debug(main, tenantIdentifier, Utils.exceptionStacktraceToString(e)); JsonObject reply = new JsonObject(); reply.addProperty("status", "UNAUTHORISED"); reply.addProperty("message", e.getMessage()); @@ -97,11 +97,12 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO JsonObject userDataInDatabase = InputParser.parseJsonObjectOrThrowError(input, "userDataInDatabase", false); assert userDataInDatabase != null; - TenantIdentifierWithStorage tenantIdentifierWithStorage = null; + TenantIdentifier tenantIdentifier; + Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - TenantIdentifier tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); - tenantIdentifierWithStorage = tenantIdentifier.withStorage(StorageLayer.getStorage(tenantIdentifier, main)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); } @@ -111,10 +112,10 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO // which is always null here if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v2_21)) { AccessToken.VERSION version = AccessToken.getAccessTokenVersionForCDI(getVersionFromRequest(req)); - Session.updateSession(tenantIdentifierWithStorage, sessionHandle, + Session.updateSession(tenantIdentifier, storage, sessionHandle, userDataInDatabase, null, version); } else { - Session.updateSessionBeforeCDI2_21(tenantIdentifierWithStorage, sessionHandle, + Session.updateSessionBeforeCDI2_21(tenantIdentifier, storage, sessionHandle, userDataInDatabase, null); } @@ -127,7 +128,7 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (AccessTokenPayloadError e) { throw new ServletException(new BadRequestException(e.getMessage())); } catch (UnauthorisedException e) { - Logging.debug(main, tenantIdentifierWithStorage, Utils.exceptionStacktraceToString(e)); + Logging.debug(main, tenantIdentifier, Utils.exceptionStacktraceToString(e)); JsonObject reply = new JsonObject(); reply.addProperty("status", "UNAUTHORISED"); reply.addProperty("message", e.getMessage()); diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionRegenerateAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionRegenerateAPI.java index c480b194c..58b110cfe 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionRegenerateAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionRegenerateAPI.java @@ -27,7 +27,6 @@ import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.session.Session; import io.supertokens.session.info.SessionInformationHolder; diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionRemoveAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionRemoveAPI.java index 1beeec007..12b1cec58 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionRemoveAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionRemoveAPI.java @@ -23,7 +23,10 @@ import io.supertokens.Main; import io.supertokens.pluginInterface.RECIPE_ID; import io.supertokens.pluginInterface.STORAGE_TYPE; +import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.exceptions.StorageQueryException; +import io.supertokens.pluginInterface.multitenancy.AppIdentifier; +import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.useridmapping.UserIdMapping; import io.supertokens.session.Session; @@ -99,27 +102,27 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I if (userId != null) { try { + TenantIdentifier tenantIdentifier = getTenantIdentifier(req); + Storage storage = getTenantStorage(req); + String[] sessionHandlesRevoked; if (revokeAcrossAllTenants) { sessionHandlesRevoked = Session.revokeAllSessionsForUser( - main, this.getTenantStorage(req).toAppIdentifierWithStorage(), userId, revokeSessionsForLinkedAccounts); + main, tenantIdentifier.toAppIdentifier(), storage, userId, revokeSessionsForLinkedAccounts); } else { sessionHandlesRevoked = Session.revokeAllSessionsForUser( - main, this.getTenantStorage(req), userId, - revokeSessionsForLinkedAccounts); + main, tenantIdentifier, storage, userId, revokeSessionsForLinkedAccounts); } - if (StorageLayer.getStorage(this.getTenantStorage(req), main).getType() == - STORAGE_TYPE.SQL) { + if (storage.getType() == STORAGE_TYPE.SQL) { try { UserIdMapping userIdMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping( - this.getTenantStorage(req).toAppIdentifierWithStorage(), - userId, UserIdType.ANY); + tenantIdentifier.toAppIdentifier(), storage, userId, UserIdType.ANY); if (userIdMapping != null) { - ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, + ActiveUsers.updateLastActive(tenantIdentifier.toAppIdentifier(), main, userIdMapping.superTokensUserId); } else { - ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, userId); + ActiveUsers.updateLastActive(tenantIdentifier.toAppIdentifier(), main, userId); } } catch (StorageQueryException ignored) { } @@ -137,8 +140,11 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I } } else { try { + AppIdentifier appIdentifier = getAppIdentifier(req); + Storage storage = getTenantStorage(req); + String[] sessionHandlesRevoked = Session.revokeSessionUsingSessionHandles(main, - this.getTenantStorage(req).toAppIdentifierWithStorage(), sessionHandles); + appIdentifier, storage, sessionHandles); JsonObject result = new JsonObject(); result.addProperty("status", "OK"); JsonArray sessionHandlesRevokedJSON = new JsonArray(); diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java index bb5ccd837..ec0ad8dff 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java @@ -21,7 +21,10 @@ import com.google.gson.JsonPrimitive; import io.supertokens.Main; import io.supertokens.pluginInterface.RECIPE_ID; +import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.exceptions.StorageQueryException; +import io.supertokens.pluginInterface.multitenancy.AppIdentifier; +import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.session.Session; import io.supertokens.webserver.InputParser; @@ -67,12 +70,15 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO try { String[] sessionHandles; + TenantIdentifier tenantIdentifier = getTenantIdentifier(req); + Storage storage = getTenantStorage(req); + if (fetchAcrossAllTenants) { sessionHandles = Session.getAllNonExpiredSessionHandlesForUser( - main, this.getTenantStorage(req).toAppIdentifierWithStorage(), userId, fetchSessionsForAllLinkedAccounts); + main, tenantIdentifier.toAppIdentifier(), storage, userId, fetchSessionsForAllLinkedAccounts); } else { sessionHandles = Session.getAllNonExpiredSessionHandlesForUser( - this.getTenantStorage(req), userId, fetchSessionsForAllLinkedAccounts); + tenantIdentifier, storage, userId, fetchSessionsForAllLinkedAccounts); } JsonObject result = new JsonObject();