<?php
/**
 * @package   solo
 * @copyright Copyright (c)2014-2024 Nicholas K. Dionysopoulos / Akeeba Ltd
 * @license   GNU General Public License version 3, or later
 */

namespace Solo\Application;

use Awf\Container\ContainerAwareInterface;
use Awf\Container\ContainerAwareTrait;
use Awf\User\Authentication;

abstract class UserAuthenticationOtep extends Authentication implements ContainerAwareInterface
{
	use ContainerAwareTrait;

	/**
	 * Validates an OTEP. If the OTEP is valid it will be removed from the list of OTEPs and the user account will be
	 * saved with the updated list of OTEPs.
	 *
	 * @param   string  $otp  The OTP generated by Google Authenticator
	 *
	 * @return  boolean  True if it's a valid OTEP.
	 */
	public function validateOtep($otp)
	{
		// Get the OTEPs
		$oteps = $this->user->getParameters()->get('tfa.otep', array());

		// If there is no OTEP we can't authenticate
		if (empty($oteps))
		{
			return false;
		}

		$oteps = (array)$oteps;

		// Does this OTEP exist in the list?
		$tempOtp = preg_filter('/\D/', '', $otp);
		$otp = is_null($tempOtp) ? $otp : $tempOtp;

		// No. Can't authenticate.
		if (!in_array($otp, $oteps))
		{
			return false;
		}

		// Remove the OTEP from the list
		$array_pos = array_search($otp, $oteps);
		$temp = array();

		// Ugly as heck, but PHP freaks out with the number-as-string array indexes it produces.
		foreach ($oteps as $foo)
		{
			if ($foo == $otp)
			{
				continue;
			}

			$temp[] = $foo;
		}

		// Save the modified user
		$this->user->getParameters()->set('tfa.otep', $temp);

		$userManager = $this->getContainer()->userManager;
		$userManager->saveUser($this->user);

		// OK, we can authenticate
		return true;
	}
}
