@fajarnugraha37/nope-iam
Version:
A highly extensible, type-safe IAM-like access control library for Node.js, inspired by AWS IAM. Deny by default, allow by vibes and less patience for your bad access patterns. Supports policies, roles, decorators, adapters, and rich evaluation context be
106 lines • 3.13 kB
JavaScript
import { promises as fs } from 'fs';
export class JSONFileAdapter {
filePath;
data = { users: [], roles: [], policies: [] };
loaded = false;
constructor(options) {
this.filePath = options.filePath;
}
async load() {
if (this.loaded)
return;
try {
const raw = await fs.readFile(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
}
catch {
this.data = { users: [], roles: [], policies: [] };
}
this.loaded = true;
}
async save() {
await fs.writeFile(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
}
async getUser(id) {
await this.load();
return this.data.users.find(u => u.id === id);
}
async getUsers(ids) {
await this.load();
return this.data.users.filter(u => ids.includes(u.id));
}
async *getAllUsers() {
await this.load();
for (const user of this.data.users)
yield user;
}
async getRole(id) {
await this.load();
return this.data.roles.find(r => r.id === id);
}
async getRoles(ids) {
await this.load();
return this.data.roles.filter(r => ids.includes(r.id));
}
async *getAllRoles() {
await this.load();
for (const role of this.data.roles)
yield role;
}
async getPolicy(id) {
await this.load();
return this.data.policies.find(p => p.id === id);
}
async getPolicies(ids) {
await this.load();
return this.data.policies.filter(p => ids.includes(p.id));
}
async *getAllPolicies() {
await this.load();
for (const policy of this.data.policies)
yield policy;
}
async saveUser(user) {
await this.load();
const idx = this.data.users.findIndex(u => u.id === user.id);
if (idx >= 0)
this.data.users[idx] = user;
else
this.data.users.push(user);
await this.save();
}
async saveRole(role) {
await this.load();
const idx = this.data.roles.findIndex(r => r.id === role.id);
if (idx >= 0)
this.data.roles[idx] = role;
else
this.data.roles.push(role);
await this.save();
}
async savePolicy(policy) {
await this.load();
const idx = this.data.policies.findIndex(p => p.id === policy.id);
if (idx >= 0)
this.data.policies[idx] = policy;
else
this.data.policies.push(policy);
await this.save();
}
async deleteUser(id) {
await this.load();
this.data.users = this.data.users.filter(u => u.id !== id);
await this.save();
}
async deleteRole(id) {
await this.load();
this.data.roles = this.data.roles.filter(r => r.id !== id);
await this.save();
}
async deletePolicy(id) {
await this.load();
this.data.policies = this.data.policies.filter(p => p.id !== id);
await this.save();
}
}
//# sourceMappingURL=jsonFileAdapter.js.map