modern-pep
Version:
Modern policy enforcement point authorizer
134 lines (122 loc) • 3.25 kB
JavaScript
const axios = require("axios");
const yaml = require("js-yaml");
const fs = require("fs");
const path = require("path");
const { v4: uuidv4 } = require("uuid");
class Authorizer {
constructor(atomsList, baseURL) {
this.authorization_atoms = atomsList;
this.baseURL = baseURL;
}
getAtom(id) {
const atom = this.authorization_atoms.find((at) => at.id === id);
if (atom) {
return atom;
}
throw new Error("authorization atom not found");
}
getAtomIDClone(id) {
const atom = this.authorization_atoms.find((at) => at.id === id);
if (atom) {
return atom;
}
return {
id: id,
description: "",
predicate: "",
tags: [],
};
}
async authorizeAtoms(body, authToken, url, callback) {
if (body) {
const headers = {
Authorization: `Bearer ${authToken}`,
'dataos-correlation-id': uuidv4(),
};
return await axios
.post(url, body, {
headers,
})
.then((res) => {
if (res.data) {
if (!callback) {
return res.data;
}
callback(res.data);
}
})
.catch((error) => {
if (error.response != null) {
const { status, statusText } = error.response;
if (status === 401 || status === 403 || status === 400) {
if (!callback) {
return { error: { status, statusText } };
}
callback({ error: { status, statusText } });
}
}
});
}
}
async authorize(id, authToken, collection = null, callback) {
let url = `${this.baseURL}/api/v1/authorize`;
if (id) {
try {
let atom = this.getAtom(id);
if (atom) {
const { predicate, tags, paths } = atom;
let context = {
predicate,
object: {
tags,
paths,
},
};
if (collection) {
context['collection'] = collection;
}
const body = {
token: authToken,
context: context,
};
return await this.authorizeAtoms(body, authToken, url, callback);
}
} catch (e) {
console.log(e);
}
}
}
async authorizeBatch(ids, authToken, collection = null, callback) {
let url = `${this.baseURL}/api/v1/authorize/batch`;
if (ids && ids.length > 0) {
let contexts = {};
try {
ids.forEach((id, index) => {
let atom = this.getAtomIDClone(id);
if (atom) {
const { predicate, tags, paths } = atom;
let context = {
predicate,
object: {
tags,
paths,
},
};
if (collection) {
context['collection'] = collection;
}
contexts = { ...contexts, [id]: context };
}
});
const body = {
token: authToken,
contexts: contexts,
};
return await this.authorizeAtoms(body, authToken, url, callback);
} catch (e) {
console.log(e);
}
}
}
}
module.exports = { Authorizer };