Skip to content

Commit

Permalink
feat: introduces use auth client
Browse files Browse the repository at this point in the history
  • Loading branch information
krpeacock committed Aug 2, 2024
1 parent ed4f2d0 commit 322781b
Show file tree
Hide file tree
Showing 11 changed files with 15,116 additions and 12,641 deletions.
27,583 changes: 14,942 additions & 12,641 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"packages/auth-client",
"packages/assets",
"packages/identity-secp256k1",
"packages/use-auth-client",
"e2e/node"
]
},
Expand Down
3 changes: 3 additions & 0 deletions packages/use-auth-client/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env", "@babel/preset-typescript", "@babel/preset-react"]
}
1 change: 1 addition & 0 deletions packages/use-auth-client/examples/auth-demo
Submodule auth-demo added at 47b995
6 changes: 6 additions & 0 deletions packages/use-auth-client/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: ['<rootDir>/test'],
setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],
};
29 changes: 29 additions & 0 deletions packages/use-auth-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@dfinity/use-auth-client",
"version": "2.0.0",
"description": "React hooks for using the auth client",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"unpkg": "./lib/esm/index",
"scripts": {
"test": "vitest"
},
"keywords": [],
"author": "Kai Peacock",
"license": "ISC",
"dependencies": {
"@dfinity/auth-client": "^2.0.0",
"react": ">16.8"
},
"devDependencies": {
"@babel/preset-env": "^7.25.3",
"@babel/preset-react": "^7.24.7",
"@babel/preset-typescript": "^7.24.7",
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@types/react": "16.8",
"fake-indexeddb": "^6.0.0",
"jest": "^29.7.0",
"vitest": "^2.0.5"
}
}
5 changes: 5 additions & 0 deletions packages/use-auth-client/setupTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import 'fake-indexeddb/auto';
import { TextEncoder } from 'util';
import '@testing-library/jest-dom';

global.TextEncoder = TextEncoder;
1 change: 1 addition & 0 deletions packages/use-auth-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './use-auth-client';
89 changes: 89 additions & 0 deletions packages/use-auth-client/src/use-auth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import * as React from 'react';
import {
AuthClient,
AuthClientCreateOptions,
AuthClientLoginOptions,
InternetIdentityAuthResponseSuccess,
} from '@dfinity/auth-client';
import { Identity } from '@dfinity/agent';

/**
* Options for the useAuthClient hook
*/
export type UseAuthClientOptions = {
/**
* Options passed during the creation of the auth client
*/
createOptions?: AuthClientCreateOptions;
/**
* Options passed during the login of the auth client
*/
loginOptions?: AuthClientLoginOptions;
};

/**
* React hook to set up the Internet Computer auth client
* @param {UseAuthClientOptions} options configuration for the hook
* @see {@link UseAuthClientOptions}
* @param {AuthClientCreateOptions} options.createOptions - options passed during the creation of the auth client
* @param {AuthClientLoginOptions} options.loginOptions -
*/
export function useAuthClient(options?: UseAuthClientOptions) {
const [authClient, setAuthClient] = React.useState<AuthClient | null>(null);
const [identity, setIdentity] = React.useState<Identity | null>(null);
const [isAuthenticated, setIsAuthenticated] = React.useState<boolean>(false);

// load the auth client on mount
React.useEffect(() => {
AuthClient.create(options?.createOptions).then(async client => {
setAuthClient(client);
setIdentity(client.getIdentity());
setIsAuthenticated(await client.isAuthenticated());
});
}, []);

/**
* Login through your configured identity provider
* Wraps the onSuccess and onError callbacks with promises for convenience
* @returns {Promise<InternetIdentityAuthResponseSuccess | void>} - Returns a promise that resolves to the response from the identity provider
*/
function login(): Promise<InternetIdentityAuthResponseSuccess | void> {
return new Promise((resolve, reject) => {
if (authClient) {
const callback = options?.loginOptions?.onSuccess;
const errorCb = options?.loginOptions?.onError;
authClient.login({
...options?.loginOptions,
onSuccess: (successResponse?: InternetIdentityAuthResponseSuccess) => {
if (successResponse !== undefined) {
callback?.(successResponse);
} else {
(callback as () => void)?.();
resolve(successResponse);
}
},
onError: error => {
errorCb?.(error);
reject(error);
},
});
}
});
}

async function logout() {
if (authClient) {
setIsAuthenticated(false);
setIdentity(null);
await authClient.logout();
}
}

return {
authClient,
identity,
isAuthenticated,
login,
logout,
};
}
25 changes: 25 additions & 0 deletions packages/use-auth-client/test/use-auth-client.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import * as React from 'react';
import { render, screen } from '@testing-library/react';
import { useAuthClient } from '../src/use-auth-client';
import { describe, it } from '@jest/globals';

describe('useAuthClient', () => {
it('should return an authClient object with the expected properties', async () => {
function Component() {
const { authClient, identity, isAuthenticated, login, logout } = useAuthClient();
return (
<div>
<div>authClient: {authClient}</div>
<div>identity: {identity}</div>
<div data-testid="isAuthenticated">{String(isAuthenticated)}</div>
<button onClick={login}>Login</button>
<button onClick={logout}>Logout</button>
</div>
);
}
render(<Component />);

const isAuthenticated = screen.getByTestId('isAuthenticated');
expect(isAuthenticated).toHaveTextContent('false');
});
});
14 changes: 14 additions & 0 deletions packages/use-auth-client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"allowJs": true,
"esModuleInterop": true,
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"lib": ["es5", "es2015", "dom"],
"jsx": "react",
"declaration": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "test"]
}

0 comments on commit 322781b

Please sign in to comment.