summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorDaniel Weipert <code@drogueronin.de>2021-04-18 21:46:19 +0200
committerDaniel Weipert <code@drogueronin.de>2021-04-18 21:46:19 +0200
commit671e3f1540f3a683d548dafd64c068ad6a64ac2f (patch)
treeec8d85847ecce2565280b038c3a48891bfa52db6 /src
parent82e4d1ca348748e8cdde86f65e62221968cabed5 (diff)
Adds UserModule
Diffstat (limited to 'src')
-rw-r--r--src/Module/Modules/UserModule.php70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/Module/Modules/UserModule.php b/src/Module/Modules/UserModule.php
new file mode 100644
index 0000000..1749b58
--- /dev/null
+++ b/src/Module/Modules/UserModule.php
@@ -0,0 +1,70 @@
+<?php
+
+namespace PHPIAC\Module\Modules;
+
+use PHPIAC\Module\ModuleInterface;
+use PHPIAC\Module\State;
+use phpseclib3\Net\SSH2;
+
+class UserModule implements ModuleInterface
+{
+ /**
+ * UserModule constructor.
+ *
+ * @param string $name
+ * @param array $options
+ * @param string $state
+ */
+ public function __construct(
+ private string $name,
+ private array $options = [],
+ private string $state = State::PRESENT
+ ) {
+ $this->options = array_replace([
+ 'append' => false,
+ 'create_home' => true,
+ 'groups' => [],
+ 'shell' => '/bin/bash',
+ ], $options);
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function checkState(): bool
+ {
+ global $ssh;
+ /**@var SSH2 $ssh*/
+ $ssh->enablePTY();
+
+ $ssh->exec("cat /etc/passwd | grep $this->name:");
+ $hasUser = $ssh->read();
+
+ $state = match ($this->state) {
+ State::PRESENT => str_starts_with($hasUser, "$this->name:"),
+ State::ABSENT => empty($hasUser),
+ };
+
+ $ssh->disablePTY();
+
+ return $state;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getCommands(): array
+ {
+ return match ($this->state) {
+ State::PRESENT => [
+ "sudo adduser $this->name --quiet" .
+ " --shell " . $this->options['shell'] .
+ ($this->options['create_home'] ? '' : ' --no-create-home'),
+ "sudo usermod -" . ($this->options['append'] ? 'a' : '') . "G " . implode(',', $this->options['groups']) . " $this->name"
+ ],
+ State::ABSENT => [
+ "sudo apt remove -y $this->package",
+ ],
+ };
+ }
+}