#!/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/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# load config file
source_conf "$TULIO/conf/tulio.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=$($TULIO_PHP $TULIO/web/inc/2fa/check.php "$TWOFA" "$token")
if [ "$result" != "ok" ]; then
	echo "Error: Authentication token mismatch."
	exit 9
fi

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

exit
