diff --git a/packages/backend/src/apps/spotify/auth/index.ts b/packages/backend/src/apps/spotify/auth/index.ts index e1a93927..289e4a72 100644 --- a/packages/backend/src/apps/spotify/auth/index.ts +++ b/packages/backend/src/apps/spotify/auth/index.ts @@ -1,6 +1,7 @@ import generateAuthUrl from './generate-auth-url'; import verifyCredentials from './verify-credentials'; import isStillVerified from './is-still-verified'; +import refreshToken from './refresh-token'; export default { fields: [ @@ -39,6 +40,7 @@ export default { clickToCopy: false, }, ], + refreshToken, generateAuthUrl, verifyCredentials, isStillVerified, diff --git a/packages/backend/src/apps/spotify/auth/refresh-token.ts b/packages/backend/src/apps/spotify/auth/refresh-token.ts new file mode 100644 index 00000000..11824599 --- /dev/null +++ b/packages/backend/src/apps/spotify/auth/refresh-token.ts @@ -0,0 +1,30 @@ +import { IGlobalVariable } from '@automatisch/types'; +import qs from 'qs'; + +const refreshToken = async ($: IGlobalVariable) => { + const stringifiedBody = qs.stringify({ + refresh_token: $.auth.data.refreshToken as string, + grant_type: 'refresh_token', + }); + + const headers = { + Authorization: `Basic ${Buffer.from( + $.auth.data.clientId + ':' + $.auth.data.clientSecret + ).toString('base64')}`, + 'Content-Type': 'application/x-www-form-urlencoded', + }; + + const response = await $.http.post( + 'https://accounts.spotify.com/api/token', + stringifiedBody, + { headers } + ); + + await $.auth.set({ + accessToken: response.data.access_token, + expiresIn: response.data.expires_in, + tokenType: response.data.token_type, + }); +}; + +export default refreshToken;