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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"dependencies": {
"crypto-js": "^4.1.1",
"nostr-tools": "1.13.1"
"events": "^3.3.0"
},
"devDependencies": {
"@types/crypto-js": "^4.1.1",
Expand Down
12 changes: 10 additions & 2 deletions 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 Down Expand Up @@ -39,13 +40,17 @@ 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;
}


on(eventName: string, listener: (tokens: Token) => void) {
pavanjoshi914 marked this conversation as resolved.
Show resolved Hide resolved
pavanjoshi914 marked this conversation as resolved.
Show resolved Hide resolved
return this._tokenEvents.on(eventName, listener);
}
/**
* Refresh the access token
*/
Expand Down Expand Up @@ -177,7 +182,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