Skip to content

feat: local-session-token-storage-modules #229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: effects-package
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/empty-queens-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---

## '@forgerock/effects': minor

add token and local/session storage manager
23 changes: 13 additions & 10 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import js from '@eslint/js';
import packageJson from 'eslint-plugin-package-json/configs/recommended';
import typescriptEslintEslintPlugin from '@typescript-eslint/eslint-plugin';
import nxEslintPlugin from '@nx/eslint-plugin';
import eslintPluginImport from 'eslint-plugin-import';
import typescriptEslintParser from '@typescript-eslint/parser';

const compat = new FlatCompat({
Expand All @@ -22,7 +21,6 @@ export default [
plugins: {
'@typescript-eslint': typescriptEslintEslintPlugin,
'@nx': nxEslintPlugin,
import: eslintPluginImport,
},
},
{
Expand All @@ -36,7 +34,6 @@ export default [
},
{
rules: {
'import/extensions': [2, 'ignorePackages'],
'@typescript-eslint/indent': ['error', 2],
'@typescript-eslint/no-use-before-define': 'warn',
'max-len': [
Expand All @@ -57,7 +54,19 @@ export default [
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
rules: {
'import/extensions': [2, 'ignorePackages'],
'@typescript-eslint/no-unused-vars': [
'error',
{
args: 'all',
argsIgnorePattern: '^_',
caughtErrors: 'all',
caughtErrorsIgnorePattern: '^_',
destructuredArrayIgnorePattern: '^_',
varsIgnorePattern: '^_',
ignoreRestSiblings: true,
},
],

'@nx/enforce-module-boundaries': [
'warn',
{
Expand Down Expand Up @@ -102,12 +111,6 @@ export default [
files: ['**/*.ts', '**/*.tsx', '!**/*.spec.ts', '!**/*.test*.ts', '**/*.cts', '**/*.mts'],
rules: {
...config.rules,
'@typescript-eslint/no-unused-vars': [
'error',
{
ignoreRestSiblings: true,
},
],
},
})),
...compat
Expand Down
2 changes: 1 addition & 1 deletion nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
},
"test": {
"inputs": ["default", "^default", "noMarkdown", "^noMarkdown"],
"dependsOn": ["^test", "^build"],
"dependsOn": ["^test", "^build", "^build", "^build"],
"outputs": ["{projectRoot}/coverage"],
"cache": true
},
Expand Down
9 changes: 0 additions & 9 deletions packages/device-client/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import { FlatCompat } from '@eslint/eslintrc';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import js from '@eslint/js';
import baseConfig from '../../eslint.config.mjs';

const compat = new FlatCompat({
baseDirectory: dirname(fileURLToPath(import.meta.url)),
recommendedConfig: js.configs.recommended,
});

export default [
{
ignores: ['**/dist'],
Expand Down
5 changes: 5 additions & 0 deletions packages/device-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
"name": "@forgerock/device-client",
"version": "0.0.1",
"private": true,
"repository": {
"type": "git",
"url": "git+https://github.com/ForgeRock/ping-javascript-sdk.git",
"directory": "packages/device-client"
},
"sideEffects": false,
"type": "module",
"exports": {
Expand Down
136 changes: 136 additions & 0 deletions packages/effects/src/lib/local-storage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
*
* Copyright (c) 2025 Ping Identity Corporation. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
import { describe, it, expect, beforeEach, afterEach, vi, Mock } from 'vitest';
import {
getLocalStorageTokens,
setLocalStorageTokens,
removeTokensFromLocalStorage,
tokenFactory,
} from './local-storage.js';
import { TOKEN_ERRORS, type ConfigOptions, type Tokens } from '@forgerock/shared-types';

describe('Token Storage Functions', () => {
// Mock config
const mockConfig: ConfigOptions = {
clientId: 'test-client',
prefix: 'test-prefix',
};

// Sample tokens
const sampleTokens: Tokens = {
accessToken: 'access-token-123',
idToken: 'id-token-456',
refreshToken: 'refresh-token-789',
tokenExpiry: 3600,
};

beforeEach(() => {
vi.clearAllMocks();
const mockLocalStorage = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
};
const mockSessionStorage = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
};

vi.stubGlobal('localStorage', mockLocalStorage);
vi.stubGlobal('sessionStorage', mockSessionStorage);
});

afterEach(() => {
// Restore the original implementations after tests
vi.unstubAllGlobals();
});

describe('getLocalStorageTokens', () => {
it('should return undefined when no tokens exist', () => {
const tokens = getLocalStorageTokens(mockConfig);

expect(localStorage.getItem).toHaveBeenCalledWith('test-prefix-test-client');
expect(tokens).toEqual({
error: TOKEN_ERRORS.NO_TOKENS_FOUND_LOCAL_STORAGE,
});
});

it('should parse and return tokens when they exist', () => {
getLocalStorageTokens(mockConfig);
expect(localStorage.getItem).toHaveBeenCalledWith('test-prefix-test-client');
});

it('should return error object when tokens exist but cannot be parsed', () => {
const result = getLocalStorageTokens(mockConfig);

expect(localStorage.getItem).toHaveBeenCalledWith('test-prefix-test-client');
expect(result).toEqual({ error: TOKEN_ERRORS.NO_TOKENS_FOUND_LOCAL_STORAGE });
});
});

describe('setTokens', () => {
it('should stringify and store tokens in localStorage', () => {
setLocalStorageTokens(mockConfig, sampleTokens);

expect(localStorage.setItem).toHaveBeenCalledWith(
'test-prefix-test-client',
JSON.stringify(sampleTokens),
);
});
});

describe('removeTokens', () => {
it('should remove tokens from localStorage', () => {
removeTokensFromLocalStorage(mockConfig);

expect(localStorage.removeItem).toHaveBeenCalledWith('test-prefix-test-client');
});
});

describe('tokenFactory', () => {
it('should return an object with get, set, and remove methods', () => {
const tokenManager = tokenFactory(mockConfig);

expect(tokenManager).toHaveProperty('get');
expect(tokenManager).toHaveProperty('set');
expect(tokenManager).toHaveProperty('remove');
expect(typeof tokenManager.get).toBe('function');
expect(typeof tokenManager.set).toBe('function');
expect(typeof tokenManager.remove).toBe('function');
});

it('get method should retrieve tokens', () => {
(localStorage.getItem as Mock).mockReturnValueOnce(JSON.stringify(sampleTokens));

const tokenManager = tokenFactory(mockConfig);
const tokens = tokenManager.get();

expect(localStorage.getItem).toHaveBeenCalledWith('test-prefix-test-client');
expect(tokens).toEqual(sampleTokens);
});

it('set method should store tokens', () => {
const tokenManager = tokenFactory(mockConfig);
tokenManager.set(sampleTokens);

expect(localStorage.setItem).toHaveBeenCalledWith(
'test-prefix-test-client',
JSON.stringify(sampleTokens),
);
});

it('remove method should remove tokens', () => {
const tokenManager = tokenFactory(mockConfig);
tokenManager.remove();

expect(localStorage.removeItem).toHaveBeenCalledWith('test-prefix-test-client');
});
});
});
43 changes: 43 additions & 0 deletions packages/effects/src/lib/local-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
*
* Copyright (c) 2025 Ping Identity Corporation. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
import { TOKEN_ERRORS, type ConfigOptions, type Tokens } from '@forgerock/shared-types';

export function getLocalStorageTokens(Config: ConfigOptions) {
const tokenString = localStorage.getItem(`${Config.prefix}-${Config.clientId}`);
if (!tokenString) {
return {
error: TOKEN_ERRORS.NO_TOKENS_FOUND_LOCAL_STORAGE,
};
}
try {
const tokens = JSON.parse(tokenString) as Tokens;
return tokens;
} catch {
return {
error: TOKEN_ERRORS.PARSE_LOCAL_STORAGE,
};
}
}

export function setLocalStorageTokens(Config: ConfigOptions, tokens: Tokens) {
const tokenString = JSON.stringify(tokens);
localStorage.setItem(`${Config.prefix}-${Config.clientId}`, tokenString);
}

export function removeTokensFromLocalStorage(Config: ConfigOptions) {
localStorage.removeItem(`${Config.prefix}-${Config.clientId}`);
}

export function tokenFactory(config: ConfigOptions) {
return {
get: () => getLocalStorageTokens(config),
set: (tokens: Tokens) => setLocalStorageTokens(config, tokens),
remove: () => removeTokensFromLocalStorage(config),
};
}
2 changes: 1 addition & 1 deletion packages/effects/src/lib/request.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const middleware: RequestMiddleware<ActionTypes>[] = [
},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(req: ModifiedFetchArgs, action: Action, next: NextFn): void => {
(_req: ModifiedFetchArgs, action: Action, next: NextFn): void => {
switch (action.type) {
case mutateAction:
action.type = 'hello' as ActionTypes;
Expand Down
Loading
Loading