summaryrefslogtreecommitdiff
path: root/useradm.php
blob: 30a7a06e4e78b67bd41d0a23b0df645aab0c27a0 (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
<?php
	if (!defined('STDIN')) {
		print "Please run this script via PHP CLI interpreter (php ./useradm.php).";
		exit;
	}

	require_once "config.php";
	require_once "db.php";

	$dbh = Db::get();

	$longopts = [ "add:", "del:", "list", "help" ];

	$options = getopt("", $longopts);

	if (count($options) == 0 || isset($options["help"])) {
		print "Manage Epube user database. Usage:
	--add USER
	--del USER
	--list\n";
	}

	if (isset($options["del"])) {
		$user = $options["del"];

		$sth = $dbh->prepare("SELECT id FROM epube_users WHERE user = ?");
		$sth->execute([$user]);

		if ($sth->fetch()) {
			print "Deleting user $user...\n";

			$sth = $dbh->prepare("DELETE FROM epube_users WHERE user = ?");
			$sth->execute([$user]);
		} else {
			print "User $user not found.\n";
		}
	}

	if (isset($options["list"])) {
		$res = $dbh->query("SELECT id, user FROM epube_users ORDER BY user");

		while ($line = $res->fetch()) {
			print $line["user"] . "\n";
		}

	}

	if (isset($options["add"])) {
		$user = $options["add"];

		if (!$user) {
			print "Not enough arguments.\n";
			exit;
		}

		print "Enter password for user $user: ";
		$pass = fgets(STDIN);

		$user = trim(mb_strtolower($user));
		$pass = trim($pass);
		$pass_hash = 'SHA256:' . hash('sha256', "$user:" . trim($pass));

		print "Adding user $user with password $pass...\n";

		$sth = $dbh->prepare("SELECT user FROM epube_users WHERE user = ?");
		$sth->execute([$user]);

		if ($line = $sth->fetch()) {
			print "User already exists, updating password.\n";

			$sth = $dbh->prepare("UPDATE epube_users SET pass = ? WHERE user = ?");
			$sth->execute([$pass_hash, $user]);

		} else {
			$sth = $dbh->prepare("INSERT INTO epube_users (user, pass)
					VALUES (?, ?)");
			$sth->execute([$user, $pass_hash]);
		}

	}

?>