aboutsummaryrefslogtreecommitdiff
path: root/routes/integration/auth-request.php
blob: ba049888b926088fb83a2720edb14a4c9813b0fe (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
<?php

// nginx (and others?) auth_request style endpoint
// returns 200 for allowed requests
// otherwise, returns 401 and sends the login page url as a header
// if request header X-Original-Uri is given, it puts it as the post-login redir

function addHeader(array $config, string $baseName, string $value): void {
    $prefix = $config['integration']['header-prefix'];
    header("$prefix-$baseName: $value");
}

function GET(array $config) {
    $session = Psso\Session::get();
    $identity = $session->getIdentity();
    if (isset($identity)) {
        // ok
        addHeader($config, 'User', $identity->user);
        addHeader($config, 'Groups', implode(',', $identity->groups));
        foreach ($identity->extras as $key => $value) {
            if ($value !== null) addHeader($config, ucfirst($key), $value);
        }
        return;
    }

    if (isset($_SERVER['HTTP_X_ORIGINAL_URI'])) {
        $host = parse_url($_SERVER['HTTP_X_ORIGINAL_URI'], PHP_URL_HOST);
        if (in_array(
            $host, $config['integration']['no-redirect-domains'] ?? []
        )) {
            // ok, don't redirect to login page
            return;
        }
    }

    http_response_code(401);
    $login = 'https://' . $config['site']['primary-domain'] . '/login';
    if (isset($_SERVER['HTTP_X_ORIGINAL_URI'])) {
        $login .= '?next=' . urlencode($_SERVER['HTTP_X_ORIGINAL_URI']);
    }
    addHeader($config, 'Location', $login);
}