<?php
require_once 'Yubikey.php';

class OC_USER_YUBIKEY extends OC_User_Backend {
}

class OC_Yubikey {
	public static function preLogin( $data ) {
		// Assume failed pre_auth()
		$data['run'] = false;
		$yubikey_clientid = OC_Appconfig::getValue('user_yubikey', 'yubikey_clientid','');
		$yubikey_clientkey = OC_Appconfig::getValue('user_yubikey', 'yubikey_clientkey','');

		if (empty($yubikey_clientid) || empty($yubikey_clientkey)) {
			return false;
		}

		$yubi = new Yubikey((int)$yubikey_clientid, $yubikey_clientkey);

		if (!$yubi->verify($data['data'])) {
			OC_Log::write('OC_USER_YUBIKEY', $yubi->getLastResponse(), 3);
			return false;
		} else {
			$query = OC_DB::prepare( "SELECT userid FROM `*PREFIX*preferences` WHERE appid = 'user_yubikey' AND configkey = 'identity' AND configvalue = ? AND userid = ?" );
			$result = $query->execute( array( substr ($data['data'], 0, 12), $data['uid'] ));
			$row=$result->fetchRow();
			if(!$row || ($row['userid'] != $data['uid'])){
				return false;
			}
		}

		// pre_auth() success
		$data['run'] = true;
	}
}

OC_Hook::connect('OC_User','pre_login','OC_Yubikey','preLogin');

?>
