<?php
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();
//Load the PHPGangsta_GoogleAuthenticator Class
require_once(dirname(__FILE__).'/GoogleAuthenticator.php');
require_once(dirname(__FILE__).'/TokenHelper.php');
/**
 * Google Authenticator Two Factor Authentication
 *
 * @author Andreas Böhler <dev@aboehler.at>
 * @author Daniel Popp dan@danpopp.net
 */
class auth_plugin_authg2fa extends auth_plugin_authplain  {
    function __construct() {
        parent::__construct();
    }
    function __destruct() {
        //parent::__destruct();
    }

    function checkPass($user,$pass) {
        $th = new TokenHelper();
        $secret = $th->getSecret($user);
        if($secret != "") {
          define('GOOGLE_AUTH_SECRET', $secret);
          $twofactor = true;
        }
        else {
          $twofactor = false;
        }
        $tslack = $this->getConf("g2fa_timeout_slack");
        $enable = $this->getConf("g2fa_enable");
        $force = $this->getConf("g2fa_force");
        $hint = $this->getConf("g2fa_hint");
        if($enable == 1) { // The plugin is at least enabled!
          if(!$twofactor) { // There is no secret for the given user..
            if($force) {
              msg($this->getLang('force'));
              $log = array('message' => 'authg2fa: login failed. No token found for the current user', 'user' => $user);
              trigger_event('PLUGIN_LOGLOG_LOG', $log);
              return false;
            }
            else if($hint) {
              $log = array('message' => 'authg2fa: passing login to parent. No token found for the current user', 'user' => $user);
              trigger_event('PLUGIN_LOGLOG_LOG', $log);
              msg($this->getLang('hint'));
            }
          }
          else { // 2FA is enabled AND we have a secret, so let's check it
            if(isset($_POST['p'])) {
              $ga = new PHPGangsta_GoogleAuthenticator();
              $twofa = $_POST['t'];
              $checkResult = $ga->verifyCode($secret, $twofa, $tslack);
            }
            else {
              $checkResult = false;
            }
            if(!$checkResult) { // 2FA code didn't match OR no password supplied
              $log = array('message' => 'authg2fa: login failed. Token did not match or no token supplied', 'user' => $user);
              trigger_event('PLUGIN_LOGLOG_LOG', $log);
              return false;
            }
          }
        }
        return parent::checkPass($user,$pass);
    }
}
?>
