From 7e4d603481b98e720713a3f17c6215b903630bf0 Mon Sep 17 00:00:00 2001 From: Cesare Naldi Date: Fri, 7 Jun 2024 09:33:19 +0200 Subject: [PATCH] feat: adds client.authentication.getRefreshToken() method --- .changeset/yellow-turkeys-appear.md | 5 ++++ .../src/authentication/Authentication.ts | 25 +++++++++++++++++++ .../src/authentication/IAuthentication.ts | 11 ++++++-- 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 .changeset/yellow-turkeys-appear.md diff --git a/.changeset/yellow-turkeys-appear.md b/.changeset/yellow-turkeys-appear.md new file mode 100644 index 000000000..630f166b7 --- /dev/null +++ b/.changeset/yellow-turkeys-appear.md @@ -0,0 +1,5 @@ +--- +"@lens-protocol/client": patch +--- + +**feat:** adds `client.authentication.getRefreshToken()` method. diff --git a/packages/client/src/authentication/Authentication.ts b/packages/client/src/authentication/Authentication.ts index 5595cc563..aac876382 100644 --- a/packages/client/src/authentication/Authentication.ts +++ b/packages/client/src/authentication/Authentication.ts @@ -112,6 +112,31 @@ export class Authentication implements IAuthentication { return failure(new CredentialsExpiredError()); } + async getRefreshToken(): PromiseResult { + const credentials = await this.credentials.get(); + + if (!credentials) { + return failure(new NotAuthenticatedError()); + } + + if (!credentials.shouldRefresh()) { + return success(credentials.refreshToken); + } + + if (credentials.canRefresh()) { + const newCredentials = await this.api.refresh(credentials.refreshToken); + await this.credentials.set(newCredentials); + + if (!newCredentials.refreshToken) { + return failure(new CredentialsExpiredError()); + } + + return success(newCredentials.refreshToken); + } + + return failure(new CredentialsExpiredError()); + } + async getIdentityToken(): PromiseResult { const credentials = await this.credentials.get(); diff --git a/packages/client/src/authentication/IAuthentication.ts b/packages/client/src/authentication/IAuthentication.ts index c171d18b6..85767cc64 100644 --- a/packages/client/src/authentication/IAuthentication.ts +++ b/packages/client/src/authentication/IAuthentication.ts @@ -81,14 +81,21 @@ export interface IAuthentication { isAuthenticated(): Promise; /** - * Get the access token. If it expired, try to refresh it. + * Get the access token. * * @returns A Result with the access token or possible error scenarios */ getAccessToken(): PromiseResult; /** - * Get the identity token. If it expired, try to refresh it. + * Get the refresh token. + * + * @returns A Result with the refresh token or possible error scenarios + */ + getRefreshToken(): PromiseResult; + + /** + * Get the identity token. * * @returns A Result with the identity token or possible error scenarios */