aboutsummaryrefslogtreecommitdiff
path: root/Psso/Challenge.php
blob: 72100ce240164e2882ebaa6d29ec3158d7eeb681 (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 Psso;

abstract class Challenge {
    public protected(set) Context $context;
    protected array $inputs = [];
    public protected(set) string $serial;
    
    protected function __construct(Context $context) {
        $this->context = $context;
        $this->serial = base64_encode(random_bytes(9));
    }
    
    public static function create(Context $context): ?static {
        return new static($context);
    }
    
    public abstract function getInputs(): array;
    
    public abstract function validate(
        AuthProvider $provider, array $inputData
    ): ChallengeResult;

    public function addAsHtml(\SimpleXMLElement $parent): void {
        $form = $parent->addChild('form');
        $form->addAttribute('method', 'post');
        foreach ($this->getInputs() as $input) {
            $input->addAsHtml($form);
            $this->inputs[$input->serial] = $input;
        }
        $serial = $form->addChild('input');
        $serial->addAttribute('type', 'hidden');
        $serial->addAttribute('name', 'challenge');
        $serial->addAttribute('value', $this->serial);
        $submit = $form->addChild('button', L('challenge.continue'));
    }

    public function findInput(string $serial): ?Input {
        return $this->inputs[$serial] ?? null;
    }

    protected static function requireInterface(
        AuthProvider $provider, string $interface
    ): void {
        if (!($provider instanceof $interface)) {
            throw new \InvalidArgumentException(
                "Provider must implement $interface"
            );
        };
    }

    protected static function requireKnownUser(Context $context): void {
        if (!isset($context->user)) {
            throw new \RuntimeException(
                'Unknown user, but known user required for ' . static::class
            );
        }
    }
}