aws-amplify
Version:
AWS Amplify is a JavaScript library for Frontend and mobile developers building cloud-enabled applications.
69 lines (66 loc) • 3.08 kB
JavaScript
import { DEFAULT_AUTH_TOKEN_COOKIES_MAX_AGE } from '../constants.mjs';
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
const defaultSetCookieOptions = {
// TODO: allow configure with a public interface
sameSite: 'lax',
secure: true,
path: '/',
};
/**
* Creates a Key Value storage interface using the `cookieStorageAdapter` as the
* underlying storage.
* @param cookieStorageAdapter An implementation of the `Adapter` in {@link CookieStorage}.
* @returns An object that implements {@link KeyValueStorageInterface}.
*/
const createKeyValueStorageFromCookieStorageAdapter = (cookieStorageAdapter, validator, setCookieOptions = {}) => {
// `setItem` and `removeItem` must use the same Path and Domain, otherwise the
// browser treats them as different cookies and the deletion does not match.
const { path, domain } = {
...defaultSetCookieOptions,
...setCookieOptions,
};
return {
setItem(key, value) {
// Delete the cookie item first then set it. This results:
// SetCookie: key=;expires=1970-01-01;(path='current-path') <- remove path'ed cookies
// SetCookie: key=value;expires=Date.now() + 365 days;path=/;secure=true
// Deliberately path-less: clears a leftover cookie stored at the request's
// default path. The `Path=/` cookie is replaced by the `set` below.
cookieStorageAdapter.delete(key);
const mergedCookieOptions = {
...defaultSetCookieOptions,
...setCookieOptions,
};
// when expires and maxAge both are not specified, we set a default maxAge
if (!mergedCookieOptions.expires && !mergedCookieOptions.maxAge) {
mergedCookieOptions.maxAge = DEFAULT_AUTH_TOKEN_COOKIES_MAX_AGE;
}
cookieStorageAdapter.set(key, value, mergedCookieOptions);
return Promise.resolve();
},
async getItem(key) {
const cookie = cookieStorageAdapter.get(key);
const value = cookie?.value ?? null;
if (value && validator?.getItem) {
const isValid = await validator.getItem(key, value);
if (!isValid)
return null;
}
return value;
},
removeItem(key) {
// Delete the cookie with the same Path and Domain used by `setItem`.
// Without them, the browser uses the current request path as the cookie
// path, and the cookie set with `Path=/` is not removed.
cookieStorageAdapter.delete(key, { path, domain });
return Promise.resolve();
},
clear() {
// TODO(HuiSF): follow up the implementation.
throw new Error('This method has not implemented.');
},
};
};
export { createKeyValueStorageFromCookieStorageAdapter, defaultSetCookieOptions };
//# sourceMappingURL=createKeyValueStorageFromCookieStorageAdapter.mjs.map