Skip to content

Commit

Permalink
Clean up files and organize methods
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelg29 committed Oct 25, 2023
1 parent c5e78a1 commit 3756012
Show file tree
Hide file tree
Showing 14 changed files with 383 additions and 261 deletions.
22 changes: 16 additions & 6 deletions ota-portal/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ const logger = require("morgan");
const path = require("path");
const errors = require("./utils/httperror");

// middleware and router includes
const auth = require("./routes/auth");
const nodesRouter = require("./routes/nodes");
const nodeAuthRouter = require("./routes/nodeAuth");
const nodeListRouter = require("./routes/nodeList");
const nodeRouter = require("./routes/nodes");
const networksRouter = require("./routes/networks");
const networkChannelsRouter = require("./routes/networkChannels");
const networkRegistrationsRouter = require("./routes/networkRegistrations");

// create application
var app = express();

// middleware
// basic middleware
app.use(logger('dev'));
app.use(express.text({
type: "text/*"
Expand All @@ -27,7 +31,7 @@ app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// authorization
// authorization middleware
app.use(auth);

// index redirect
Expand All @@ -37,10 +41,14 @@ app.get("/", (req, res) => {
});
});

app.use("/nodes", nodesRouter);
app.use("/nodes", nodeAuthRouter);
// register middleware
app.use("/nodes", nodeRouter);
app.use("/nodes", nodeListRouter);
app.use("/networks", networksRouter);
app.use("/networks", networkChannelsRouter);
app.use("/networks", networkRegistrationsRouter);

// not found handler
app.use(function (req, res, next) {
next(errors.errorObj(404, "Not found."));
});
Expand All @@ -55,9 +63,11 @@ app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = isDevelopment ? err : {};

// set status code
err.statusCode = err.statusCode || 500;
res.status(err.statusCode);

// wrap content in specific content type
const returnType = req.headers.accept;
if (returnType === "application/json") {
res.send({
Expand Down
10 changes: 5 additions & 5 deletions ota-portal/public/javascripts/nodes/tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ async function deleteNode(nodeId) {
await dataRequest("DELETE", `nodes/${nodeId}`);
}

async function uploadFile() {
async function uploadFile(networkId) {
// get node IDs to upload to
let nodeSelectElements = document.querySelectorAll("input.node-selector");
let node_ids = [];
let nodeIds = [];
for (let el of nodeSelectElements) {
if (!!el.checked) {
node_ids.push(el.id.substring("select-".length));
nodeIds.push(el.id.substring("select-".length));
}
}

// get channel ID to upload file
let channelRes = await dataRequest("POST", "file_channel", undefined, {
"node_ids": node_ids
let channelRes = await dataRequest("POST", `networks/${networkId}/channel`, undefined, {
"nodeIds": nodeIds
});

return;
Expand Down
36 changes: 28 additions & 8 deletions ota-portal/routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
/**
* Authorization middleware.
*/

const express = require('express');
const router = express.Router();
const errors = require('../utils/httperror');
const rclient = require('../utils/redis-client');
const base64url = require('base64url').default;

// encryption and decryption parameters and keys
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = !!process.env.PORTAL_TOKEN_ENC_KEY
Expand All @@ -12,11 +18,10 @@ const iv = !!process.env.PORTAL_TOKEN_ENC_IV
? Buffer.from(process.env.PORTAL_TOKEN_ENC_IV)
: crypto.randomBytes(8);

// cookie names
const tokenCookieName = "jamota-token";
const tokenExpiryCookieName = "jamota-token-expiry";

const base64url = require('base64url').default;

function encryptToken(token) {
// get buffer of string
var b = Buffer.from(JSON.stringify(token));
Expand Down Expand Up @@ -78,7 +83,9 @@ async function logout(req, res) {
}
}

// access token decoder
/**
* Access token decoder. To be executed before route-specific function.
*/
router.use(errors.asyncWrap(async function(req, res, next) {
if (req.url === "/login" || req.url === "/createAccount") {
next();
Expand Down Expand Up @@ -117,6 +124,9 @@ router.use(errors.asyncWrap(async function(req, res, next) {
next();
}));

/**
* Request a refreshed access token.
*/
router.post("/refreshToken", async function(req, res, next) {
if (req.user) {
const userKey = "user:" + req.user.username;
Expand All @@ -132,12 +142,16 @@ router.post("/refreshToken", async function(req, res, next) {
}
});

// registration form
/**
* Form to create an account with the OTA system.
*/
router.get("/createAccount", function(req, res, next) {
res.render("createAccount");
});

// create account request
/**
* Register an account with the OTA system.
*/
router.post("/createAccount", errors.asyncWrap(async function(req, res, next) {
if (!req.body || !req.body.email || !req.body.username || !req.body.password || !req.body.name) {
errors.error(400, "Invalid input.");
Expand Down Expand Up @@ -175,7 +189,9 @@ router.post("/createAccount", errors.asyncWrap(async function(req, res, next) {
res.redirect("/login");
}));

// login form
/**
* Get the login form.
*/
router.get("/login", function(req, res, next) {
if (req.user) {
res.redirect("/");
Expand All @@ -185,7 +201,9 @@ router.get("/login", function(req, res, next) {
}
});

// login request
/**
* Validate a login request.
*/
router.post("/login", errors.asyncWrap(async function(req, res, next) {
if (req.user) {
res.sendStatus(200);
Expand Down Expand Up @@ -226,7 +244,9 @@ router.post("/login", errors.asyncWrap(async function(req, res, next) {
res.redirect("/");
}));

// logout
/**
* Logout the user.
*/
router.all("/logout", async function(req, res, next) {
logout(req, res);
res.redirect("/login");
Expand Down
Empty file removed ota-portal/routes/list.js
Empty file.
51 changes: 51 additions & 0 deletions ota-portal/routes/networkChannels.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Authorized requests for network channels in the database.
*/

const express = require("express");
const router = express.Router();

const errors = require("../utils/httperror");
const request = require("../utils/request");
const rclient = require("../utils/redis-client");

const network = require("../utils/network");
const channel = require("../utils/channel");
const node = require("../utils/node");

/**
* Create a channel to communicate with multiple nodes. Each network can only have one active channel.
*/
router.post("/:id/channel", errors.asyncWrap(async function(req, res) {
// parse request
const networkId = req.params.id;
const channelReq = request.validateBody(req, ["nodeIds?"]);

// validate request
await network.getNetworkFromOwner(req, networkId);
let [err, networkNodeIds] = await rclient.getSetMembers(node.networkNodesKey(networkId));

let nodeIds = [];
if ("nodeIds" in channelReq && channelReq.nodeIds.length > 0) {
// filter nodes to the current network
for (let nodeId of channelReq.nodeIds) {
if (networkNodeIds.indexOf(nodeId) != -1) {
nodeIds.push(nodeId);
}
}
}
else {
// if none provided, select all nodes in the network
nodeIds = networkNodeIds;
}

console.log(nodeIds);

// create channel
await channel.newChannelObj(networkId, nodeIds);

// return response
res.status(200);
}));

module.exports = router;
53 changes: 53 additions & 0 deletions ota-portal/routes/networkRegistrations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Authorized requests for network registrations in the database.
*/

const express = require("express");
const router = express.Router();

const errors = require("../utils/httperror");
const request = require("../utils/request");

const network = require("../utils/network");
const passphrases = require("../utils/network_passphrase");

/**
* Get the node registration form.
*/
router.get("/:id/node", errors.asyncWrap(async function(req, res, next) {
[err, redisRes] = await network.getNetworkFromOwner(req, req.params.id);

res.render("network/register", {
netId: req.params.id
});
}));

/**
* Prepare a node passphrase.
*/
router.post("/:id/node", errors.asyncWrap(async function(req, res, next) {
const nodeReq = request.validateBody(req, ["name", "pass"]);

passphrases.validateNetworkPassphrase(nodeReq.pass);

// check requested network
const networkId = req.params.id;
await network.getNetworkFromOwner(req, networkId);

// set in database
await passphrases.addNetworkPassphrase(networkId, nodeReq.name, nodeReq.pass);

res.redirect("/nodes?network-id=" + req.params.id);
}));

/**
* Clear all unused passphrases.
*/
router.delete("/:id/passphrases", errors.asyncWrap(async function(req, res, next) {
const networkId = req.params.id;
await network.getNetworkFromOwner(req, networkId);
await passphrases.clearPassphrases(networkId);
res.sendStatus(204);
}));

module.exports = router;
42 changes: 1 addition & 41 deletions ota-portal/routes/networks.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const request = require("../utils/request");

const ijam_types = require("../utils/ijam_types");
const network = require("../utils/network");
const passphrases = require("../utils/network_passphrase");
const node = require("../utils/node");

/**
Expand Down Expand Up @@ -108,7 +107,7 @@ router.get("/", errors.asyncWrap(async function(req, res, next) {
var data = await filterNetworkEntries(networkIds);

if (req.headers.accept === "application/json") {
res.send(data)
res.send(data);
}
else {
res.render("network/list", {
Expand All @@ -117,43 +116,4 @@ router.get("/", errors.asyncWrap(async function(req, res, next) {
}
}));

/**
* Get the node registration form.
*/
router.get("/:id/node", errors.asyncWrap(async function(req, res, next) {
[err, redisRes] = await network.getNetworkFromOwner(req, req.params.id);

res.render("network/register", {
netId: req.params.id
});
}));

/**
* Prepare a node passphrase.
*/
router.post("/:id/node", errors.asyncWrap(async function(req, res, next) {
const nodeReq = request.validateBody(req, ["name", "pass"]);

passphrases.validateNetworkPassphrase(nodeReq.pass);

// check requested network
const networkId = req.params.id;
await network.getNetworkFromOwner(req, networkId);

// set in database
await network.addNetworkPassphrase(networkId, nodeReq.name, nodeReq.pass);

res.redirect("/nodes?network-id=" + req.params.id);
}));

/**
* Clear all unused passphrases.
*/
router.delete("/:id/passphrases", errors.asyncWrap(async function(req, res, next) {
const networkId = req.params.id;
await network.getNetworkFromOwner(req, networkId);
await network.clearPassphrases(networkId);
res.sendStatus(204);
}));

module.exports = router;
Loading

0 comments on commit 3756012

Please sign in to comment.