diff --git a/examples/cloudflare-workers/web-sdk/src/worker.ts b/examples/cloudflare-workers/web-sdk/src/worker.ts index 9215983d9..86c1dedc0 100644 --- a/examples/cloudflare-workers/web-sdk/src/worker.ts +++ b/examples/cloudflare-workers/web-sdk/src/worker.ts @@ -86,7 +86,7 @@ export default { const momento = new CacheClient({ configuration: Configurations.Laptop.v1(), credentialProvider: CredentialProvider.fromString({ - authToken:env.MOMENTO_API_KEY + apiKey:env.MOMENTO_API_KEY }), defaultTtlSeconds: 60, }); diff --git a/examples/deno/http-api/index.ts b/examples/deno/http-api/index.ts index da4e40190..4b4e3a340 100644 --- a/examples/deno/http-api/index.ts +++ b/examples/deno/http-api/index.ts @@ -13,8 +13,8 @@ export const handler = async (_request: Request): Promise => { throw new Error('Missing environment variable MOMENTO_CACHE_NAME') } - const authToken = env['MOMENTO_API_KEY'] - if (!authToken) { + const apiKey = env['MOMENTO_API_KEY'] + if (!apiKey) { throw new Error('Missing environment variable MOMENTO_API_KEY') } @@ -26,7 +26,7 @@ export const handler = async (_request: Request): Promise => { const key = 'foo' const value = 'FOO' - const momento = new HttpClient(authToken, endpoint) + const momento = new HttpClient(apiKey, endpoint) await momento.set(cacheName, key, value, 10) console.log(`Set the key-value pair in the cache ${cacheName}`) diff --git a/examples/deno/web-sdk/deno.json b/examples/deno/web-sdk/deno.json index 71c82223d..8a3d2d921 100644 --- a/examples/deno/web-sdk/deno.json +++ b/examples/deno/web-sdk/deno.json @@ -24,9 +24,9 @@ }, "imports": { "http": "https://deno.land/std@0.198.0/http/server.ts", - "momento": "npm:@gomomento/sdk-web@1.35.0", + "momento": "npm:@gomomento/sdk-web@1.39.2", "xhr4sw": "npm:xhr4sw@0.0.5", "dotenv": "https://deno.land/std/dotenv/mod.ts" } -} \ No newline at end of file +} diff --git a/examples/deno/web-sdk/index.ts b/examples/deno/web-sdk/index.ts index cd879dd24..8162113a5 100644 --- a/examples/deno/web-sdk/index.ts +++ b/examples/deno/web-sdk/index.ts @@ -27,15 +27,15 @@ export const handler = async (_request: Request): Promise => { throw new Error('Missing environment variable MOMENTO_CACHE_NAME') } - const authToken = env['MOMENTO_API_KEY'] - if (!authToken) { + const apiKey = env['MOMENTO_API_KEY'] + if (!apiKey) { throw new Error('Missing environment variable MOMENTO_API_KEY') } const momento = new CacheClient({ configuration: Configurations.Browser.v1(), credentialProvider: CredentialProvider.fromString({ - authToken: authToken, + apiKey: apiKey, }), defaultTtlSeconds: 60, }) diff --git a/examples/fastly-compute/src/index.ts b/examples/fastly-compute/src/index.ts index f01e68332..d1a208c0a 100644 --- a/examples/fastly-compute/src/index.ts +++ b/examples/fastly-compute/src/index.ts @@ -35,8 +35,8 @@ async function handleRequest(event: FetchEvent) { // Get all required information from the Config Store // Note: for production environments, the Momento API key should be saved in a Fastly Secret Store - const authToken = secrets.get('MOMENTO_API_KEY'); - if (!authToken) { + const apiKey = secrets.get('MOMENTO_API_KEY'); + if (!apiKey) { return new Response('Missing required env var MOMENTO_API_KEY', { status: 500, }); @@ -64,7 +64,7 @@ async function handleRequest(event: FetchEvent) { const value = 'serverless'; try { - const momento = new MomentoFetcher(authToken, httpEndpoint, backend); + const momento = new MomentoFetcher(apiKey, httpEndpoint, backend); const getResp = await momento.get(cacheName, key); console.log(`Fetching the key when the cache is empty: ${getResp}`); diff --git a/examples/nodejs/access-control/access-control.ts b/examples/nodejs/access-control/access-control.ts index be58d017b..8bc76c23d 100644 --- a/examples/nodejs/access-control/access-control.ts +++ b/examples/nodejs/access-control/access-control.ts @@ -10,7 +10,7 @@ import { DeleteCache, AuthClient, ExpiresIn, - GenerateAuthToken, + GenerateApiKey, TokenScope, TokenScopes, CacheRole, @@ -67,19 +67,19 @@ async function get(cacheClient: CacheClient, cacheName: string, key: string) { } } -async function generateAuthToken( +async function generateApiKey( authClient: AuthClient, scope: TokenScope, durationSeconds: number ): Promise<[string, string]> { - const generateTokenResponse = await authClient.generateAuthToken(scope, ExpiresIn.seconds(durationSeconds)); - if (generateTokenResponse instanceof GenerateAuthToken.Success) { + const generateTokenResponse = await authClient.generateApiKey(scope, ExpiresIn.seconds(durationSeconds)); + if (generateTokenResponse instanceof GenerateApiKey.Success) { console.log(`Generated an API key with ${scope.toString()} scope at time ${Date.now() / 1000}!`); console.log('Logging only a substring of the tokens, because logging security credentials is not advisable:'); - console.log(`API key starts with: ${generateTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${generateTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${generateTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${generateTokenResponse.expiresAt.epoch()}`); - return [generateTokenResponse.authToken, generateTokenResponse.refreshToken]; + return [generateTokenResponse.apiKey, generateTokenResponse.refreshToken]; } else { throw new Error(`Failed to generate API key: ${generateTokenResponse.toString()}`); } @@ -107,14 +107,14 @@ async function main() { await set(mainCacheClient, CACHE_OPEN_DOOR, 'hello', 'world'); // Create a token valid for 600 seconds that can only read a specific cache 'open-door' - const [scopedToken, scopedRefreshToken] = await generateAuthToken( + const [scopedToken, scopedRefreshToken] = await generateApiKey( mainAuthClient, TokenScopes.cacheReadOnly(CACHE_OPEN_DOOR), tokenValidForSeconds ); const scopedTokenCacheClient = await CacheClient.create({ configuration: Configurations.Laptop.v1(), - credentialProvider: CredentialProvider.fromString({authToken: scopedToken}), + credentialProvider: CredentialProvider.fromString({apiKey: scopedToken}), defaultTtlSeconds: 600, }); @@ -155,11 +155,7 @@ async function main() { ], }; - const [scopedToken1, scopedRefreshToken1] = await generateAuthToken( - mainAuthClient, - permissions, - tokenValidForSeconds - ); + const [scopedToken1, scopedRefreshToken1] = await generateApiKey(mainAuthClient, permissions, tokenValidForSeconds); // Do something with the token. } diff --git a/examples/nodejs/aws/doc-example-files/doc-examples-js-aws-secrets.ts b/examples/nodejs/aws/doc-example-files/doc-examples-js-aws-secrets.ts index 5bc1cac80..397e48bb7 100644 --- a/examples/nodejs/aws/doc-example-files/doc-examples-js-aws-secrets.ts +++ b/examples/nodejs/aws/doc-example-files/doc-examples-js-aws-secrets.ts @@ -2,7 +2,7 @@ import {CacheClient, Configurations, CredentialProvider, CacheGet, CacheSet, Cre import {SecretsManagerClient, GetSecretValueCommand} from '@aws-sdk/client-secrets-manager'; -async function example_API_retrieveAuthTokenFromSecretsManager( +async function example_API_retrieveApiKeyFromSecretsManager( ttl = 600, secretName = 'MOMENTO_API_KEY', regionName = 'us-west-2' @@ -33,7 +33,7 @@ async function example_API_retrieveAuthTokenFromSecretsManager( // Gets a client connection object from Momento Cache and returns that for later use. return await CacheClient.create({ configuration: Configurations.Laptop.v1(), - credentialProvider: CredentialProvider.fromString({authToken: secret}), + credentialProvider: CredentialProvider.fromString({apiKey: secret}), defaultTtlSeconds: ttl, }); } @@ -79,7 +79,7 @@ async function readFromCache(client: CacheClient, cacheName: string, key: string // Call the various functions async function main() { const CACHE_NAME = 'demo-cache2'; - const cacheClient = await example_API_retrieveAuthTokenFromSecretsManager(); + const cacheClient = await example_API_retrieveApiKeyFromSecretsManager(); await createCache(cacheClient, CACHE_NAME); await writeToCache(cacheClient, CACHE_NAME, 'code', '12345'); diff --git a/examples/nodejs/cache/README.ja.md b/examples/nodejs/cache/README.ja.md index 061947fec..ace4e238a 100644 --- a/examples/nodejs/cache/README.ja.md +++ b/examples/nodejs/cache/README.ja.md @@ -33,11 +33,11 @@ npm install @gomomento/sdk import { CacheClient, CacheGetStatus } from "@gomomento/sdk"; // ユーザーのMomentoオーストークン -const authToken = process.env.MOMENTO_API_KEY; +const apiKey = process.env.MOMENTO_API_KEY; // Momentoをイニシャライズする const DEFAULT_TTL = 60; // デフォルトTTLは60秒 -const momento = await CacheClient.create(authToken, DEFAULT_TTL); +const momento = await CacheClient.create(apiKey, DEFAULT_TTL); // "myCache"という名のキャッシュを作成する const CACHE_NAME = "myCache"; diff --git a/examples/nodejs/cache/doc-example-files/doc-examples-js-apis.ts b/examples/nodejs/cache/doc-example-files/doc-examples-js-apis.ts index 2324432cc..78246d5ef 100644 --- a/examples/nodejs/cache/doc-example-files/doc-examples-js-apis.ts +++ b/examples/nodejs/cache/doc-example-files/doc-examples-js-apis.ts @@ -28,8 +28,8 @@ import { AllTopics, CacheRole, TopicRole, - GenerateAuthToken, - RefreshAuthToken, + GenerateApiKey, + RefreshApiKey, GenerateDisposableToken, CacheIncrement, CacheItemGetType, @@ -74,7 +74,7 @@ import { TopicConfigurations, } from '@gomomento/sdk'; -function retrieveAuthTokenFromYourSecretsManager(): string { +function retrieveApiKeyFromYourSecretsManager(): string { // this is not a valid API key but conforms to the syntax requirements. const fakeTestV1ApiKey = 'eyJhcGlfa2V5IjogImV5SjBlWEFpT2lKS1YxUWlMQ0poYkdjaU9pSklVekkxTmlKOS5leUpwYzNNaU9pSlBibXhwYm1VZ1NsZFVJRUoxYVd4a1pYSWlMQ0pwWVhRaU9qRTJOemd6TURVNE1USXNJbVY0Y0NJNk5EZzJOVFV4TlRReE1pd2lZWFZrSWpvaUlpd2ljM1ZpSWpvaWFuSnZZMnRsZEVCbGVHRnRjR3hsTG1OdmJTSjkuOEl5OHE4NExzci1EM1lDb19IUDRkLXhqSGRUOFVDSXV2QVljeGhGTXl6OCIsICJlbmRwb2ludCI6ICJ0ZXN0Lm1vbWVudG9ocS5jb20ifQo='; @@ -86,8 +86,8 @@ function example_API_CredentialProviderFromEnvVar() { } function example_API_CredentialProviderFromString() { - const authToken = retrieveAuthTokenFromYourSecretsManager(); - CredentialProvider.fromString({authToken: authToken}); + const apiKey = retrieveApiKeyFromYourSecretsManager(); + CredentialProvider.fromString({apiKey: apiKey}); } function example_API_ConfigurationLaptop() { @@ -787,86 +787,86 @@ function example_API_InstantiateTopicClient() { }); } -async function example_API_GenerateAuthToken(authClient: AuthClient) { +async function example_API_GenerateApiKey(authClient: AuthClient) { // Generate a token that allows all data plane APIs on all caches and topics. - const allDataRWTokenResponse = await authClient.generateAuthToken(AllDataReadWrite, ExpiresIn.minutes(30)); - if (allDataRWTokenResponse instanceof GenerateAuthToken.Success) { + const allDataRWTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30)); + if (allDataRWTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated an API key with AllDataReadWrite scope!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`API key starts with: ${allDataRWTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${allDataRWTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${allDataRWTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${allDataRWTokenResponse.expiresAt.epoch()}`); - } else if (allDataRWTokenResponse instanceof GenerateAuthToken.Error) { + } else if (allDataRWTokenResponse instanceof GenerateApiKey.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with AllDataReadWrite scope: ${allDataRWTokenResponse.errorCode()}: ${allDataRWTokenResponse.toString()}` + `An error occurred while attempting to call generateApiKey with AllDataReadWrite scope: ${allDataRWTokenResponse.errorCode()}: ${allDataRWTokenResponse.toString()}` ); } // Generate a token that can only call read-only data plane APIs on a specific cache foo. No topic apis (publish/subscribe) are allowed. - const singleCacheROTokenResponse = await authClient.generateAuthToken( + const singleCacheROTokenResponse = await authClient.generateApiKey( TokenScopes.cacheReadOnly('foo'), ExpiresIn.minutes(30) ); - if (singleCacheROTokenResponse instanceof GenerateAuthToken.Success) { + if (singleCacheROTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated an API key with read-only access to cache foo!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`API key starts with: ${singleCacheROTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${singleCacheROTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${singleCacheROTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${singleCacheROTokenResponse.expiresAt.epoch()}`); - } else if (singleCacheROTokenResponse instanceof GenerateAuthToken.Error) { + } else if (singleCacheROTokenResponse instanceof GenerateApiKey.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with single cache read-only scope: ${singleCacheROTokenResponse.errorCode()}: ${singleCacheROTokenResponse.toString()}` + `An error occurred while attempting to call generateApiKey with single cache read-only scope: ${singleCacheROTokenResponse.errorCode()}: ${singleCacheROTokenResponse.toString()}` ); } // Generate a token that can call all data plane APIs on all caches. No topic apis (publish/subscribe) are allowed. - const allCachesRWTokenResponse = await authClient.generateAuthToken( + const allCachesRWTokenResponse = await authClient.generateApiKey( TokenScopes.cacheReadWrite(AllCaches), ExpiresIn.minutes(30) ); - if (allCachesRWTokenResponse instanceof GenerateAuthToken.Success) { + if (allCachesRWTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated an API key with read-write access to all caches!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`API key starts with: ${allCachesRWTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${allCachesRWTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${allCachesRWTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${allCachesRWTokenResponse.expiresAt.epoch()}`); - } else if (allCachesRWTokenResponse instanceof GenerateAuthToken.Error) { + } else if (allCachesRWTokenResponse instanceof GenerateApiKey.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with all caches read-write scope: ${allCachesRWTokenResponse.errorCode()}: ${allCachesRWTokenResponse.toString()}` + `An error occurred while attempting to call generateApiKey with all caches read-write scope: ${allCachesRWTokenResponse.errorCode()}: ${allCachesRWTokenResponse.toString()}` ); } // Generate a token that can call publish and subscribe on all topics within cache bar - const singleCacheAllTopicsRWTokenResponse = await authClient.generateAuthToken( + const singleCacheAllTopicsRWTokenResponse = await authClient.generateApiKey( TokenScopes.topicPublishSubscribe({name: 'bar'}, AllTopics), ExpiresIn.minutes(30) ); - if (singleCacheAllTopicsRWTokenResponse instanceof GenerateAuthToken.Success) { + if (singleCacheAllTopicsRWTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated an API key with publish-subscribe access to all topics within cache bar!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`API key starts with: ${singleCacheAllTopicsRWTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${singleCacheAllTopicsRWTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${singleCacheAllTopicsRWTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${singleCacheAllTopicsRWTokenResponse.expiresAt.epoch()}`); - } else if (singleCacheAllTopicsRWTokenResponse instanceof GenerateAuthToken.Error) { + } else if (singleCacheAllTopicsRWTokenResponse instanceof GenerateApiKey.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with read-write scope for all topics in a single cache: ${singleCacheAllTopicsRWTokenResponse.errorCode()}: ${singleCacheAllTopicsRWTokenResponse.toString()}` + `An error occurred while attempting to call generateApiKey with read-write scope for all topics in a single cache: ${singleCacheAllTopicsRWTokenResponse.errorCode()}: ${singleCacheAllTopicsRWTokenResponse.toString()}` ); } // Generate a token that can only call subscribe on topic where_is_mo within cache mo_nuts - const oneCacheOneTopicRWTokenResponse = await authClient.generateAuthToken( + const oneCacheOneTopicRWTokenResponse = await authClient.generateApiKey( TokenScopes.topicSubscribeOnly('mo_nuts', 'where_is_mo'), ExpiresIn.minutes(30) ); - if (oneCacheOneTopicRWTokenResponse instanceof GenerateAuthToken.Success) { + if (oneCacheOneTopicRWTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated an API key with subscribe-only access to topic where_is_mo within cache mo_nuts!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`API key starts with: ${oneCacheOneTopicRWTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${oneCacheOneTopicRWTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${oneCacheOneTopicRWTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${oneCacheOneTopicRWTokenResponse.expiresAt.epoch()}`); - } else if (oneCacheOneTopicRWTokenResponse instanceof GenerateAuthToken.Error) { + } else if (oneCacheOneTopicRWTokenResponse instanceof GenerateApiKey.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with read-write scope for single topic in a single cache: ${oneCacheOneTopicRWTokenResponse.errorCode()}: ${oneCacheOneTopicRWTokenResponse.toString()}` + `An error occurred while attempting to call generateApiKey with read-write scope for single topic in a single cache: ${oneCacheOneTopicRWTokenResponse.errorCode()}: ${oneCacheOneTopicRWTokenResponse.toString()}` ); } @@ -894,32 +894,32 @@ async function example_API_GenerateAuthToken(authClient: AuthClient) { permissions: [cachePermission1, cachePermission2, topicPermission1, topicPermission2], }; - const multiplePermsTokenResponse = await authClient.generateAuthToken(permissions, ExpiresIn.minutes(30)); - if (multiplePermsTokenResponse instanceof GenerateAuthToken.Success) { + const multiplePermsTokenResponse = await authClient.generateApiKey(permissions, ExpiresIn.minutes(30)); + if (multiplePermsTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated an API key with multiple cache and topic permissions!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`API key starts with: ${multiplePermsTokenResponse.authToken.substring(0, 10)}`); + console.log(`API key starts with: ${multiplePermsTokenResponse.apiKey.substring(0, 10)}`); console.log(`Refresh token starts with: ${multiplePermsTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Expires At: ${multiplePermsTokenResponse.expiresAt.epoch()}`); - } else if (multiplePermsTokenResponse instanceof GenerateAuthToken.Error) { + } else if (multiplePermsTokenResponse instanceof GenerateApiKey.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with multiple permissions: ${multiplePermsTokenResponse.errorCode()}: ${multiplePermsTokenResponse.toString()}` + `An error occurred while attempting to call generateApiKey with multiple permissions: ${multiplePermsTokenResponse.errorCode()}: ${multiplePermsTokenResponse.toString()}` ); } } -async function example_API_RefreshAuthToken(authClient: AuthClient) { - const generateTokenResponse = await authClient.generateAuthToken(AllDataReadWrite, ExpiresIn.minutes(30)); - if (generateTokenResponse instanceof GenerateAuthToken.Success) { +async function example_API_RefreshApiKey(authClient: AuthClient) { + const generateTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30)); + if (generateTokenResponse instanceof GenerateApiKey.Success) { console.log('Generated API key; refreshing!'); const refreshAuthClient = new AuthClient({ - credentialProvider: CredentialProvider.fromString({authToken: generateTokenResponse.authToken}), + credentialProvider: CredentialProvider.fromString({apiKey: generateTokenResponse.apiKey}), }); - const refreshTokenResponse = await refreshAuthClient.refreshAuthToken(generateTokenResponse.refreshToken); - if (refreshTokenResponse instanceof RefreshAuthToken.Success) { + const refreshTokenResponse = await refreshAuthClient.refreshApiKey(generateTokenResponse.refreshToken); + if (refreshTokenResponse instanceof RefreshApiKey.Success) { console.log('API key refreshed!'); // logging only a substring of the tokens, because logging security credentials is not advisable :) - console.log(`Refreshed API key starts with: ${refreshTokenResponse.authToken.substring(0, 10)}`); + console.log(`Refreshed API key starts with: ${refreshTokenResponse.apiKey.substring(0, 10)}`); console.log(`New refresh token starts with: ${refreshTokenResponse.refreshToken.substring(0, 10)}`); console.log(`Refreshed API key expires At: ${refreshTokenResponse.expiresAt.epoch()}`); } @@ -939,7 +939,7 @@ async function example_API_GenerateDisposableToken(authClient: AuthClient) { console.log(`Expires At: ${oneKeyOneCacheToken.expiresAt.epoch()}`); } else if (oneKeyOneCacheToken instanceof GenerateDisposableToken.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with disposable token scope: ${oneKeyOneCacheToken.errorCode()}: ${oneKeyOneCacheToken.toString()}` + `An error occurred while attempting to call generateApiKey with disposable token scope: ${oneKeyOneCacheToken.errorCode()}: ${oneKeyOneCacheToken.toString()}` ); } @@ -955,7 +955,7 @@ async function example_API_GenerateDisposableToken(authClient: AuthClient) { console.log(`Expires At: ${keyPrefixAllCachesToken.expiresAt.epoch()}`); } else if (keyPrefixAllCachesToken instanceof GenerateDisposableToken.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with disposable token scope: ${keyPrefixAllCachesToken.errorCode()}: ${keyPrefixAllCachesToken.toString()}` + `An error occurred while attempting to call generateApiKey with disposable token scope: ${keyPrefixAllCachesToken.errorCode()}: ${keyPrefixAllCachesToken.toString()}` ); } @@ -971,7 +971,7 @@ async function example_API_GenerateDisposableToken(authClient: AuthClient) { console.log(`Expires At: ${allTopicsOneCacheToken.expiresAt.epoch()}`); } else if (allTopicsOneCacheToken instanceof GenerateDisposableToken.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with disposable token scope: ${allTopicsOneCacheToken.errorCode()}: ${allTopicsOneCacheToken.toString()}` + `An error occurred while attempting to call generateApiKey with disposable token scope: ${allTopicsOneCacheToken.errorCode()}: ${allTopicsOneCacheToken.toString()}` ); } @@ -987,7 +987,7 @@ async function example_API_GenerateDisposableToken(authClient: AuthClient) { console.log(`Expires At: ${oneTopicAllCachesToken.expiresAt.epoch()}`); } else if (oneTopicAllCachesToken instanceof GenerateDisposableToken.Error) { throw new Error( - `An error occurred while attempting to call generateAuthToken with disposable token scope: ${oneTopicAllCachesToken.errorCode()}: ${oneTopicAllCachesToken.toString()}` + `An error occurred while attempting to call generateApiKey with disposable token scope: ${oneTopicAllCachesToken.errorCode()}: ${oneTopicAllCachesToken.toString()}` ); } } @@ -1034,10 +1034,10 @@ async function example_API_TopicSubscribe(topicClient: TopicClient) { } async function main() { - const originalAuthToken = process.env['MOMENTO_API_KEY']; - process.env['MOMENTO_API_KEY'] = retrieveAuthTokenFromYourSecretsManager(); + const originalApiKey = process.env['MOMENTO_API_KEY']; + process.env['MOMENTO_API_KEY'] = retrieveApiKeyFromYourSecretsManager(); example_API_CredentialProviderFromEnvVar(); - process.env['MOMENTO_API_KEY'] = originalAuthToken; + process.env['MOMENTO_API_KEY'] = originalApiKey; example_API_CredentialProviderFromString(); example_API_ConfigurationLaptop(); @@ -1114,8 +1114,8 @@ async function main() { environmentVariableName: 'MOMENTO_API_KEY', }), }); - await example_API_GenerateAuthToken(authClient); - await example_API_RefreshAuthToken(authClient); + await example_API_GenerateApiKey(authClient); + await example_API_RefreshApiKey(authClient); await example_API_GenerateDisposableToken(authClient); example_API_InstantiateTopicClient(); diff --git a/examples/nodejs/lambda-examples/simple-get/README.md b/examples/nodejs/lambda-examples/simple-get/README.md index fd57badf4..22318715a 100644 --- a/examples/nodejs/lambda-examples/simple-get/README.md +++ b/examples/nodejs/lambda-examples/simple-get/README.md @@ -43,7 +43,7 @@ You will also need a superuser API key generated from the [Momento Console](http Then run: ``` -npm run cdk -- deploy --parameters MomentoAuthToken= +npm run cdk -- deploy --parameters MomentoApiKey= ``` The lambda does not set up a way to access itself externally, so to run it, you will have to go to MomentoSimpleGet in AWS Lambda and run a test. diff --git a/examples/nodejs/lambda-examples/simple-get/infrastructure/lib/simple-get-stack.ts b/examples/nodejs/lambda-examples/simple-get/infrastructure/lib/simple-get-stack.ts index 4e9bcca32..a96b4e105 100644 --- a/examples/nodejs/lambda-examples/simple-get/infrastructure/lib/simple-get-stack.ts +++ b/examples/nodejs/lambda-examples/simple-get/infrastructure/lib/simple-get-stack.ts @@ -9,15 +9,15 @@ export class SimpleGetStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); - const momentoAuthTokenParam = new cdk.CfnParameter(this, 'MomentoAuthToken', { + const momentoApiKeyParam = new cdk.CfnParameter(this, 'MomentoApiKey', { type: 'String', description: 'The Momento API key that will be used to read from the cache.', noEcho: true, }); - const authTokenSecret = new secrets.Secret(this, 'MomentoSimpleGetAuthToken', { - secretName: 'MomentoSimpleGetAuthToken', - secretStringValue: new cdk.SecretValue(momentoAuthTokenParam.valueAsString), + const apiKeySecret = new secrets.Secret(this, 'MomentoSimpleGetApiKey', { + secretName: 'MomentoSimpleGetApiKey', + secretStringValue: new cdk.SecretValue(momentoApiKeyParam.valueAsString), }); const getLambda = new lambdaNodejs.NodejsFunction(this, 'MomentoSimpleGet', { @@ -30,10 +30,10 @@ export class SimpleGetStack extends cdk.Stack { timeout: cdk.Duration.seconds(30), memorySize: 128, environment: { - MOMENTO_API_KEY_SECRET_NAME: authTokenSecret.secretName, + MOMENTO_API_KEY_SECRET_NAME: apiKeySecret.secretName, }, }); - authTokenSecret.grantRead(getLambda); + apiKeySecret.grantRead(getLambda); } } diff --git a/examples/nodejs/lambda-examples/simple-get/lambda/simple-get/handler.ts b/examples/nodejs/lambda-examples/simple-get/lambda/simple-get/handler.ts index ef8b46172..2bae29a91 100644 --- a/examples/nodejs/lambda-examples/simple-get/lambda/simple-get/handler.ts +++ b/examples/nodejs/lambda-examples/simple-get/lambda/simple-get/handler.ts @@ -44,17 +44,17 @@ export const handler = async () => { }; async function getCacheClient(): Promise { - const authTokenSecretName = process.env.MOMENTO_API_KEY_SECRET_NAME; - if (authTokenSecretName === undefined) { + const apiKeySecretName = process.env.MOMENTO_API_KEY_SECRET_NAME; + if (apiKeySecretName === undefined) { throw new Error("Missing required env var 'MOMENTO_API_KEY_SECRET_NAME"); } if (_cacheClient === undefined) { - const momentoAuthToken = await getSecret(authTokenSecretName); + const momentoApiKey = await getSecret(apiKeySecretName); console.log('Retrieved secret!'); // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-assignment _cacheClient = await CacheClient.create({ configuration: Configurations.Lambda.latest(), - credentialProvider: CredentialProvider.fromString({authToken: momentoAuthToken}), + credentialProvider: CredentialProvider.fromString({apiKey: momentoApiKey}), defaultTtlSeconds: 60, }); } diff --git a/examples/nodejs/lambda-examples/topics-microservice/resources/libMomentoClient.ts b/examples/nodejs/lambda-examples/topics-microservice/resources/libMomentoClient.ts index e5bc25042..4bf24cff5 100644 --- a/examples/nodejs/lambda-examples/topics-microservice/resources/libMomentoClient.ts +++ b/examples/nodejs/lambda-examples/topics-microservice/resources/libMomentoClient.ts @@ -58,7 +58,7 @@ export async function CreateCacheClient( // Get a new cache connection with the token and set a default TTL for the connection. return await CacheClient.create({ configuration: Configurations.Laptop.latest(), - credentialProvider: CredentialProvider.fromString({ authToken : token }), + credentialProvider: CredentialProvider.fromString({ apiKey : token }), defaultTtlSeconds: ttl, }); } @@ -73,6 +73,6 @@ export async function CreateTopicClient(secretName: string, region: string): Pro // Get a new cache connection with the token and set a default TTL for the connection. return new TopicClient({ configuration: Configurations.Lambda.latest(), - credentialProvider: CredentialProvider.fromString({ authToken : token }), + credentialProvider: CredentialProvider.fromString({ apiKey : token }), }); } diff --git a/examples/nodejs/load-gen/README.ja.md b/examples/nodejs/load-gen/README.ja.md index 061947fec..ace4e238a 100644 --- a/examples/nodejs/load-gen/README.ja.md +++ b/examples/nodejs/load-gen/README.ja.md @@ -33,11 +33,11 @@ npm install @gomomento/sdk import { CacheClient, CacheGetStatus } from "@gomomento/sdk"; // ユーザーのMomentoオーストークン -const authToken = process.env.MOMENTO_API_KEY; +const apiKey = process.env.MOMENTO_API_KEY; // Momentoをイニシャライズする const DEFAULT_TTL = 60; // デフォルトTTLは60秒 -const momento = await CacheClient.create(authToken, DEFAULT_TTL); +const momento = await CacheClient.create(apiKey, DEFAULT_TTL); // "myCache"という名のキャッシュを作成する const CACHE_NAME = "myCache"; diff --git a/examples/nodejs/observability/README.ja.md b/examples/nodejs/observability/README.ja.md index 9ba551827..9c93c9d74 100644 --- a/examples/nodejs/observability/README.ja.md +++ b/examples/nodejs/observability/README.ja.md @@ -33,11 +33,11 @@ npm install @gomomento/sdk import { CacheClient, CacheGetStatus } from "@gomomento/sdk"; // ユーザーのMomentoオーストークン -const authToken = process.env.MOMENTO_API_KEY; +const apiKey = process.env.MOMENTO_API_KEY; // Momentoをイニシャライズする const DEFAULT_TTL = 60; // デフォルトTTLは60秒 -const momento = new CacheClient(authToken, DEFAULT_TTL); +const momento = new CacheClient(apiKey, DEFAULT_TTL); // "myCache"という名のキャッシュを作成する const CACHE_NAME = "myCache"; diff --git a/examples/nodejs/token-vending-machine/README.md b/examples/nodejs/token-vending-machine/README.md index acd25a114..a1ce568d3 100644 --- a/examples/nodejs/token-vending-machine/README.md +++ b/examples/nodejs/token-vending-machine/README.md @@ -51,7 +51,7 @@ You will also need a superuser API key generated from the [Momento Console](http Then run: ``` -npm run cdk -- deploy --parameters MomentoAuthToken= +npm run cdk -- deploy --parameters MomentoApiKey= ``` When the command completes, you should see something like this near the end of the output: diff --git a/examples/nodejs/token-vending-machine/infrastructure/lib/token-vending-machine-stack.ts b/examples/nodejs/token-vending-machine/infrastructure/lib/token-vending-machine-stack.ts index 7c7caf519..a2d84163a 100644 --- a/examples/nodejs/token-vending-machine/infrastructure/lib/token-vending-machine-stack.ts +++ b/examples/nodejs/token-vending-machine/infrastructure/lib/token-vending-machine-stack.ts @@ -13,16 +13,16 @@ export class TokenVendingMachineStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); - const momentoAuthTokenParam = new cdk.CfnParameter(this, 'MomentoAuthToken', { + const momentoApiKeyParam = new cdk.CfnParameter(this, 'MomentoApiKey', { type: 'String', description: 'The Momento API key that will be used to vend browser tokens. Generated tokens will be stored in Secrets Manager for ongoing access later.', noEcho: true, }); - const authTokenSecret = new secrets.Secret(this, 'MomentoTokenVendingMachineAuthToken', { - secretName: 'MomentoTokenVendingMachineAuthToken', - secretStringValue: new cdk.SecretValue(momentoAuthTokenParam.valueAsString), + const apiKeySecret = new secrets.Secret(this, 'MomentoTokenVendingMachineApiKey', { + secretName: 'MomentoTokenVendingMachineApiKey', + secretStringValue: new cdk.SecretValue(momentoApiKeyParam.valueAsString), }); const tvmLambda = new lambdaNodejs.NodejsFunction(this, 'MomentoTokenVendingMachine', { @@ -35,11 +35,11 @@ export class TokenVendingMachineStack extends cdk.Stack { timeout: cdk.Duration.seconds(30), memorySize: 128, environment: { - MOMENTO_API_KEY_SECRET_NAME: authTokenSecret.secretName, + MOMENTO_API_KEY_SECRET_NAME: apiKeySecret.secretName, }, }); - authTokenSecret.grantRead(tvmLambda); + apiKeySecret.grantRead(tvmLambda); const api = new apig.RestApi(this, 'MomentoTokenVendingMachineApi', { restApiName: 'Momento Token Vending Machine', diff --git a/examples/nodejs/token-vending-machine/lambda/token-vending-machine/config.ts b/examples/nodejs/token-vending-machine/lambda/token-vending-machine/config.ts index b3cdf67ae..9001690f3 100644 --- a/examples/nodejs/token-vending-machine/lambda/token-vending-machine/config.ts +++ b/examples/nodejs/token-vending-machine/lambda/token-vending-machine/config.ts @@ -1,10 +1,4 @@ -import { - ExpiresIn, - AllTopics, - CacheRole, - TopicRole, - type DisposableTokenScope, -} from "@gomomento/sdk"; +import {ExpiresIn, AllTopics, CacheRole, TopicRole, DisposableTokenScope} from '@gomomento/sdk'; /** * First, set the scope of permissions for your tokens. @@ -49,14 +43,15 @@ export const tokenPermissions: DisposableTokenScope = { permissions: [ { role: CacheRole.ReadWrite, - cache: "default-cache" + cache: 'default-cache', }, { - role: TopicRole.PublishSubscribe, - cache: "default-cache", - topic: AllTopics - } -]}; + role: TopicRole.PublishSubscribe, + cache: 'default-cache', + topic: AllTopics, + }, + ], +}; /** * Second, set the TTL for your tokens in terms of seconds, minutes, hours, @@ -68,15 +63,15 @@ export const tokenPermissions: DisposableTokenScope = { export const tokenExpiresIn: ExpiresIn = ExpiresIn.hours(1); /** - * Third, set the authentication method for the token vending machine to protect + * Third, set the authentication method for the token vending machine to protect * against unauthorized users. The available options are provided below. - * + * * Note: when using Amazon Cognito, you'll need to first sign into Cognito to get an ID - * token that you'll include in your requests to the Token Vending Machine API. + * token that you'll include in your requests to the Token Vending Machine API. */ export enum AuthenticationMethod { - Open, // no authentication + Open, // no authentication LambdaAuthorizer, // use Lambda Authorizer attached to API Gateway - AmazonCognito, // use Cognito user pool authorizer attached to API Gateway + AmazonCognito, // use Cognito user pool authorizer attached to API Gateway } -export const authenticationMethod: AuthenticationMethod = AuthenticationMethod.Open; \ No newline at end of file +export const authenticationMethod: AuthenticationMethod = AuthenticationMethod.Open; diff --git a/examples/nodejs/token-vending-machine/lambda/token-vending-machine/handler.ts b/examples/nodejs/token-vending-machine/lambda/token-vending-machine/handler.ts index 77509e6bc..3f4bd9ccc 100644 --- a/examples/nodejs/token-vending-machine/lambda/token-vending-machine/handler.ts +++ b/examples/nodejs/token-vending-machine/lambda/token-vending-machine/handler.ts @@ -9,19 +9,19 @@ let _momentoAuthClient: AuthClient | undefined = undefined; export const handler = async (event: APIGatewayProxyEvent): Promise => { try { - const vendorAuthTokenSecretName = process.env.MOMENTO_API_KEY_SECRET_NAME; - if (vendorAuthTokenSecretName === undefined) { + const vendorApiKeySecretName = process.env.MOMENTO_API_KEY_SECRET_NAME; + if (vendorApiKeySecretName === undefined) { throw new Error("Missing required env var 'MOMENTO_API_KEY_SECRET_NAME"); } - console.log("headers in handler:", event.headers); - const vendedAuthToken = await vendAuthToken(vendorAuthTokenSecretName, event.headers); + console.log('headers in handler:', event.headers); + const vendedApiKey = await vendDisposableToken(vendorApiKeySecretName, event.headers); return { statusCode: 200, headers: { - "Content-Type": "application/json", - "Access-Control-Allow-Origin": "*" + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', }, - body: JSON.stringify(vendedAuthToken), + body: JSON.stringify(vendedApiKey), }; } catch (err) { console.log(err); @@ -34,20 +34,25 @@ export const handler = async (event: APIGatewayProxyEvent): Promise { - const momentoAuthClient = await getMomentoAuthClient(vendorAuthTokenSecretName); +async function vendDisposableToken( + vendorApiKeySecretName: string, + headers: APIGatewayProxyEventHeaders +): Promise { + const momentoAuthClient = await getMomentoAuthClient(vendorApiKeySecretName); let generateTokenResponse; if (authenticationMethod === AuthenticationMethod.AmazonCognito) { const cognitoUserTokenPermissions = determineCognitoUserTokenScope(headers); - generateTokenResponse = await momentoAuthClient.generateDisposableToken(cognitoUserTokenPermissions, tokenExpiresIn); - } - else { + generateTokenResponse = await momentoAuthClient.generateDisposableToken( + cognitoUserTokenPermissions, + tokenExpiresIn + ); + } else { generateTokenResponse = await momentoAuthClient.generateDisposableToken(tokenPermissions, tokenExpiresIn); } @@ -62,27 +67,25 @@ async function vendAuthToken(vendorAuthTokenSecretName: string, headers: APIGate } function determineCognitoUserTokenScope(headers: APIGatewayProxyEventHeaders) { - if (!("cachename" in headers) || !("usergroup" in headers)) { + if (!('cachename' in headers) || !('usergroup' in headers)) { throw new Error("Could not find expected headers 'cachename' and 'usergroup'"); } - if (headers["cachename"] && headers["usergroup"] === 'ReadWriteUserGroup') { - return TokenScopes.topicPublishSubscribe(headers["cachename"], AllTopics); - } - else if (headers["cachename"] && headers["usergroup"] === 'ReadOnlyUserGroup') { - return TokenScopes.topicSubscribeOnly(headers["cachename"], AllTopics); - } - else { - throw new Error(`Unrecognized Cognito user group: ${headers["usergroup"]}`); + if (headers['cachename'] && headers['usergroup'] === 'ReadWriteUserGroup') { + return TokenScopes.topicPublishSubscribe(headers['cachename'], AllTopics); + } else if (headers['cachename'] && headers['usergroup'] === 'ReadOnlyUserGroup') { + return TokenScopes.topicSubscribeOnly(headers['cachename'], AllTopics); + } else { + throw new Error(`Unrecognized Cognito user group: ${headers['usergroup']}`); } } -async function getMomentoAuthClient(authTokenSecretName: string): Promise { +async function getMomentoAuthClient(apiKeySecretName: string): Promise { if (_momentoAuthClient === undefined) { - const momentoAuthToken = await getSecret(authTokenSecretName); + const momentoApiKey = await getSecret(apiKeySecretName); console.log('Retrieved secret!'); _momentoAuthClient = new AuthClient({ - credentialProvider: CredentialProvider.fromString({authToken: momentoAuthToken}), + credentialProvider: CredentialProvider.fromString({apiKey: momentoApiKey}), }); } return _momentoAuthClient; diff --git a/examples/nodejs/topics/README.ja.md b/examples/nodejs/topics/README.ja.md index 061947fec..ace4e238a 100644 --- a/examples/nodejs/topics/README.ja.md +++ b/examples/nodejs/topics/README.ja.md @@ -33,11 +33,11 @@ npm install @gomomento/sdk import { CacheClient, CacheGetStatus } from "@gomomento/sdk"; // ユーザーのMomentoオーストークン -const authToken = process.env.MOMENTO_API_KEY; +const apiKey = process.env.MOMENTO_API_KEY; // Momentoをイニシャライズする const DEFAULT_TTL = 60; // デフォルトTTLは60秒 -const momento = await CacheClient.create(authToken, DEFAULT_TTL); +const momento = await CacheClient.create(apiKey, DEFAULT_TTL); // "myCache"という名のキャッシュを作成する const CACHE_NAME = "myCache"; diff --git a/examples/web/cache/README.ja.md b/examples/web/cache/README.ja.md index 9ba551827..9c93c9d74 100644 --- a/examples/web/cache/README.ja.md +++ b/examples/web/cache/README.ja.md @@ -33,11 +33,11 @@ npm install @gomomento/sdk import { CacheClient, CacheGetStatus } from "@gomomento/sdk"; // ユーザーのMomentoオーストークン -const authToken = process.env.MOMENTO_API_KEY; +const apiKey = process.env.MOMENTO_API_KEY; // Momentoをイニシャライズする const DEFAULT_TTL = 60; // デフォルトTTLは60秒 -const momento = new CacheClient(authToken, DEFAULT_TTL); +const momento = new CacheClient(apiKey, DEFAULT_TTL); // "myCache"という名のキャッシュを作成する const CACHE_NAME = "myCache"; diff --git a/examples/web/nextjs-chat/src/app/api/momento/token/route.ts b/examples/web/nextjs-chat/src/app/api/momento/token/route.ts index 40aea72e1..40f648a40 100644 --- a/examples/web/nextjs-chat/src/app/api/momento/token/route.ts +++ b/examples/web/nextjs-chat/src/app/api/momento/token/route.ts @@ -14,34 +14,36 @@ import { getServerSession } from "next-auth"; const authClient = new AuthClient({ credentialProvider: CredentialProvider.fromString({ - authToken: process.env.MOMENTO_API_KEY, + apiKey: process.env.MOMENTO_API_KEY, }), }); export const revalidate = 0; export async function GET(_request: Request) { - let generateAuthTokenResponse; + let generateDisposableTokenResponse; switch (authenticationMethod) { case AuthenticationMethod.Open: - generateAuthTokenResponse = await fetchTokenWithOpenAuth(); + generateDisposableTokenResponse = await fetchTokenWithOpenAuth(); break; case AuthenticationMethod.Credentials: - generateAuthTokenResponse = await fetchTokenWithAuthCredentials(); + generateDisposableTokenResponse = await fetchTokenWithAuthCredentials(); break; default: throw new Error("Unimplemented authentication method"); } - if (generateAuthTokenResponse instanceof GenerateDisposableToken.Success) { - return new Response(generateAuthTokenResponse.authToken, { + if ( + generateDisposableTokenResponse instanceof GenerateDisposableToken.Success + ) { + return new Response(generateDisposableTokenResponse.authToken, { headers: { "Cache-Control": "no-cache", }, }); } else if ( - generateAuthTokenResponse instanceof GenerateDisposableToken.Error + generateDisposableTokenResponse instanceof GenerateDisposableToken.Error ) { - throw new Error(generateAuthTokenResponse.message()); + throw new Error(generateDisposableTokenResponse.message()); } throw new Error("Unable to get token from momento"); } diff --git a/examples/web/nextjs-chat/src/utils/momento-web.ts b/examples/web/nextjs-chat/src/utils/momento-web.ts index 4efc164ca..e5b026620 100644 --- a/examples/web/nextjs-chat/src/utils/momento-web.ts +++ b/examples/web/nextjs-chat/src/utils/momento-web.ts @@ -50,7 +50,7 @@ async function getNewWebClients(): Promise { const topicClient = new TopicClient({ configuration: Configurations.Browser.v1(), credentialProvider: CredentialProvider.fromString({ - authToken: token, + apiKey: token, }), }); webTopicClient = topicClient; diff --git a/examples/web/vite-chat-app/src/utils/momento-web.ts b/examples/web/vite-chat-app/src/utils/momento-web.ts index c934c0655..b6a6c2295 100644 --- a/examples/web/vite-chat-app/src/utils/momento-web.ts +++ b/examples/web/vite-chat-app/src/utils/momento-web.ts @@ -65,12 +65,12 @@ async function getNewWebClients(selectedUser?: string): Promise throw new Error(`Unrecognized token vending machine auth type ${token_vending_machine_auth}`); } } - + const token = await fetchResp.json(); const topicClient = new TopicClient({ configuration: Configurations.Browser.v1(), credentialProvider: CredentialProvider.fromString({ - authToken: token.authToken, + apiKey: token.apiKey, }), }); webTopicClient = topicClient; @@ -102,7 +102,7 @@ async function fetchTokenWithLambdaAuth() { } async function fetchTokenWithCognitoAuth(selectedUser?: string) { - // Cognito auth flow: sign into Cognito, get ID token, pass ID token as + // Cognito auth flow: sign into Cognito, get ID token, pass ID token as // the Authorization token to the token vending machine const cognitoClient = new CognitoIdentityProviderClient({ "region": import.meta.env.VITE_TOKEN_VENDING_MACHINE_AWS_REGION, @@ -114,13 +114,13 @@ async function fetchTokenWithCognitoAuth(selectedUser?: string) { let userCredentials = {}; if (selectedUser === "ReadWrite") { - userCredentials = { + userCredentials = { "USERNAME": import.meta.env.VITE_TOKEN_VENDING_MACHINE_USERNAME_READWRITE, "PASSWORD": import.meta.env.VITE_TOKEN_VENDING_MACHINE_PASSWORD_READWRITE, }; } else { - userCredentials = { + userCredentials = { "USERNAME": import.meta.env.VITE_TOKEN_VENDING_MACHINE_USERNAME_READONLY, "PASSWORD": import.meta.env.VITE_TOKEN_VENDING_MACHINE_PASSWORD_READONLY, }; @@ -129,7 +129,7 @@ async function fetchTokenWithCognitoAuth(selectedUser?: string) { const input = { AuthFlow: "USER_PASSWORD_AUTH", AuthParameters: userCredentials, - ClientId: import.meta.env.VITE_TOKEN_VENDING_MACHINE_CLIENT_ID, + ClientId: import.meta.env.VITE_TOKEN_VENDING_MACHINE_CLIENT_ID, }; const command = new InitiateAuthCommand(input); const response = await cognitoClient.send(command); @@ -140,7 +140,7 @@ async function fetchTokenWithCognitoAuth(selectedUser?: string) { const decodedToken: any = jwt_decode(IdToken); const userCognitoGroup = decodedToken['cognito:groups'][0]; - + // Make the actual API call to the token vending machine here return await fetch(import.meta.env.VITE_TOKEN_VENDING_MACHINE_URL, { cache: "no-store", // don't cache the token since it will expire in 5 min @@ -203,7 +203,7 @@ async function publish(cacheName: string, topicName: string, message: string) { clearCurrentClient(); await subscribeToTopic(cacheName, topicName, onItemCb, onErrorCb); await publish(cacheName, topicName, message); - } + } else if (resp.errorCode() === MomentoErrorCode.PERMISSION_ERROR) { console.log("User is not allowed to publish to topic", resp); alert("You have entered the chat room as a read-only user!");