Skip to content

Commit

Permalink
No commit message
Browse files Browse the repository at this point in the history
  • Loading branch information
2 parents 46d2858 + d7056f3 commit 2a4b51e
Show file tree
Hide file tree
Showing 61 changed files with 840 additions and 388 deletions.
2 changes: 1 addition & 1 deletion .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
updates: []

########################################################################################################################
#
Expand Down
10 changes: 10 additions & 0 deletions examples/cloudflare-workers/http-api/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ export interface Env {

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {

if (env.MOMENTO_API_KEY === undefined) {
throw new Error('MOMENTO_API_KEY should be set in .dev.vars for local development, and should' +
' be uploaded to Cloudflare secrets through NPX if you are testing your worker. See README for more details')
}

if (env.MOMENTO_CACHE_NAME === undefined) {
throw new Error('MOMENTO_CACHE_NAME should be set in wrangler.toml file. See README for more details')
}

const client = new MomentoFetcher(env.MOMENTO_API_KEY, env.MOMENTO_REST_ENDPOINT);
const cache = env.MOMENTO_CACHE_NAME;
const key = "key";
Expand Down
4 changes: 2 additions & 2 deletions examples/cloudflare-workers/web-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ npm install

- Next, if you don't have one already, create a cache inside the [Momento console](https://console.gomomento.com/caches).

- Cloudflare uses a file called wrangler.toml to configure the development and publishing of a worker. More information about Cloudflare configuration can be found [on their website](https://developers.cloudflare.com/workers/wrangler/configuration/). In the example directory, update the `wrangler.toml` file and set the `MOMENTO_CACHE` environment variable to match the name of the cache you created earlier.


### Setting up Momento Authentication
- In the Momento console, generate an [API key for your cache](https://console.gomomento.com/tokens), making sure to choose the same AWS region you used to create the cache. You'll want to use a `Fine-Grained Access Key` with read/write permissions for the cache you created.
![Console API Key Screen](https://assets.website-files.com/628fadb065a50abf13a11485/64b97cb50a7e1d8d752ae539_3fU8mYh6gAhMwUYzrLOEiEXQc-KO79zANMtiH141Js2tZydZ7sFxZtr5TWLcC3OzFJTIEMZQOkLtWtBOOTEOEXmpinv1Ah3AC_LdkovI3FU7iUGY_N35cB0op1PXTNHAW0kZ-9wZ6qrCol5wrz_nuA.png)
- Copy the `API key` value from the API key generation screen for use in the next two steps.
![API Key generation results](https://assets.website-files.com/628fadb065a50abf13a11485/64b97cb50d9a0db6b03c40e8_JZLnsjtwN5RaGx83NX424WKmvauAuqcUD3YeWLx2LFFIwLiXHupq1XF3MOyggObfaC8LE1fQUN4b-9nDTOwGYUHugfZYqYTK92HybD2X1OsuRF-DxmJKekTWgV0SY0LzWpE9vvA0To8sGmNXkG-geQ.png)
- Update the `.dev.vars` file in the example directory with the Momento API key. Since this is a secret key, we don’t store it as an environment variable, instead storing it as a Cloudflare secret.
- Cloudflare uses a file called wrangler.toml to configure the development and publishing of a worker. More information about Cloudflare configuration can be found [on their website](https://developers.cloudflare.com/workers/wrangler/configuration/). In the example directory, update the `wrangler.toml` file and set the `MOMENTO_CACHE` environment variable to match the name of the cache you created earlier. Note that
you'll also need to uncomment two lines including line that has `[vars]` in it.
- Start the development server:

### Running locally
Expand Down
16 changes: 8 additions & 8 deletions examples/cloudflare-workers/web-sdk/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/cloudflare-workers/web-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"dependencies": {
"@gomomento/sdk-core": "^1.38.0",
"@gomomento/sdk-web": "^1.39.1",
"@gomomento/sdk-web": "^1.39.3",
"xhr4sw": "^0.0.5"
}
}
11 changes: 10 additions & 1 deletion examples/cloudflare-workers/web-sdk/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,20 @@ export interface Env {
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {

if (env.MOMENTO_API_KEY === undefined) {
throw new Error('MOMENTO_API_KEY should be set in .dev.vars for local development, and should' +
' be uploaded to Cloudflare secrets through NPX if you are testing your worker. See README for more details')
}

if (env.MOMENTO_CACHE_NAME === undefined) {
throw new Error('MOMENTO_CACHE_NAME should be set in wrangler.toml file. See README for more details')
}

console.log(`Creating cache client`);
const momento = new CacheClient({
configuration: Configurations.Laptop.v1(),
credentialProvider: CredentialProvider.fromString({
authToken:env.MOMENTO_API_KEY
apiKey:env.MOMENTO_API_KEY
}),
defaultTtlSeconds: 60,
});
Expand Down
6 changes: 3 additions & 3 deletions examples/deno/http-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export const handler = async (_request: Request): Promise<Response> => {
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')
}

Expand All @@ -26,7 +26,7 @@ export const handler = async (_request: Request): Promise<Response> => {
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}`)
Expand Down
4 changes: 2 additions & 2 deletions examples/deno/web-sdk/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
},
"imports": {
"http": "https://deno.land/[email protected]/http/server.ts",
"momento": "npm:@gomomento/sdk-web@1.35.0",
"momento": "npm:@gomomento/sdk-web@1.39.2",
"xhr4sw": "npm:[email protected]",
"dotenv": "https://deno.land/std/dotenv/mod.ts"

}
}
}
6 changes: 3 additions & 3 deletions examples/deno/web-sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ export const handler = async (_request: Request): Promise<Response> => {
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,
})
Expand Down
6 changes: 3 additions & 3 deletions examples/fastly-compute/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
Expand Down Expand Up @@ -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}`);
Expand Down
22 changes: 9 additions & 13 deletions examples/nodejs/access-control/access-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
DeleteCache,
AuthClient,
ExpiresIn,
GenerateAuthToken,
GenerateApiKey,
TokenScope,
TokenScopes,
CacheRole,
Expand Down Expand Up @@ -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()}`);
}
Expand Down Expand Up @@ -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,
});

Expand Down Expand Up @@ -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.
}

Expand Down
30 changes: 15 additions & 15 deletions examples/nodejs/access-control/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/nodejs/access-control/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@
"typescript": "4.4.3"
},
"dependencies": {
"@gomomento/sdk": "^1.39.1"
"@gomomento/sdk": "^1.39.3"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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,
});
}
Expand Down Expand Up @@ -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');
Expand Down
Loading

0 comments on commit 2a4b51e

Please sign in to comment.