2017-10-18 13:31:08 -04:00
|
|
|
var express = require('express');
|
|
|
|
var router = express.Router();
|
|
|
|
var crypto = require('crypto');
|
|
|
|
|
2018-08-01 11:54:35 -04:00
|
|
|
var User = require('../../models/User.js');
|
|
|
|
var Key = require('../../models/Key.js');
|
2017-10-18 13:31:08 -04:00
|
|
|
|
2018-01-15 11:48:36 -05:00
|
|
|
var requireScope = function (perm) {
|
|
|
|
return function(req, res, next) {
|
|
|
|
User.findOne({username: req.session.passport.user}, function(err, user) {
|
|
|
|
if (err) throw err;
|
|
|
|
if (user.scope.indexOf(perm) === -1)
|
|
|
|
res.status(400).json({'message': 'No permission.'});
|
|
|
|
else
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
router.post('/create', requireScope('api.create'), function (req, res) {
|
2017-10-18 13:31:08 -04:00
|
|
|
if (!req.body.identifier || !req.body.scope) {
|
|
|
|
res.status(400).json({'message': 'Bad request.'});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
Key.count({'username': req.session.passport.user}, function (err, count) {
|
|
|
|
if (count >= 10) {
|
|
|
|
res.status(403).json({'message': 'Key limit reached.'});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var scope;
|
|
|
|
try {
|
|
|
|
scope = JSON.parse(req.body.scope);
|
|
|
|
} catch (e) {
|
2018-01-14 09:23:51 -05:00
|
|
|
res.status(500).json({'message': e.name + ': ' + e.message});
|
2017-10-18 13:31:08 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var id = req.sanitize(req.body.identifier);
|
|
|
|
if (id.length === 0) id = "err";
|
|
|
|
|
|
|
|
var entry = {
|
|
|
|
key: crypto.randomBytes(32).toString('hex'),
|
|
|
|
identifier: id,
|
|
|
|
scope: scope,
|
|
|
|
username: req.session.passport.user,
|
|
|
|
date: Date.now()
|
|
|
|
};
|
|
|
|
|
|
|
|
Key.create(entry, function (err) {
|
|
|
|
if (err) {
|
|
|
|
throw err;
|
|
|
|
} else {
|
|
|
|
res.status(200).json({
|
|
|
|
key: entry.key,
|
|
|
|
identifier: entry.identifier,
|
|
|
|
scope: entry.scope
|
|
|
|
});
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
|
|
|
router.get('/get', function (req, res, next) {
|
|
|
|
var query = {username: req.session.passport.user};
|
|
|
|
|
|
|
|
if (req.body.identifier)
|
|
|
|
query.identifier = req.body.identifier;
|
|
|
|
|
|
|
|
Key.find(query, function (err, keys) {
|
|
|
|
if (err) {
|
|
|
|
next(err);
|
|
|
|
} else {
|
|
|
|
res.status(200).json(keys);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
2018-01-15 11:48:36 -05:00
|
|
|
router.post('/delete', requireScope('api.delete'), function(req, res, next) {
|
2017-10-21 17:47:55 -04:00
|
|
|
Key.deleteOne({key: req.body.key}, function(err) {
|
|
|
|
if (err) next(err);
|
|
|
|
else res.status(200).json({'message': 'Successfully deleted.'});
|
|
|
|
});
|
2017-10-21 15:10:24 -04:00
|
|
|
});
|
|
|
|
|
2017-10-18 13:31:08 -04:00
|
|
|
module.exports = router;
|