from twisted.web import client
from zope.interface import implements
from twisted import cred
import twisted.cred.portal
import twisted.cred.credentials
import twisted.cred.checkers
import twisted.cred.error
import logging
from twisted.internet import defer

log = logging.getLogger("AuthLog")


class clientAuth:

   implements(cred.checkers.ICredentialsChecker)
   
   credentialInterfaces = (
      cred.credentials.IUsernamePassword,
   )

   def __init__(self, uri):
      self.uri = uri
      
   def checkAuth(self, usr, pwd):
      log.debug('Auth HTTP Request for user '+usr)
      return client.getPage(self.uri+'?user='+usr+'&pass='+pwd)

   def getAuth(self, usr, pwd):
      return self.checkAuth(usr, pwd).addCallback(self.getPerms)

   def getPerms(self, res):
      perms = {'general': {'canview': False, 'canset': False, 'admin': False, 'enabled': False}}
      try:
         if res[:1] == '1' or res[:1] == '4':
            perms['general']['canview'] = True
            perms['general']['enabled'] = True
            if res[:1] == '4':
               perms['general']['admin'] = True
            try:
               permissions = res[2:].split(',')
               for perm in permissions:
                  if perm.split(':')[1] == '1':
                     try:
                        perms[perm.split(':')[0]]['canset'] = True
                     except:
                        perms[perm.split(':')[0]] = {'canset': True}

            except:
               pass
            return perms

         elif res[:1] == '2':
            perms['general']['canview'] = True
            return perms

         elif res[:1] == '3':
            return False

         return False
      except:
         return False

   def requestAvatarId(self, c):
      return self.checkAuth(c.username, c.password).addCallback(
         self.getPerms).addCallback(
         self.AvatarResults, c)

   def AvatarResults(self, res, c):
      if res:
         #return c.username
         return defer.succeed([c, res])
      raise cred.error.UnauthorizedLogin()



class DBClientAuth(clientAuth):

   def __init__(self):
      pass

   def checkAuth(self, usr, pwd):
      from Database import utils as dbutils
      log.debug('Auth DATABASE Request for user '+usr)
      if len(str(pwd)) > 5:
         if str(pwd)[:5] == 'HASH:':
            return defer.succeed(dbutils.checkUserPwd(usr, str(pwd)[5:], True))
      return defer.succeed(dbutils.checkUserPwd(usr, pwd))

   def getPerms(self, res):
      if len(res) == 2:
         if len(res[0]) > 0:
            perms = {'general': {'canview': True, 'canset': False, 'admin': False, 'enabled': False}}
            udata = res[0][0]
            usubs = res[1]
            if udata.admin:
               perms['general']['admin'] = True
            if len(usubs) > 0:
               perms['general']['enabled'] = True
               for tnum in usubs:
                  perms[str(tnum)] = {'canset': True, 'canview': True}

            log.debug("PERMS RESULT: %s"  % str(perms))
            return perms
      return False
