<?php

/**
 * Returns the authentication token
 */
function wpdav_get_auth_token(){

    return get_option(WPDAV_OPTION_TABLE_TOKEN);

}

/**
 * Sets the authentication token
 */
function wpdav_reset_auth_token(){

    $token = bin2hex(random_bytes(32));
    update_option(WPDAV_OPTION_TABLE_TOKEN, $token);

    return $token;

}

/**
 * Removes the authentication token
 */
function wpdav_remove_auth_token(){

    delete_option(WPDAV_OPTION_TABLE_TOKEN);

}

/**
 * Returns true if the user is authenticated
 */
function wpdav_is_user_authenticated(){

    if(!$_SERVER['HTTP_AUTHORIZATION'])
        return false;

    $request_token = $_SERVER['HTTP_AUTHORIZATION'];
    $request_token = str_replace('Bearer ', '', $request_token);

    $token = wpdav_get_auth_token();

    if(!$token)
        return false;

    return $request_token == $token;

}