{"_id":"@aetosky/auth","_rev":"1-2b854a28bfcc37902e93faa58d15cd65","name":"@aetosky/auth","dist-tags":{"latest":"1.0.1"},"versions":{"1.0.0":{"name":"@aetosky/auth","version":"1.0.0","keywords":["oauth2","authentication","typescript"],"author":{"name":"Aetosky"},"license":"MIT","_id":"@aetosky/auth@1.0.0","maintainers":[{"name":"thai.bui","email":"thai.bui@aetosky.com"}],"dist":{"shasum":"b7446097faaf26872c7e1592aa26e713dbe0b98a","tarball":"https://registry.npmjs.org/@aetosky/auth/-/auth-1.0.0.tgz","fileCount":11,"integrity":"sha512-OPqtsb9VWoDJd9Qr3enT6kj68uCx+Pywjg9aFgKmo6cjd8OaSKe/GbKnslSCV6A+GhuqTlCSryavH36WFyIpPQ==","signatures":[{"sig":"MEYCIQD5aCNrqeBuiz3H1r7S33PTm0bHmPtrQyKTxhDwUl7SCgIhAMH930RhjLIfedKeebK86KKeQ04HOEMVGR3KPT6PDyoP","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":31479},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"860150241e6542eca8aa380952bcea2825317c40","scripts":{"test":"jest","build":"tsc"},"_npmUser":{"name":"thai.bui","email":"thai.bui@aetosky.com"},"repository":{"url":"https://git.eofactory.ai/aetos-x/aetos-v2/auth-js-library.git","type":"git"},"_npmVersion":"10.8.1","description":"A lightweight OAuth2 client library for JavaScript/TypeScript.","directories":{},"_nodeVersion":"20.16.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^27.0.0","ts-jest":"^27.0.0","typescript":"^4.0.0","@types/jest":"^27.0.0"},"_npmOperationalInternal":{"tmp":"tmp/auth_1.0.0_1740561492572_0.8056069688818206","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@aetosky/auth","version":"1.0.1","description":"A lightweight OAuth2 client library for JavaScript/TypeScript.","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","test":"jest"},"repository":{"type":"git","url":"https://git.eofactory.ai/aetos-x/aetos-v2/auth-js-library.git"},"keywords":["oauth2","authentication","typescript"],"author":{"name":"Aetosky"},"license":"MIT","publishConfig":{"access":"public"},"devDependencies":{"typescript":"^4.0.0","jest":"^27.0.0","ts-jest":"^27.0.0","@types/jest":"^27.0.0"},"_id":"@aetosky/auth@1.0.1","gitHead":"860150241e6542eca8aa380952bcea2825317c40","_nodeVersion":"20.16.0","_npmVersion":"10.8.1","dist":{"integrity":"sha512-fmrAo75vNQym0Evdm9xhlem4Q4qZN3jm9jnuFKHMXbh9ONe1+OLm3eAOVNRl409JJ7gp3AXTcdvSupducN3ugw==","shasum":"f7f2074a5c1c1045ceadeef94d62a572dd97f238","tarball":"https://registry.npmjs.org/@aetosky/auth/-/auth-1.0.1.tgz","fileCount":11,"unpackedSize":31464,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCYjZio/hJ5VG4Pb0izgVid8tr5V9inC/BZgqw01V4u7gIgJgPaSY8oc/0ojv35rezjipfFR5aLVYlMSydad2X8eD8="}]},"_npmUser":{"name":"thai.bui","email":"thai.bui@aetosky.com"},"directories":{},"maintainers":[{"name":"thai.bui","email":"thai.bui@aetosky.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/auth_1.0.1_1740561741971_0.45560284005172513"},"_hasShrinkwrap":false}},"time":{"created":"2025-02-26T09:18:12.455Z","modified":"2025-02-26T09:22:22.347Z","1.0.0":"2025-02-26T09:18:12.840Z","1.0.1":"2025-02-26T09:22:22.160Z"},"author":{"name":"Aetosky"},"license":"MIT","keywords":["oauth2","authentication","typescript"],"repository":{"type":"git","url":"https://git.eofactory.ai/aetos-x/aetos-v2/auth-js-library.git"},"description":"A lightweight OAuth2 client library for JavaScript/TypeScript.","maintainers":[{"name":"thai.bui","email":"thai.bui@aetosky.com"}],"readme":"```markdown\n# @aetosky/auth\n\nA lightweight OAuth2 client library for JavaScript and TypeScript, designed for seamless integration with Aetosky’s authentication flow. It handles login redirection, token exchange, automatic token refresh, and secure API requests.\n\n## Features\n\n- **OAuth2 Flow:** Manages login, callback handling, and token exchange.\n- **Token Management:** Stores access and refresh tokens, and refreshes tokens automatically before expiration.\n- **Secure Requests:** Automatically attaches a valid access token to API requests.\n- **Easy Logout:** Clears stored tokens and redirects users to the login page.\n- **Singleton Pattern:** Ensures a single instance of the Auth class is used throughout your application.\n- **TypeScript Ready:** Fully typed for TypeScript, with full JavaScript compatibility.\n- **Custom Error Handling:** Uses a custom `AuthError` class to provide meaningful error messages.\n\n## Installation\n\n### Using npm\n\n```bash\nnpm install @aetosky/auth\n```\n\n### Using yarn\n\n```bash\nyarn add @aetosky/auth\n```\n\n## Quick Start\n\nIn your application, simply initialize the Auth instance and check for an active session. If the user isn’t logged in, the library will attempt to exchange an OAuth2 code for tokens or redirect to the login page if needed.\n\n### Example\n\n```javascript\nimport Auth from '@aetosky/auth';\nimport config from './config';\n\n(async () => {\n  // Initialize the singleton Auth instance with your backend URL and redirect URI\n  const auth = Auth.getInstance({\n    baseURL: config.backendUrl,\n    redirectUri: window.location.origin\n  });\n\n  // Check if the user is logged in. If not, attempt to handle the OAuth2 callback.\n  let logged = await auth.isLogged();\n  if (!logged) {\n    logged = await auth.exchangeCodeForToken();\n  }\n\n  // If still not logged in, redirect to the login page.\n  if (!logged) {\n    await auth.redirectToLogin();\n  }\n\n  // Retrieve and use the authenticated user's information.\n  const user = await auth.getUser();\n  console.log('User:', user);\n})();\n```\n\n## Usage Details\n\n### Initialization\n\nCreate an instance of the Auth class by providing your backend URL and a redirect URI:\n\n```javascript\nimport Auth from '@aetosky/auth';\n\nconst auth = new Auth({\n  baseURL: 'https://app.aetosky.com',      // Your API base URL\n  redirectUri: window.location.origin       // URL to redirect after login\n});\n```\n\nAlternatively, use the singleton accessor:\n\n```javascript\nconst auth = Auth.getInstance({\n  baseURL: 'https://app.aetosky.com',\n  redirectUri: window.location.origin\n});\n```\n\n### OAuth2 Callback Handling\n\nAfter the user logs in, the authentication server redirects back with an authorization code. Use `handleAuthCallback()` (or `exchangeCodeForToken()`) to exchange the code for tokens and clean up the URL:\n\n```javascript\nawait auth.handleAuthCallback();\n// or\nawait auth.exchangeCodeForToken();\n```\n\n### Getting a Valid Access Token\n\nRetrieve the current access token. The library will refresh the token automatically if it is expired or about to expire:\n\n```javascript\nconst token = await auth.getToken();\nconsole.log('Access token:', token);\n```\n\n### Get current user information\n\nYou can also get the current user information:\n\n```javascript\nconst user = await auth.getUser();\nconsole.log('User data:', user);\n```\n\n### Logging Out\n\nClear tokens and redirect to the login page using the `logout()` method:\n\n```javascript\nawait auth.logout();\n```\n\n## API Overview\n\n- **`getToken(): Promise<string | null>`**  \n  Returns a valid access token (refreshing it if necessary).\n\n- **`request(endpoint: string, options?: RequestInit): Promise<any>`**  \n  Makes an authenticated API request, attaching the access token to the request header.\n\n- **`getUser(): Promise<any>`**  \n  Retrieves user information via the `/api/auth/me` endpoint.\n\n- **`logout(): Promise<void>`**  \n  Logs out the user, clearing stored tokens and redirecting to login.\n\n- **`redirectToLogin(): Promise<void>`**  \n  Redirects the user to the login page.\n\n- **`exchangeCodeForToken(): Promise<boolean>`**  \n  Exchanges an OAuth2 code from the URL for access and refresh tokens, then cleans the URL.\n\n- **`clearTokens(): void`**  \n  Removes all token-related data from localStorage.\n\n## Error Handling\n\nThe library throws an `AuthError` for any authentication-related issues. Use try-catch blocks to handle these errors gracefully:\n\n```javascript\ntry {\n  const user = await auth.getUser();\n} catch (error) {\n  if (error instanceof AuthError) {\n    console.error('Authentication error:', error.message);\n  }\n}\n```\n\n### AuthError Class\n\n```javascript\nclass AuthError extends Error {\n  constructor(message, statusCode) {\n    super(message);\n    this.name = \"AuthError\";\n    this.statusCode = statusCode;\n  }\n}\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n```","readmeFilename":"README.md"}