#!/bin/bash
# info: check user token
# options: USER TOKEN
#
# example: v-check-user-2fa admin 493690
#
# This function verifies user 2fa token.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
user=$1
token=$2

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '2' "$#" 'USER TOKEN'
is_format_valid 'user' 'system'
is_object_valid 'user' 'USER' "$user"

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Reading user values
source $USER_DATA/user.conf

# Check if 2FA is enabled
if [ -z "$TWOFA" ]; then
	echo "Error: Two-factor authentication is not enabled."
	exit "$E_NOTEXIST"
fi

# Check if token is valid
result=$($HESTIA_PHP $HESTIA/web/inc/2fa/check.php "$TWOFA" "$token")
if [ "$result" != "ok" ]; then
	echo "Error: Authentication token mismatch."
	exit 9
fi

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

exit
