@ttoss/react-auth 2.6.30 → 2.6.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,178 +1,144 @@
1
1
  # @ttoss/react-auth
2
2
 
3
- This module handles auth in your applications and other ttoss modules.
3
+ AWS Cognito authentication module for React applications using AWS Amplify, built on top of `@ttoss/react-auth-core` for provider-agnostic authentication patterns.
4
4
 
5
- This module is intended to use with AWS Cognito. It uses [AWS Amplify](https://docs.amplify.aws/lib/auth/getting-started/q/platform/js) under the hood.
5
+ ## Installation
6
6
 
7
- [Amplify Auth configuration](https://docs.amplify.aws/lib/auth/start/q/platform/js#re-use-existing-authentication-resource) must be provided in your App to make Auth Module works properly.
8
-
9
- ## ESM Only
7
+ ```shell
8
+ pnpm add @ttoss/react-auth @ttoss/react-notifications aws-amplify
9
+ ```
10
10
 
11
- This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
11
+ ## Core Concepts
12
12
 
13
- ## Getting Started
13
+ This package provides AWS Cognito-specific implementations of the authentication patterns defined in `@ttoss/react-auth-core`. It automatically handles Amplify configuration, auth state management, and integrates with ttoss notification system.
14
14
 
15
- ### Install
15
+ **Key Features:**
16
16
 
17
- ```shell
18
- $ yarn add @ttoss/auth @ttoss/react-notifications aws-amplify
19
- ```
17
+ - AWS Cognito authentication with Amplify
18
+ - Automatic auth state synchronization
19
+ - Built-in error handling and notifications
20
+ - TypeScript support with full type safety
21
+ - ESM-only package
20
22
 
21
- ## Examples of use
23
+ ## Quick Start
22
24
 
23
- ### Amplify config
25
+ ### 1. Configure AWS Amplify
24
26
 
25
27
  ```ts
26
28
  import { Amplify, type ResourcesConfig } from 'aws-amplify';
27
- import {
28
- CookieStorage,
29
- KeyValueStorageInterface,
30
- defaultStorage,
31
- sessionStorage,
32
- } from 'aws-amplify/utils';
33
- import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
34
29
 
35
30
  const authConfig: ResourcesConfig['Auth'] = {
36
31
  Cognito: {
37
- // REQUIRED Amazon Cognito User Pool Client ID (26-char alphanumeric string)
38
- userPoolClientId: 'a1b2c3d4e5f6g7h8i9j0k1l2m3',
39
-
40
- // OPTIONAL - Amazon Cognito User Pool ID
41
- userPoolId: 'XX-XXXX-X_abcd1234',
42
-
43
- loginWith: {
44
- // OPTIONAL - Hosted UI configuration
45
- oauth: {
46
- domain: 'your_cognito_domain',
47
- scopes: [
48
- 'phone',
49
- 'email',
50
- 'profile',
51
- 'openid',
52
- 'aws.cognito.signin.user.admin',
53
- ],
54
- redirectSignIn: ['http://localhost:3000/'],
55
- redirectSignOut: ['http://localhost:3000/'],
56
- responseType: 'code', // or 'token', note that REFRESH token will only be generated when the responseType is code
57
- },
58
- },
32
+ // ... your Cognito config
59
33
  },
60
34
  };
61
35
 
62
- Amplify.configure({
63
- Auth: authConfig,
64
- });
65
-
66
- // Browser Local Storage
67
- // In Amplify the localStorage is the default storage mechanism. It saves the tokens in the browser's localStorage.
68
- // This local storage will persist across browser sessions and tabs. You can explicitly set to this storage by calling:
69
- cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage);
70
-
71
- // Cookie Storage
72
- // CookieStorage saves the tokens in the browser's Cookies. The cookies will persist across browser sessions and tabs.
73
- // You can explicitly set to this storage by calling:
74
- cognitoUserPoolsTokenProvider.setKeyValueStorage(
75
- new CookieStorage(
76
- // OPTIONAL - Configuration for cookie storage
77
- {
78
- // REQUIRED - Cookie domain (only required if cookieStorage is provided)
79
- domain: '.yourdomain.com',
80
- // OPTIONAL - Cookie path
81
- path: '/',
82
- // OPTIONAL - Cookie expiration in days
83
- expires: 365,
84
- // OPTIONAL - See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
85
- sameSite: 'strict' | 'lax' | 'none',
86
- // OPTIONAL - Cookie secure flag
87
- // Either true or false, indicating if the cookie transmission requires a secure protocol (https).
88
- secure: true,
89
- }
90
- )
91
- );
36
+ Amplify.configure({ Auth: authConfig });
37
+ ```
92
38
 
93
- // Browser Session Storage
94
- // sessionStorage saves the tokens in the browser's sessionStorage and these tokens will clear when a tab is closed.
95
- // The benefit to this storage mechanism is that the session only lasts as long as the browser is open and you
96
- // can sign out users when they close the tab. You can update to this storage by calling:
97
- cognitoUserPoolsTokenProvider.setKeyValueStorage(sessionStorage);
39
+ ### 2. Setup Authentication Provider
98
40
 
99
- // Custom Storage
100
- // You can implement your own custom storage mechanism by creating a class that implements the storage interface.
101
- // Here is an example that uses memory storage:
41
+ ```tsx
42
+ import { AuthProvider } from '@ttoss/react-auth';
43
+ import { NotificationsProvider } from '@ttoss/react-notifications';
102
44
 
103
- class MyCustomStorage implements KeyValueStorageInterface {
104
- storageObject: Record<string, string> = {};
105
- async setItem(key: string, value: string): Promise<void> {
106
- this.storageObject[key] = value;
107
- }
108
- async getItem(key: string): Promise<string | null> {
109
- return this.storageObject[key];
110
- }
111
- async removeItem(key: string): Promise<void> {
112
- delete this.storageObject[key];
113
- }
114
- async clear(): Promise<void> {
115
- this.storageObject = {};
116
- }
45
+ function App() {
46
+ return (
47
+ <NotificationsProvider>
48
+ <AuthProvider>
49
+ <YourApp />
50
+ </AuthProvider>
51
+ </NotificationsProvider>
52
+ );
117
53
  }
118
-
119
- cognitoUserPoolsTokenProvider.setKeyValueStorage(new MyCustomStorage());
120
54
  ```
121
55
 
122
- ### PrivateRoute component
56
+ ### 3. Use Authentication in Components
123
57
 
124
58
  ```tsx
125
- import { useAuth } from '@ttoss/react-auth';
59
+ import { Auth, useAuth } from '@ttoss/react-auth';
60
+ import { Navigate } from 'react-router-dom';
61
+
62
+ // Authentication form component
63
+ function LoginPage() {
64
+ return <Auth />;
65
+ }
126
66
 
127
- const PrivateRoute = (props: any) => {
67
+ // Protected route component
68
+ function PrivateRoute({ children }: { children: React.ReactNode }) {
128
69
  const { isAuthenticated } = useAuth();
129
70
 
130
71
  if (!isAuthenticated) {
131
- return <Navigate to="/login" state={{ redirectTo: props.path || '/' }} />;
72
+ return <Navigate to="/login" />;
132
73
  }
133
- return <Route {...props} />;
134
- };
74
+
75
+ return <>{children}</>;
76
+ }
77
+
78
+ // Using auth state
79
+ function UserProfile() {
80
+ const { user, signOut } = useAuth();
81
+
82
+ return (
83
+ <div>
84
+ <h1>Welcome, {user?.email}</h1>
85
+ <button onClick={signOut}>Sign Out</button>
86
+ </div>
87
+ );
88
+ }
135
89
  ```
136
90
 
137
- ### Login Page
91
+ ## API Reference
138
92
 
139
- ```tsx
140
- import { Auth, useAuth } from '@ttoss/react-auth';
93
+ ### `useAuth()`
141
94
 
142
- const Login = () => {
143
- const auth = useAuth();
95
+ Returns authentication state and methods:
144
96
 
145
- const onSuccess = () => {
146
- // Navigate to logged-area
147
- };
97
+ ```tsx
98
+ const {
99
+ user, // Current user data or null
100
+ isAuthenticated, // Boolean authentication status
101
+ signOut, // Function to sign out user
102
+ } = useAuth();
103
+ ```
148
104
 
149
- return (
150
- <div>
151
- <h1>Login Page</h1>
105
+ ### `getAuthData(options?)`
152
106
 
153
- <Auth onSignIn={onSuccess} />
107
+ Retrieve current authentication data programmatically:
154
108
 
155
- <button onClick={auth.signOut}>Logout</button>
156
- </div>
157
- );
158
- };
159
- export default Login;
109
+ ```tsx
110
+ import { getAuthData } from '@ttoss/react-auth';
111
+
112
+ const authData = await getAuthData({ includeTokens: true });
160
113
  ```
161
114
 
162
- ## Auth with Progressbar
115
+ ### `checkAuth()`
116
+
117
+ Check if user is currently authenticated:
163
118
 
164
119
  ```tsx
165
- import { AuthProvider } from '@ttoss/react-auth';
166
- import { NotificationsProvider } from '@ttoss/react-notifications';
120
+ import { checkAuth } from '@ttoss/react-auth';
167
121
 
168
- ReactDOM.render(
169
- <React.StrictMode>
170
- <NotificationsProvider>
171
- <AuthProvider>
172
- <App />
173
- </AuthProvider>
174
- </NotificationsProvider>
175
- </React.StrictMode>,
176
- document.getElementById('root')
122
+ const isAuthenticated = await checkAuth();
123
+ ```
124
+
125
+ ## Storage Configuration
126
+
127
+ Configure token storage mechanism using Amplify's storage options:
128
+
129
+ ```ts
130
+ import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
131
+ import { CookieStorage, sessionStorage } from 'aws-amplify/utils';
132
+
133
+ // Cookie storage (recommended for production)
134
+ cognitoUserPoolsTokenProvider.setKeyValueStorage(
135
+ new CookieStorage({
136
+ domain: '.yourdomain.com',
137
+ secure: true,
138
+ sameSite: 'strict',
139
+ })
177
140
  );
141
+
142
+ // Session storage (clears on tab close)
143
+ cognitoUserPoolsTokenProvider.setKeyValueStorage(sessionStorage);
178
144
  ```