1 /**
2 	Provides a web based administration interface.
3 
4 	Copyright: © 2012-2013 RejectedSoftware e.K.
5 	License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
6 	Authors: Sönke Ludwig
7 */
8 module vibedist.admin;
9 
10 import vibedist.controller;
11 import vibedist.engine;
12 
13 import std.exception;
14 import std.file;
15 import std.functional : toDelegate;
16 import std.process : spawnProcess;
17 import vibe.crypto.passwordhash;
18 import vibe.core.log;
19 import vibe.http.auth.basic_auth;
20 import vibe.http.router;
21 import vibe.http.server;
22 import vibe.inet.path;
23 
24 
25 private AdminWebInterface s_interface;
26 
27 void startAdminWebInterface(VibeDistController ctrl)
28 {
29 	s_interface = new AdminWebInterface(ctrl);
30 }
31 
32 class AdminWebInterface {
33 	private {
34 		VibeDistController m_ctrl;
35 	}
36 
37 	this(VibeDistController ctrl)
38 	{
39 		Config config;
40 		ctrl.getConfig(config);
41 
42 		// setup admin interface
43 		auto settings = new HTTPServerSettings;
44 		settings.bindAddresses = [config.adminInterface];
45 		settings.port = config.adminPort;
46 		//settings.sslCertFile = "admin.crt";
47 		//settings.sslKeyFile = "admin.key";
48 
49 		auto router = new URLRouter;
50 		router.get("*", performBasicAuth("VibeDist Admin Interface", toDelegate(&testPassword)));
51 		router.get("/", &showAdminHome);
52 		router.post("/restart_node", &reloadNode);
53 		router.post("/start_node", &startNode);
54 
55 		listenHTTP(settings, router);
56 	}
57 
58 	void showAdminHome(HTTPServerRequest req, HTTPServerResponse res)
59 	{
60 		Config config;
61 		m_ctrl.getConfig(config);
62 
63 		auto interfaces = g_interfaces;
64 
65 		res.render!("home.dt", req, config, interfaces);
66 	}
67 
68 	void startNode(HTTPServerRequest req, HTTPServerResponse res)
69 	{
70 		auto path = Path(req.form["path"]);
71 		enforce(path.absolute, "The path to the vibe application must be absolute.");
72 
73 		string[] args;
74 		args ~= "dub";
75 		args ~= "--";
76 		args ~= "--disthost";
77 		args ~= "127.0.0.1";
78 		auto cwd = getcwd();
79 		chdir(path.toNativeString());
80 		scope(exit) chdir(cwd);
81 		auto process = spawnProcess(args);
82 		logInfo("Spawned %s as %d", path.toString(), process);
83 
84 		res.redirect("/");
85 	}
86 
87 	void reloadNode(HTTPServerRequest req, HTTPServerResponse res)
88 	{
89 
90 	}
91 
92 	private bool testPassword(string username, string password)
93 	{
94 		if( username != "root" ) return false;
95 		Config cfg;
96 		m_ctrl.getConfig(cfg);
97 		auto pwhash = cfg.rootPasswordHash;
98 		return testSimplePasswordHash(pwhash, password);
99 	}
100 }