#!/usr/bin/env python
import CORBA, sys, regex, string, random
from string import split, strip, joinfields
from random import randint
class USERAUTH:   # interface
	currtoken=randint(1,28752)
	def __init__(self):
	        USERAUTH.currtoken=randint(1,28752)
	def validate(self, user, capability):
		if capabilities.has_key(user):
			caplist = split(capabilities[user], ',')
			if (caplist.occurrences(capability) == 0):
				raise SECURITY.USERAUTH.NOTAUTHENTICATED
				return
			if not tokens.has_key(user):
				log("failcap", joinfields(["Tried user/capability:", 
					user, USERAUTH.currtoken], ":"))
				raise SECURITY.USERAUTH.NOTAUTHENTICATED
				return
	def login (self, user, password):
		if pwtable.has_key(user):
			if (password == pwtable[user]):
				USERAUTH.currtoken = (USERAUTH.currtoken * 2 + 
					randint(1,1352)) % 12023
				print "Latest token:", USERAUTH.currtoken
				log("auth", joinfields(["Gave token:", user, 
					"%d" % USERAUTH.currtoken], ":"))
				tokens[user] = USERAUTH.currtoken
				return tokens[user]
			else:
				log("failure", joinfields(["Bad PW:", user, 
					password], ":"))
				raise SECURITY.USERAUTH.NOTAUTHENTICATED
				return
		else:
			print "Bad user!"
			print "ID:", user, "PW:", password
			raise SECURITY.USERAUTH.NOTAUTHENTICATED
			return
def log(type, msg):
  LOGORB.addlog(LOG.loginfo(hostname="knuth", userid="cbbrowne",
			application="security-server",
			messagetype=type,
			shortmessage=msg))

## First, load in the IDs.
f=open("/brownes/knuth/local/src/ORBit/others/dvdcorba/server/ids.txt")
pwtable={}
tokens={}
capabilities={}
while 1:
	line=f.readline()
	if not line: break
	if not (line[0] == "#"):
		(id, password, caps) = split( line, ':')
		id=strip(id)
		pwtable[id] = strip(password)
		capabilities[id]=strip(caps)
for id in pwtable.keys():
	print "ID:", id, " --> ", pwtable[id]

CORBA.load_idl("security.idl")
CORBA.load_idl("/usr/share/idl/name-service.idl")
CORBA.load_idl("logger.idl")
orb = CORBA.ORB_init((), CORBA.ORB_ID)
poa = orb.resolve_initial_references("RootPOA")

logior = open("./logger.ior").readline()
LOGORB = orb.string_to_object(logior)
print LOGORB.__repo_id

LOGORB.addlog(LOG.loginfo(hostname="knuth", userid="cbbrowne",
			application="security-server",
			messagetype="info",
			shortmessage="Start up Security Server"))
servant = POA.SECURITY.USERAUTH(USERAUTH())
poa.activate_object(servant)
ref = poa.servant_to_reference(servant)
open("./security-server.ior", "w").write(orb.object_to_string(ref))

poa.the_POAManager.activate()
orb.run()
