@design-sdk/figma-oauth
Version:
OAuth management for figma
76 lines (75 loc) • 2.86 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuthState = exports.OAuth = void 0;
const request_1 = require("./request");
const urls_1 = require("./urls");
const configure_1 = require("./configure");
class OAuth {
static new({ state, redirect_uri, }) {
const oauth = new OAuthState({ state, redirect_uri });
this._authprocs.set(oauth.state, oauth);
return oauth;
}
static get(state) {
return this._authprocs.get(state);
}
static resolve(state) {
this._authprocs.delete(state);
}
}
exports.OAuth = OAuth;
OAuth._authprocs = new Map();
class OAuthState {
constructor({ state = _stateid(), redirect_uri = (0, configure_1.__cfg_get_redirect_uri)(), }) {
this.state = state;
this._app_id = (0, configure_1.__cfg_get_client_id)();
this._app_secret = (0, configure_1.__cfg_get_client_secret)();
if (!redirect_uri) {
throw "redirect_uri must be provided by configuration. use `.env` or `configure()`.";
}
this.redirect_uri = redirect_uri;
}
get stage() {
return this._stage;
}
get authUrl() {
return urls_1.urls.oauth_browser_url({
client_id: this._app_id,
redirect_uri: this.redirect_uri,
state: this.state,
});
}
authenticate({ code }) {
return __awaiter(this, void 0, void 0, function* () {
return yield request_1.request.authentication({
client_id: this._app_id,
client_secret: this._app_secret,
grant_type: "authorization_code",
redirect_uri: this.redirect_uri,
code: code,
});
});
}
resolve() {
try {
OAuth.resolve(this.state);
}
catch (_) {
throw new Error("Unable to resolve OAuth state: This OAuthState was not initialized by `OAuth.new()`");
}
}
}
exports.OAuthState = OAuthState;
function _stateid() {
// random string gen - ref: https://stackoverflow.com/a/8084248/5463235
return Math.random().toString(36).substring(7);
}