aboutsummaryrefslogtreecommitdiff
path: root/middlewares/TokenAuthenticationMiddleware.php
blob: 31544ab7a6b58ee32e85eb93fdd7d7305c6bfa75 (plain) (blame)
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
<?php

declare(strict_types=1);

class TokenAuthenticationMiddleware implements Middleware
{
    public function __invoke(Request $request, $next): Response
    {
        if (! Configuration::getConfig('authentication', 'token')) {
            return $next($request);
        }

        $token = $request->get('token');

        if (! $token) {
            return new Response(render(__DIR__ . '/../templates/token.html.php', [
                'message'   => 'Missing token',
                'token'     => '',
            ]), 401);
        }

        if (! hash_equals(Configuration::getConfig('authentication', 'token'), $token)) {
            return new Response(render(__DIR__ . '/../templates/token.html.php', [
                'message'   => 'Invalid token',
                'token'     => $token,
            ]), 401);
        }

        $request = $request->withAttribute('token', $token);

        return $next($request);
    }
}