<?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/. */

/**
 * Authentication and account functions
 */
use Base32\Base32;
use OTPHP\TOTP;

/**
 * Checks the given credentials against the database.
 * @param string $username
 * @param string $password
 * @return boolean True if OK, else false
 */
function authenticate_user($username, $password) {
    global $database;
    $username = strtolower($username);
    if (is_empty($username) || is_empty($password)) {
        return false;
    }
    $hash = $database->get('accounts', 'password', ['username' => $username]);
    return (comparePassword($password, $hash));
}

function user_exists($username) {
    return $database->has('accounts', ['username' => strtolower($username)]);
}


////////////////////////////////////////////////////////////////////////////////
//                          2-factor authentication                           //
////////////////////////////////////////////////////////////////////////////////

/**
 * Check if a user has TOTP setup
 * @global $database $database
 * @param string $username
 * @return boolean true if TOTP secret exists, else false
 */
function userHasTOTP($username) {
    global $database;
    $username = strtolower($username);
    $secret = $database->get('accounts', 'authsecret', ['username' => $username]);
    if (is_empty($secret)) {
        return false;
    }
    return true;
}

/**
 * Verify a TOTP multiauth code
 * @global $database
 * @param string $username
 * @param int $code
 * @return boolean true if it's legit, else false
 */
function verifyTOTP($username, $code) {
    global $database;
    $username = strtolower($username);
    $authsecret = $database->get('accounts', 'authsecret', ['username' => $username]);
    if (is_empty($authsecret)) {
        return false;
    }
    $totp = new TOTP(null, $authsecret);
    return $totp->verify($code);
}

