Skip to content
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

token changed callback #42

Merged
merged 10 commits into from
Aug 18, 2023
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,28 @@ const client = new Client(authClient);
const result = await client.createInvoice({amount: 1000});
```

#### Handling refresh token
Access tokens do expire. If an access token is about to expire, this library will automatically use a refresh token to retrieve a fresh one. Utilising the tokens event is a simple approach to guarantee that you always save the most recent tokens:
pavanjoshi914 marked this conversation as resolved.
Show resolved Hide resolved

```js
const token = loadTokenForUser(); // {access_token: string, refresh_token: string, expires_at: number}
const authClient = new auth.OAuth2User({
client_id: process.env.CLIENT_ID,
callback: "http://localhost:8080/callback",
scopes: ["invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send"],
token: token
});

// listen to the tokens event
authClient.on('tokens', (tokens) => {
if (tokens.refresh_token) {
pavanjoshi914 marked this conversation as resolved.
Show resolved Hide resolved
// store the tokens in database
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
```

#### Sending payments

```js
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
},
"dependencies": {
"crypto-js": "^4.1.1",
"nostr-tools": "1.13.1"
"nostr-tools": "1.13.1",
"events": "^3.3.0"
},
"devDependencies": {
"@types/crypto-js": "^4.1.1",
Expand Down
16 changes: 15 additions & 1 deletion src/OAuth2User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import CryptoJS from 'crypto-js';
import { buildQueryString, basicAuthHeader } from "./utils";
import { OAuthClient, AuthHeader, GetTokenResponse, Token, GenerateAuthUrlOptions } from "./types";
import { RequestOptions, rest } from "./request";
import EventEmitter from 'events';

const AUTHORIZE_URL = "https://getalby.com/oauth";

Expand All @@ -23,6 +24,8 @@ export interface OAuth2UserOptions {
token?: Token;
}

export type EventName= "tokens";

function processTokenResponse(token: GetTokenResponse): Token {
const { expires_in, ...rest } = token;
return {
Expand All @@ -39,13 +42,21 @@ export class OAuth2User implements OAuthClient {
code_verifier?: string;
code_challenge?: string;
private _refreshAccessTokenPromise: Promise<{token: Token}> | null;
private _tokenEvents = new EventEmitter();
pavanjoshi914 marked this conversation as resolved.
Show resolved Hide resolved
constructor(options: OAuth2UserOptions) {
const { token, ...defaultOptions } = options;
this.options = {client_secret: '', ...defaultOptions};
this.token = token;
this._refreshAccessTokenPromise = null;
}

/**
* Subscribe to the events
*/
async on(eventName: EventName, listener: (tokens: Token) => void): Promise<void> {
this._tokenEvents.on(eventName, listener);
}

/**
* Refresh the access token
*/
Expand Down Expand Up @@ -177,7 +188,10 @@ export class OAuth2User implements OAuthClient {

async getAuthHeader(): Promise<AuthHeader> {
if (!this.token?.access_token) throw new Error("access_token is required");
if (this.isAccessTokenExpired()) await this.refreshAccessToken();
if (this.isAccessTokenExpired()){
await this.refreshAccessToken()
this._tokenEvents.emit("tokens", this.token);
};
return {
Authorization: `Bearer ${this.token.access_token}`,
};
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3090,7 +3090,7 @@ eventemitter3@^4.0.4:
resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f"
integrity sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==

events@^3.0.0:
events@^3.0.0, events@^3.3.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"
integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==
Expand Down