Skip to content
Snippets Groups Projects
Select Git revision
  • 5ddb85b24417405b65b1661f9a1a0c4442043f41
  • main default protected
  • rewrite
  • production
4 results

api_handler.php

Blame
  • api_handler.php 5.03 KiB
    <?php
    
    $output_format = "json";
    header('Content-type: application/json');
    
    if (array_key_exists('HTTP_AUTHORIZATION', $_SERVER)) {
        $access_token = str_replace("Bearer ", "", $_SERVER['HTTP_AUTHORIZATION']);
    }
    
    if (!empty($access_token)) {
        // Check who the access token belongs to
        $token = db_execute("SELECT * FROM tokens WHERE access_token = ?", [$access_token]);
        // if the token doesn't exist...
        if (empty($token)) {
    
            $invalid_token = true; // We won't tell this to the end-user immediately because I'd prefer to tell them about
                                    // 404 first.
        } else {
            $token_owner = $token['owner_id'];
        }
    }
    
    function check_authorisation($token=""): int
    {
        global $token_owner;
        // Validate token
        if (!validate_access_token($token) && "" != $token) {
            return 0; // Unauthorised
        }
    
        // Check the type of token
        $token_row = db_execute("SELECT * FROM tokens WHERE access_token = ?", [$token]);
    
        if (null == $token_row) {
            if (array_key_exists('auth', $_SESSION)) {
                if ($_SESSION['auth']) {
                    $token_row = [
                        "type" => "dangerous"
                    ];
                    $token_owner = $_SESSION['id'];
                } else {
                    return 0;
                }
            } else {
                return 0;
            }
        }
    
        return match ($token_row['type']) {
            "dangerous" => 1<<0 | 1<<1, // Everything
            "basic"     => 1<<1, // Basic
            "oauth"     => $token_row['permissions'],
            default     => 0,
        };
    }
    
    // Misc (unauthorised)
    
    function redirect_to_documentation(): void
    {
        header('Location: /docs/api');
    }
    
    // Health check
    
    function api_health_check(): array
    {
        return ["message" => "Science compels us to explode the sun!", "time" => time(), "response_code" => 200];
    }