1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-11-15 17:18:05 -05:00
shimapan/app/routes/api/keys.js

80 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-08-01 18:57:45 -04:00
const express = require('express');
const router = express.Router();
const config = require('config');
const crypto = require('crypto');
const ModelPath = '../../models/';
const Key = require(ModelPath + 'Key.js');
const verifyBody = require('../../util/verifyBody');
2018-08-01 18:57:45 -04:00
const verifyScope = require('../../util/verifyScope');
const requireAuth = require('../../util/auth').requireAuth;
const createParams = [
{name: 'identifier', type: 'string', sanitize: true},
{name: 'scope', instance: Array}];
2019-01-02 14:25:51 -05:00
router.post('/create', requireAuth('key.create'), verifyBody(createParams), async (req, res) => {
2018-08-13 06:13:47 -04:00
const keyCount = await Key.countDocuments({issuer: req.username});
2018-08-01 18:57:45 -04:00
if (keyCount >= config.get('Key.limit'))
return res.status(403).json({message: 'Key limit reached.'});
const scope = req.body.scope;
if (!scope.every(scope => verifyScope(req.scope, scope)))
return res.status(403).json({message: 'Requested scope exceeds own scope.'});
const key = {
key: await crypto.randomBytes(32).toString('hex'),
identifier: req.body.identifier,
scope: scope,
issuer: req.username,
date: Date.now()
};
await Key.create(key);
res.status(200).json({
message: 'Key created.',
key: key.key
});
2019-01-02 14:25:51 -05:00
});
2018-08-01 18:57:45 -04:00
const getProps = [
{name: 'identifier', type: 'string', optional: true},
{name: 'issuer', type: 'string', optional: true}];
2019-01-02 14:25:51 -05:00
router.get('/get', requireAuth('key.get'), verifyBody(getProps), async (req, res) => {
2018-08-01 18:57:45 -04:00
let query = {};
2017-10-18 13:31:08 -04:00
if (req.body.identifier)
query.identifier = req.body.identifier;
2018-08-01 18:57:45 -04:00
if (!verifyScope(req.scope, 'key.get.others'))
query.issuer = req.username;
else if (req.body.issuer)
query.issuer = req.body.issuer;
const keys = await Key.find(query);
res.status(200).json(keys);
2019-01-02 14:25:51 -05:00
});
2018-08-01 18:57:45 -04:00
2018-08-14 08:32:42 -04:00
const deleteProps = [
{name: 'key', type: 'string'},
{name: 'issuer', type: 'string', optional: true}];
2019-01-02 14:25:51 -05:00
router.post('/delete', requireAuth('key.delete'), verifyBody(deleteProps), async (req, res) => {
2018-08-01 18:57:45 -04:00
let query = {key : req.body.key};
if (!verifyScope(req.scope, 'key.delete.others'))
query.issuer = req.username;
else if (req.body.issuer)
query.issuer = req.body.issuer;
const key = await Key.findOne(query);
if (!key)
return res.status(422).json({message: 'Key not found.'});
await Key.deleteOne({_id: key._id});
res.status(200).json({message: 'Key deleted.'});
2019-01-02 14:25:51 -05:00
});
2017-10-21 15:10:24 -04:00
2017-10-18 13:31:08 -04:00
module.exports = router;