<?php

/*
 * This file is part of the AuthStack project.
 *
 * (c) Buckhill Ltd <development@buckhill.co.uk>
 *
 * This source file is subject to the Buckhill license that is bundled
 * with this source code in the file LICENSE.
 */

namespace AuthStack\TwoFactor\Verifier\Implementation;


use Buckhill\Yubico\Modes\OATH\OTP;
use Buckhill\Yubico\Modes\OATH\YubikeyOATH as Yubikey;
use AuthStack\TwoFactor\Verifier\VerifierInterface;
use AuthStack\TwoFactor\Verifier\Traits\TraitErrorHandler;
use AuthStack\TwoFactor\Verifier\Traits\TraitResultHandler;
use AuthStack\TwoFactor\Verifier\Traits\TraitFetchFromMetadata;


class YubikeyOATH implements VerifierInterface
{
    use TraitErrorHandler;
    use TraitFetchFromMetadata;
    use TraitResultHandler;

    public function verify($otp)
    {
        $auth           = new OTP($otp);
        $yubikey        = Yubikey::fromArray($this->getMetadata());

        //--------------------------------------------------------------------------------------------------------------
        // OTP class throws an exception in case of errors
        //--------------------------------------------------------------------------------------------------------------

        $result = false;

        try
        {
            $counter         = $yubikey->verify($auth);

            $this->setResult([
                'counter' => $counter + 1
            ]);

            $result         = true;
        }
        catch(\Exception $e)
        {
            $this->setError($e->getMessage());
        }

        return $result;
    }
}