aboutsummaryrefslogtreecommitdiff
path: root/app.js
blob: ed2133470edbcf58b6062d6400f0e5ce077d88a1 (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const express = require("express");
const api = require("./api/v1");
const git = require("./api/git");
const yaml = require('js-yaml');
const fs = require('fs');
const { exit } = require("process");
const sanitization = require("./api/sanitization");

let settings;

try {
	settings = yaml.load(fs.readFileSync("./settings.yml", 'utf8'));
} catch(e) {
	throw(e);
}

const mandatory_settings = ["host", "port", "title", "about", "base_dir"];
const missing_settings_key = mandatory_settings.find(key => settings.hasOwnProperty(key) === false);
if(missing_settings_key) {
	console.error(`Error: missing key in settings.yml: ${missing_settings_key}`);
	exit(1);
}

const app = express();

app.get(/.*\.(css|js|ico)$/, (req, res, next) =>
{
	fs.access(`dist${req.path}`, err =>
	{
		if(err) {
			next();
			return;
		}
		res.sendFile(`dist${req.path}`, { root: __dirname });
	});
});

app.use("/api/v1", (req, res, next) =>
{
	req.settings = settings;
	next();
}, api);

app.use("/:repo", async (req, res, next) =>
{
	if(!sanitization.sanitizeRepoName(req.params.repo)) {
		res.status(400).json({ "error": "Unacceptable git repository name!" });
		return;
	}

	fs.readdir(settings["base_dir"], (err, dir_content) =>
	{
		if(err) {
			res.status(404).send("404: Page not found");
			return;
		}
		
		dir_content = dir_content.filter(repo => repo.endsWith(".git"));

		if(!dir_content.includes(req.params.repo + ".git")) {
			res.status(404).send("404: Page not found");
			return;
		}
		else {
			next();
		}
	});
})

app.get("/:repo", (req, res) =>
{
	res.redirect(`/${req.params.repo}/log`);
});

app.get("/:repo/:page", (req, res, next) =>
{
	const pages = ["log", "refs", "tree"];
	if(!pages.includes(req.params.page)) {
		next();
		return;
	}
	
	res.sendFile("dist/app.html", { root: __dirname });
});

app.get("/:repo/log/:commit", (req, res, next) =>
{
	if(!sanitization.sanitizeCommitID(req.params.commit)) {
		next();
		return;
	}
	res.sendFile("dist/app.html", { root: __dirname });
});


app.get("/", (req, res) =>
{
	res.sendFile("dist/app.html", { root: __dirname });
});

app.use((req, res) =>
{
	res.status(404).send("404: Page not found");
});

app.listen(settings["port"], settings["host"], () => console.log(`App is running on ${settings["host"]}:${settings["port"]}`));