lunify.js
Version:
A basic api wrapper for the spotify api covering the oauth routes.
91 lines • 2.92 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserOauth = void 0;
const __1 = require("../..");
class UserOauth {
client;
accessToken;
refreshToken;
tokenType;
scope;
expiresIn;
expiresTimestamp;
createdTimestamp;
revoked;
constructor(client,
// omiting "public user" due to "<OauthManager>.refreshToken(...)"
data) {
this.client = client;
this.refreshToken = null;
if ("refresh_token" in data)
this.refreshToken = data.refresh_token;
this.accessToken = data.access_token;
this.tokenType = data.token_type;
this.scope = this.convertScopesToStringArray(data.scope);
this.expiresIn = data.expires_in * 1_000;
this.expiresTimestamp = data.created_timestamp + data.expires_in * 1_000;
this.createdTimestamp = data.created_timestamp;
this.revoked = false;
}
convertScopesToStringArray(scopesString) {
const scopesArray = scopesString.split(" ");
const enumValues = Object.values(__1.Scopes);
return scopesArray
.filter((scope) => enumValues.includes(scope));
}
/**
* Refresh a spotify access token
* @param {string} refreshToken - oauth refresh token
* @example ```ts
* await access.refresh();
* ```
* Or if you want to use a specific refresh token, like from a database
* @example ```ts
* const refreshToken = ...; // from the database for example
* await access.refresh(refreshToken);
* ```
*/
async refresh(refreshToken) {
if (refreshToken)
this.refreshToken = refreshToken;
if (this.revoked)
throw new Error(__1.LunifyErrors.TokenRevoked);
if (!this.refreshToken)
throw new Error(__1.LunifyErrors.NoRefreshToken);
const res = await this.client.oauth.refreshToken(this.refreshToken);
if (!res) {
this.revoked = true;
throw new Error(__1.LunifyErrors.TokenRevoked);
}
this.accessToken = res.accessToken;
return res.accessToken;
}
/**
* Generates a authorization token header
*/
async getAuthorization() {
if (this.expiresTimestamp < Date.now()) {
await this.refresh();
}
return this.tokenType + " " + this.accessToken;
}
/**
* Check if the access token is still valid (expires after 1 hour of creating, usually)
*/
isValid() {
if (this.expiresTimestamp < Date.now())
return false;
return true;
}
/**
* Fetch the user accociated with this access token
* @example ```ts
* const user = await access.fetchUser();
* ```
*/
async fetchUser() {
return await this.client.users.fetch(this);
}
}
exports.UserOauth = UserOauth;
//# sourceMappingURL=Oauth.js.map