@cactive/id
Version:
Interaction with the ID system.
91 lines (90 loc) • 3.18 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const phin_1 = __importDefault(require("phin"));
class Connections {
_token;
_options;
constructor(token, options = {}) {
this._token = token;
this._options = {
base_url: options.base_url ?? 'https://cactive.id/api/v2/',
verbose: options.verbose ?? false,
};
}
$(endpoint, method, data) {
if (this._options.verbose)
console.log(`[📡] :: ${method} @ ${this._options.base_url + endpoint}`);
return new Promise((resolve, reject) => {
(0, phin_1.default)({
method,
url: this._options.base_url + endpoint,
data: data ?? '',
headers: {
'Content-Type': 'application/json',
Authorization: `${this._token}`,
},
}).then(res => {
const ok = !res.statusCode ? false : res.statusCode >= 200 && res.statusCode < 300;
if (ok) {
try {
resolve(JSON.parse(res.body.toString()));
}
catch (e) {
reject(e);
}
}
else if (res.statusCode === 400)
reject(res.statusMessage);
else
reject(`Server Error: ${res.statusMessage || res.statusCode || 'Unknown'}`);
});
});
}
/**
* Fetches a refresh token based on Identification token from an OAuth gateway
* @param identifier_token Identifier token provided by the oauth gateway
* @param client_id Project Client Id
* @param client_secret Project Client Secret
* @param redirect_uri Used Redirect URI
* @param scopes Used Scopes
* @returns Refresh token
*/
oauthIdentify(identifier_token, client_id, client_secret, redirect_uri, scopes) {
return this.$(`oauth/identify`, 'POST', {
client_id,
redirect_uri,
scopes,
token: identifier_token,
client_secret
});
}
/**
* Creates an Access Token from a Refresh Token
* @param refresh_token Refresh token
* @returns Access token
*/
async refreshToken(refresh_token) {
return (await this.$(`oauth/refresh`, 'POST', { token: refresh_token })).refresh;
}
/**
* Fetches a user by an Access Token
* @param access_token Access token
* @returns User
*/
getUserByAccessToken(access_token) {
return this.$(`oauth/user`, 'POST', { token: access_token });
}
/**
* Fetches a User by their ID
* @param id User ID
* @returns User
*/
getUser(id) {
return this.$(`user/${encodeURIComponent(id)}`, 'GET');
}
}
module.exports = Connections;
exports.default = Connections;