<?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\RFC6238\OTP;
use AuthStack\TwoFactor\Verifier\VerifierInterface;
use AuthStack\TwoFactor\Verifier\Traits\TraitErrorHandler;
use AuthStack\TwoFactor\Verifier\Traits\TraitResultHandler;
use AuthStack\TwoFactor\Verifier\Traits\TraitFetchFromMetadata;

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

    public function verify($otp)
    {
        $secret     = $this->fromMetadata('secret');
        $interval   = $this->fromMetadata('interval', 30); // Interval value are seconds
        $algo       = $this->fromMetadata('algo', 'sha1');

        $auth       = new OTP($secret, $interval, $algo);

        $auth->setConversionMethod(function($secret){
            return $secret;
        });

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

        $result = false;

        try
        {
            $result = $auth->verify($otp);

            if(false === $result)
            {
                $this->setError("Invalid OTP.");
            }
        }
        catch(\Exception $e)
        {
            $this->setError($e->getMessage());
        }

        return $result;
    }
}