coam-client
Version:
A thin client for COAM service
569 lines (563 loc) • 23.7 kB
JavaScript
"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var axios = require('axios');
var axiosRetry = require('axios-retry');
var _require = require('pope'),
pope = _require.pope;
var DEFAULT_BASE_URL = 'https://api.cimpress.io';
var CoamClient = /*#__PURE__*/function () {
function CoamClient(options) {
var _this = this;
_classCallCheck(this, CoamClient);
var opts = options || {};
this.baseUrl = opts.baseUrl || DEFAULT_BASE_URL;
this.timeout = Number.isInteger(opts.timeout) ? opts.timeout : 8000;
this.accessToken = opts.accessToken || undefined;
this.retryAttempts = Number.isInteger(opts.retryAttempts) ? opts.retryAttempts : 2;
this.retryDelayInMs = Number.isInteger(opts.retryDelayInMs) ? opts.retryDelayInMs : 200;
this.retryOnForbidden = 'retryOnForbidden' in opts ? opts.retryOnForbidden : true;
this.debugFunction = 'debugFunction' in opts ? opts.debugFunction : undefined;
this.errorFunction = 'errorFunction' in opts ? opts.errorFunction : console.error;
this.skipCache = 'skipCache' in opts ? opts.skipCache : false;
this.logPrefix = '[CoamClient]';
var validOptions = ['baseUrl', 'accessToken', 'timeout', 'retryAttempts', 'retryDelayInMs', 'retryOnForbidden', 'debugFunction', 'errorFunction', 'skipCache'];
Object.keys(opts).forEach(function (passedOption) {
if (validOptions.indexOf(passedOption) === -1) {
_this.__logError("".concat(_this.logPrefix, " Option '").concat(passedOption, "' is not understood and will be ignored."));
}
});
this.instance = axios.create({
baseURL: this.baseUrl,
timeout: this.timeout
});
this.instance.interceptors.response.use(function (response) {
return response;
}, function (error) {
var newError = error && error.response && {
data: error.response.data,
status: error.response.status,
headers: error.response.headers
} || error.message && {
message: error.message,
code: error.code,
stack: error.stack
} || error;
throw newError;
});
if (this.retryAttempts > 0) {
if (typeof axiosRetry !== 'function') {
axiosRetry = axiosRetry["default"];
}
axiosRetry(this.instance, {
retries: this.retryAttempts,
retryCondition: function retryCondition(error) {
if (axiosRetry.isNetworkOrIdempotentRequestError(error)) {
return true;
}
if (_this.retryOnForbidden && error && error.response && error.response.status === 403) {
return true;
}
// do not retry
return false;
},
retryDelay: function retryDelay() {
return _this.retryDelayInMs;
},
shouldResetTimeout: true
});
}
}
return _createClass(CoamClient, [{
key: "__exec",
value: function __exec(data) {
var _this2 = this;
if (this.skipCache && data.method === 'GET') {
data.params = Object.assign(data.params || {}, {
skipCache: Math.random()
});
}
return this.instance.request(data).then(function (response) {
return response.data;
})["catch"](function (err) {
_this2.__logError(err);
throw err;
});
}
}, {
key: "__config",
value: function __config(data) {
return Object.assign({}, {
headers: {
Authorization: "Bearer ".concat(this.accessToken)
}
}, data);
}
}, {
key: "__buildUrl",
value: function __buildUrl(urlPattern, dataToEncode) {
var encoded = {};
Object.keys(dataToEncode).forEach(function (k) {
return encoded[k] = encodeURIComponent(dataToEncode[k]);
});
return pope(urlPattern, encoded);
}
}, {
key: "__logDebug",
value: function __logDebug() {
if (this.debugFunction) {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
this.debugFunction.apply(null, args);
}
}
}, {
key: "__logError",
value: function __logError() {
if (this.errorFunction) {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
this.errorFunction.apply(null, args);
}
}
}, {
key: "buildGroupUrlFromId",
value: function buildGroupUrlFromId(groupId) {
return "".concat(this.baseUrl, "/auth/access-management/v1/groups/").concat(groupId);
}
}, {
key: "hasPermission",
value: function hasPermission(principal, resourceType, resourceIdentifier, permission) {
var url = this.__buildUrl("/auth/access-management/v1/principals/{{principal}}/permissions/{{resourceType}}/{{resourceIdentifier}}/{{permission}}", {
principal: principal,
resourceType: resourceType,
resourceIdentifier: resourceIdentifier,
permission: permission
});
var data = this.__config({
url: url,
method: 'GET'
});
return this.__exec(data).then(function () {
return Promise.resolve(true);
})["catch"](function (e) {
// COAM returns a 404 if the principal does not have access to a resource
if (e.status === 404) {
return false;
}
// for all other errors, we want to throw an exception so that clients
// can retry instead of assuming the user does not have access
throw e;
});
}
}, {
key: "grantRoleToPrincipal",
value: function grantRoleToPrincipal(groupUrl, principal, roleName) {
var _this3 = this;
return this.getGroupInfo(groupUrl).then(function (groupInfo) {
if (!groupInfo) {
return Promise.reject(new Error('Failed to retrieve template COAM group.'));
}
return _this3.addGroupMember(groupInfo.id, principal, false).then(function () {
return _this3.modifyUserRoles(groupInfo.id, principal, {
'add': [roleName]
});
});
});
}
}, {
key: "getGroupInfo",
value: function getGroupInfo(groupUrl) {
var data = this.__config({
url: groupUrl,
method: 'GET',
params: {
canonicalize: 'true'
}
});
return this.__exec(data);
}
}, {
key: "setAdminFlag",
value: function setAdminFlag(groupId, principal, isAdmin) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/members/{{principal}}", {
groupId: groupId,
principal: principal
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
'is_admin': isAdmin
}
});
return this.__exec(data);
}
}, {
key: "removeUserRole",
value: function removeUserRole(groupId, principal, role) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/members/{{principal}}/roles", {
groupId: groupId,
principal: principal
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
'remove': [role]
}
});
return this.__exec(data);
}
}, {
key: "addUserRole",
value: function addUserRole(groupId, principal, role) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/members/{{principal}}/roles", {
groupId: groupId,
principal: principal
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
'add': [role]
}
});
return this.__exec(data);
}
}, {
key: "group56",
value: function group56(principal) {
var url = this.__buildUrl("/auth/access-management/v1/principals/{{principal}}/groups", {
principal: principal
});
var data = this.__config({
url: url,
method: 'GET'
});
return this.__exec(data).then(function (data) {
return !!data.groups.find(function (a) {
return a.id === '56';
});
});
}
}, {
key: "modifyUserRoles",
value: function modifyUserRoles(groupId, principal, rolesChanges) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/members/{{principal}}/roles", {
groupId: groupId,
principal: principal
});
var data = this.__config({
url: url,
method: 'PATCH',
data: rolesChanges
});
return this.__exec(data);
}
}, {
key: "addGroupMember",
value: function addGroupMember(groupId, principal, isAdmin) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/members", {
groupId: groupId,
principal: principal
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
'add': [{
is_admin: !!isAdmin,
principal: principal
}]
},
params: {
canonicalize: true
}
});
return this.__exec(data);
}
}, {
key: "removeGroupMember",
value: function removeGroupMember(groupId, principal) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/members", {
groupId: groupId
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
'remove': [principal]
}
});
return this.__exec(data);
}
}, {
key: "getRoles",
value: function getRoles() {
var data = this.__config({
url: "/auth/access-management/v1/roles",
method: 'GET'
});
return this.__exec(data);
}
}, {
key: "findPrincipals",
value: function findPrincipals(query) {
if (!query || query.length === 0) {
return Promise.resolve([]);
}
var data = this.__config({
url: '/auth/access-management/v1/search/canonicalPrincipals/bySubstring',
method: 'GET',
params: {
q: query,
canonicalize: true
}
});
// [{user_id / name / email}]
return this.__exec(data).then(function (p) {
return p.canonical_principals;
});
}
}, {
key: "getPrincipal",
value: function getPrincipal(principal) {
var url = this.__buildUrl("/auth/access-management/v1/principals/{{principal}}", {
principal: principal
});
var data = this.__config({
url: url,
method: 'GET'
});
return this.__exec(data);
}
}, {
key: "createGroup",
value: function createGroup(name, description) {
var data = this.__config({
url: '/auth/access-management/v1/groups',
method: 'POST',
data: {
name: name,
description: description
}
});
// [{user_id / name / email}]
return this.__exec(data);
}
}, {
key: "removeGroup",
value: function removeGroup(groupId) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}", {
groupId: groupId
});
var data = this.__config({
url: url,
method: 'DELETE'
});
return this.__exec(data);
}
}, {
key: "findGroups",
value: function findGroups(resourceType, resourceIdentifier, accountId, forAccountId, relationAccountId, isEssentialGroup, offset, limit, q) {
var data = this.__config({
url: "/auth/access-management/v1/groups",
method: 'GET',
params: {
resource_type: resourceType,
resource_identifier: resourceIdentifier,
account_id: accountId,
for_account_id: forAccountId,
relation_account_id: relationAccountId,
is_essential_group: isEssentialGroup,
offset: offset,
limit: limit,
q: q
}
});
return this.__exec(data);
}
}, {
key: "removeResourceFromGroup",
value: function removeResourceFromGroup(groupId, resourceType, resourceId) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/resources", {
groupId: groupId
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
add: [],
remove: [{
resource_type: resourceType,
resource_identifier: resourceId
}]
}
});
return this.__exec(data);
}
}, {
key: "addResourceToGroup",
value: function addResourceToGroup(groupId, resourceType, resourceId) {
var url = this.__buildUrl("/auth/access-management/v1/groups/{{groupId}}/resources", {
groupId: groupId
});
var data = this.__config({
url: url,
method: 'PATCH',
data: {
add: [{
resource_type: resourceType,
resource_identifier: resourceId
}],
remove: []
}
});
return this.__exec(data);
}
}, {
key: "getUserPermissionsForResourceType",
value: function getUserPermissionsForResourceType(principal, resourceType) {
var include = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var permissionFilters = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var urlString = "/auth/access-management/v1/principals/{{principal}}/permissions/{{resourceType}}?include=".concat(include).concat(permissionFilters ? "&permissionFilter=".concat(permissionFilters.join(',')) : '');
var url = this.__buildUrl(urlString, {
principal: principal,
resourceType: resourceType
});
var data = this.__config({
url: url,
method: 'GET'
});
return this.__exec(data);
}
}, {
key: "getUserPermissionsForResourceTypes",
value: function getUserPermissionsForResourceTypes(principal, resourceTypes) {
var include = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var permissionFilters = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var urlString = "/auth/access-management/v1/principals/{{principal}}/permissions?resourceTypes=".concat(resourceTypes.join(','), "&include=").concat(include).concat(permissionFilters ? "&permissionFilter=".concat(permissionFilters.join(',')) : '');
var url = this.__buildUrl(urlString, {
principal: principal
});
var data = this.__config({
url: url,
method: 'GET'
});
return this.__exec(data);
}
}, {
key: "getUsersWithPermission",
value: function getUsersWithPermission(resourceType, resourceIdentifier, permission) {
var url = this.__buildUrl("/auth/access-management/v1/search/canonicalPrincipals/byPermission?resource_type={{resourceType}}".concat(resourceIdentifier ? '&resource_identifier={{resourceIdentifier}}' : '', "&permission={{permission}}"), {
resourceType: resourceType,
resourceIdentifier: resourceIdentifier,
permission: permission
});
var data = this.__config({
url: url,
method: 'GET'
});
// [{user_id / name / email}]
return this.__exec(data).then(function (p) {
return p.canonical_principals;
});
}
}, {
key: "getUsersWithResource",
value: function getUsersWithResource(resourceType, permissionFilters) {
var url = this.__buildUrl("/auth/access-management/v1/search/canonicalPrincipals/byResource?resource_type={{resourceType}}".concat(permissionFilters && permissionFilters.length > 0 ? '&permissionFilter={{commaSeparatedPermissionFilter}}' : ''), {
resourceType: resourceType,
commaSeparatedPermissionFilter: permissionFilters && permissionFilters.length > 0 && permissionFilters.join(',')
});
var data = this.__config({
url: url,
method: 'GET'
});
// [{canonical_principal / resource_type / is_client / permissions}]
return this.__exec(data);
}
}, {
key: "createGroupWithUser",
value: function () {
var _createGroupWithUser = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(principalToCreateGroup, principalToAddToGroup, groupName, groupDescription, rolesToAdd, resourcesToAdd) {
var res, groupId, i, _i, resource, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.n = 1;
return this.createGroup(groupName, groupDescription);
case 1:
res = _context.v;
groupId = res.id;
_context.n = 2;
return this.addGroupMember(groupId, principalToAddToGroup);
case 2:
_context.n = 3;
return this.setAdminFlag(groupId, principalToAddToGroup, true);
case 3:
i = 0;
case 4:
if (!(i < rolesToAdd.length)) {
_context.n = 6;
break;
}
_context.n = 5;
return this.addUserRole(groupId, principalToAddToGroup, rolesToAdd[i]);
case 5:
i++;
_context.n = 4;
break;
case 6:
_i = 0;
case 7:
if (!(_i < resourcesToAdd.length)) {
_context.n = 9;
break;
}
resource = resourcesToAdd[_i];
_context.n = 8;
return this.addResourceToGroup(groupId, resource.resourceType, resource.resourceId);
case 8:
_i++;
_context.n = 7;
break;
case 9:
_context.p = 9;
_context.n = 10;
return this.removeGroupMember(groupId, principalToCreateGroup);
case 10:
_context.n = 12;
break;
case 11:
_context.p = 11;
_t = _context.v;
if (!(_t.status !== 404)) {
_context.n = 12;
break;
}
throw _t;
case 12:
return _context.a(2, groupId);
}
}, _callee, this, [[9, 11]]);
}));
function createGroupWithUser(_x, _x2, _x3, _x4, _x5, _x6) {
return _createGroupWithUser.apply(this, arguments);
}
return createGroupWithUser;
}()
}]);
}();
module.exports = CoamClient;