-
Notifications
You must be signed in to change notification settings - Fork 0
/
permissions-db.js
47 lines (42 loc) · 1.25 KB
/
permissions-db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
var Pool = require('pg').Pool;
var lib = require('http-helper-functions');
var config = {
host: process.env.PG_HOST || 'localhost',
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE
};
var pool = new Pool(config);
function withPermissionsDo(req, res, subject, callback) {
// fetch the permissions resource for `subject`.
subject = lib.internalizeURL(subject, req.headers.host);
var query = 'SELECT etag, data FROM permissions WHERE subject = $1';
pool.query(query,[subject], function (err, pgResult) {
if (err) {
lib.internalError(res, err);
} else {
if (pgResult.rowCount === 0) {
lib.notFound(req, res);
}
else {
var row = pgResult.rows[0];
callback(row.data, row.etag);
}
}
});
}
function init(callback) {
var query = 'CREATE TABLE IF NOT EXISTS permissions (subject text primary key, etag serial, data jsonb);'
pool.query(query, function(err, pgResult) {
if(err) {
console.error('error creating permissions table', err);
} else {
console.log(`connected to PG at ${config.host}`);
callback();
}
});
}
exports.withPermissionsDo = withPermissionsDo;
exports.init = init;
exports.pool = pool;