summaryrefslogtreecommitdiff
path: root/src/UserModule.php
blob: c23097641db7037e71b4ed6b8dd746259d02d1c4 (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
<?php

namespace PHPIAC\Modules;

use PHPIAC\Connection;
use PHPIAC\Module\Module;
use PHPIAC\Module\State;

class UserModule extends Module
{
    protected string $username;
    protected string $password;

    protected bool $append = false;
    protected bool $createHome = true;
    protected array $groups = [];
    protected string $shell = '/bin/bash';
    protected string $state = State::PRESENT;

    /**
     * @inheritDoc
     */
    public function checkState(): bool
    {
        Connection::enablePty();

        Connection::exec("cat /etc/passwd | grep $this->username:");
        $hasUser = Connection::read();

        $state = match ($this->state) {
            State::PRESENT => str_starts_with($hasUser, "$this->username:"),
            State::ABSENT => empty($hasUser),
        };

        Connection::disablePty();

        return $state;
    }

    /**
     * @inheritDoc
     */
    public function getCommands(): array
    {
        if ($this->state === State::PRESENT) {
            Connection::exec(implode(PHP_EOL, [
                "sudo adduser $this->username --quiet" .
                " --shell " . $this->shell .
                ($this->createHome ? '' : ' --no-create-home'),
                "sudo usermod -" . ($this->append ? 'a' : '') . "G " . implode(',', $this->groups) . " $this->username"
            ]));
        }
        else if ($this->state === State::ABSENT) {
            Connection::exec("sudo userdel $this->username");
        }

        return [];
    }
}