#!/usr/bin/env python
#
# Copyright 2012 Red Hat, Inc
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import ctypes

import authhub

ykclient = ctypes.cdll.LoadLibrary("libykclient.so")

YKCLIENT_OK = 0

class YubikeyHandler(authhub.Handler):
    
    def getTokenInfo(self, params):
        cfg = params.get("config", {})
        url = cfg.get("url", None)
        id  = cfg.get("id", None)
        vnd = cfg.get("vendor", None)
        
        if not isinstance(url, basestring) or type(id) != int:
            return []
        
        if vnd is None:
            vnd = "Yubico, Inc."

        return [{"otp-vendor": vnd}]
    
    def verifyRequest(self, params):
        cfg = params.get("config", {})
        req = params.get("request", {})
        url = cfg.get("url", None)
        id  = cfg.get("id", None)
        val = req.get("otp-value", None)
        
        if not isinstance(val, basestring):
            return False
        
        if not isinstance(url, basestring) or type(id) != int:
            return False
        
        ykc = ctypes.c_void_p()
        if ykclient.ykclient_init(ykc.byref()) != YKCLIENT_OK:
            return False
        
        try:
            ykclient.ykclient_set_client(ykc, id, 0, None)
            ykclient.ykclient_set_url_template(ykc, url)
            return ykclient.ykclient_request(ykc, val) == YKCLIENT_OK
        finally: # Always free the handle
            ykclient.ykclient_done(ykc.byref())

if __name__ == "__main__":
    authhub.ThreadingPlugin(YubikeyHandler()).runForever()
        
    

