<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Simple JSON API to allow other apps to access accounts in this system.
 *
 * Requests can be sent via either GET or POST requests.  POST is recommended
 * as it has a lower chance of being logged on the server, exposing unencrypted
 * user passwords.
 */
require __DIR__ . '/required.php';
require __DIR__ . '/lib/login.php';

switch ($VARS['action']) {
    case "ping":
        exit(json_encode(["status" => "OK"]));
        break;
    case "auth":
        $errmsg = "";
        if (authenticate_user($VARS['username'], $VARS['password'], $errmsg)) {
            exit(json_encode(["status" => "OK", "msg" => "Login successful."]));
        } else {
            exit(json_encode(["status" => "ERROR", "msg" => "Login incorrect."]));
        }
        break;
    case "hastotp":
        if (userHasTOTP($VARS['username'])) {
            exit(json_encode(["status" => "OK", "otp" => true]));
        } else {
            exit(json_encode(["status" => "OK", "otp" => false]));
        }
        break;
    case "verifytotp":
        if (verifyTOTP($VARS['username'], $VARS['code'])) {
            exit(json_encode(["status" => "OK", "valid" => true]));
        } else {
            exit(json_encode(["status" => "ERROR", "msg" => "Authentication code incorrect.", "valid" => false]));
        }
        break;
    default:
        http_response_code(404);
        die(json_encode("404 Not Found: the requested action is not available."));
}
