def executeCommand(self,command):
        log("IN command %s" % (command.name))
        table64 = command.getValue("table64")
        
        tableJSON = table64.decode('base64','strict')
        tableDict = json.loads(tableJSON)
        
        #get event ID
        db = mongo.MongoDBComponents(info.dbIP,info.dbPort)
        allEvents = db.find_all(info.dbDefault, info.rootTableCollectionName)
        
        #$to do: need a better way to do this ...
        #max = allEvents.count
        maxEvent = 0
        for ev in allEvents:
            maxEvent += 1;
            
        tableNumber = maxEvent + 1

        # move this block to function ...
        
        tableDict['tableNumber'] = tableNumber
        
        mongo.newMongo(info).save(info.dbDefault,info.rootTableCollectionName, tableDict)

        log("recieved table JSON %s" % (tableJSON) )
        panel = command.getValue("panel")

        s = "Saved new Table Event #%s" % ( str(tableNumber) )

        displayCmd = Command('Display')
        displayCmd.addParameter('panel', panel)
        displayCmd.addParameter('html64', Utils().pack(s) )
        
        command.outCommands.append(displayCmd)       
    def executeCommand(self,command):
        panel = command.getValue("panel")
        usr  = command.getValue("usr").decode('base64','strict')
        pwd =  command.getValue("pwd").decode('base64','strict')
       
        from src.framework import mongo
        userInDB = mongo.MongoDBComponents(info.dbIP,info.dbPort).find_one(info.dbDefault, info.userCollection, {'username': usr } )
        s = strings.NO_SUCH_USER
        if(userInDB):
            #user found
            
            if userInDB['locked']:
                s = strings.ACCOUNT_LOCKED
            elif(userInDB['password'] == pwd):
                #user authenticated
                
                #?reset pwd attempts
                pwdAttempts = int(userInDB['passwordAttempts'])
                if(pwdAttempts > 0):
                    userInDB['passwordAttempts'] = 0
                    mongo.newMongo(info).save(info.dbDefault,info.userCollection, userInDB)
                    
                s = strings.WELCOME + " " + userInDB['username']
                
                """display navigation"""
                showNavigation = Command('ShowNavigation')
                showNavigation.addParameter('panel', panel)
                command.outCommands.append(showNavigation)

                """set session timeout value"""
                setKontext = Command('SetKontext')
                setKontext.addParameter('sessionTimeoutMinutes', info.sessionTimeoutMinutes)
                command.outCommands.append(setKontext)

                """set kredentials"""
                setKreds = Command('SetKontext')
                kredPair = "%s_%s" % ( userInDB['username'], userInDB['password'] )
                setKreds.addParameter('kreds',Utils().pack(kredPair))
                command.outCommands.append(setKreds)
                
            else:
                #bad passowrd
                pwdAttempts = int(userInDB['passwordAttempts'])
                if(pwdAttempts >= info.passwordAttempts):
                    userInDB['locked'] = True
                    s = strings.ACCOUNT_LOCKED
                    log("ACCOUNT LOCKED {0} password attempted > {1} times".format(usr,pwdAttempts))
                else:
                    userInDB['passwordAttempts'] = pwdAttempts + 1
                    s = strings.WRONG_PASSWORD % (str( info.passwordAttempts - pwdAttempts))
                    log("BAD PASSWORD {0} password attempted > {1} times".format(usr,pwdAttempts))
                    
                #save bad password update
                mongo.newMongo(info).save(info.dbDefault,info.userCollection, userInDB)   

       
        displayCmd = Command('Alert')
        displayCmd.addParameter('msg', Utils().pack(s) )
        command.outCommands.append(displayCmd)    
 def passwd(self,username,oldpassword,newpassword,newpasswordConfirm):
    
     if(newpassword != newpasswordConfirm):
         raise NewPasswordMismatchException("passwords did not match")
     
     usr = mongo.MongoDBComponents(info.dbIP,info.dbPort).find_one(info.dbDefault, info.userCollection, {'username': username } )
     
     if(oldpassword != usr['password']):
         raise OldPasswordMismatchException("old password was incorrect")
     
     
     usr['password'] = newpassword
     mongo.newMongo(info).save(info.dbDefault,info.userCollection, usr)
     
     return "password changed"
    def getLeaves(self,node,level=1,visitor=None):

        if node == None:
            return None
        '''
        extract tree leaf nodes only
        ''' 
        #tree been built
        if visitor == None:
            visitor = Visitor()
            
        #visitor.trajectory.append(str(node['name']))   
            
        #print "{0} ({1}) {2}".format(s,level,node["name"] )
        
        if len(node['children']) > 0:
            for childID in node['children']:
                #recurse
                searchTerm = {'_id':childID}
                childNode = mongo.newMongo(self.conf).find_one(self.dbName,self.collectionName,searchTerm)
                self.getLeaves(childNode,level + 1,visitor)
        else:
            visitor.leaves.append( node['_id'] )
                
        return visitor
def targetMongo(dbName,collectionName,searchTerm,conf):

    targetNode = mongo.newMongo(conf).find_one(dbName, collectionName, searchTerm)
    if (targetNode == None):
        raise MongoDocNotFoundException("No MongoDB Node found at {0}/{1}/{2}".format(dbName, collectionName, searchTerm))
    mongoHelper = MongoTreeBuilder(conf, dbName, collectionName)
    return mongoHelper, targetNode
    def append(self,parent,child,conf=None,dbName=None,collectionName=None):

        if conf == None:
            conf = self.conf
        if dbName == None:
            dbName = self.dbName
        if collectionName == None:
            collectionName = self.collectionName
        
        
        child['parent'] = parent['_id']
        child_id = mongo.newMongo(conf).save(dbName,collectionName,child.ToDict())
        parent['children'].append(child_id)
        mongo.newMongo(conf).save(dbName,collectionName,parent)
        
        child['_id'] = child_id
        return child
def initializeUsersAndGroups():
    """ default system setup / initialization script """
    
    username = '******'
    password = '******'
    groupname = 'administrators'
    
    msgs = []
    
    userCollection = config.userCollection
    groupCollection = config.groupCollection
    
    pwdEncryped = Utils().md5encode(password)
    
    
    usr = mongo.MongoDBComponents(config.dbIP,config.dbPort).find_one(config.dbDefault, userCollection, {'username': username } )
    if usr:
        msgs.append( '%s user already setup - %s' % (username,usr['_id']))
    else:

        u = User(None, {'username':username,'password':pwdEncryped,'description':'base administrator account'})
        usrID = mongo.newMongo(config).save(config.dbDefault,userCollection, u)
        msgs.append( 'created new user %s with objectID %s' % (username,usrID))
        usr = mongo.MongoDBComponents(config.dbIP,config.dbPort).find_one(config.dbDefault, userCollection, {'username': username } )
    
    grp = mongo.MongoDBComponents(config.dbIP,config.dbPort).find_one(config.dbDefault, groupCollection, {'groupname': groupname } )
    if grp:
        msgs.append( '%s group already setup %s' % (groupname,grp['_id']))
    else:
        g = Group(None, {'groupname':groupname,'description':'admin group'})
        grpID = mongo.newMongo(config).save(config.dbDefault,groupCollection, g)
        msgs.append( 'created new group %s with objectID %s' % (groupname,grpID) )
        grp = mongo.MongoDBComponents(config.dbIP,config.dbPort).find_one(config.dbDefault, groupCollection, {'groupname': groupname } )

   
    
    if( usr['_id'] in grp['users']):
        msgs.append( 'user [%s] is already in group [%s]' % (username,groupname))
    else:
        
        grp['users'].append(usr['_id'])
        mongo.newMongo(config).save(config.dbDefault,groupCollection, grp)
        msgs.append( 'added user to group')
    
    return msgs
    def printtree(self,node,level=1):

        s = ""
        for i in range(level*self.PRETTY_PRINT_SPACING):
            s = s + "    "
        try:    
            print "{0} ({1}) {2}".format(s,config.levels[level-1],node["name"] )
        except:
            print "error printing tree"
            return

        for childID in node['children']:
            searchTerm = {'_id':childID}
            childNode = mongo.newMongo(self.conf).find_one(self.dbName,self.collectionName,searchTerm)
            self.printtree(childNode,level + 1)
 def obtainPathToRoot(self,node,visitor=None):
     if(visitor == None): visitor = Visitor()
     visitor.trajectory.append(node)
     
     parent = node['parent']
    
     if(parent==None):
         return visitor
     else:
         searchTerm = {'_id':parent}
         p = mongo.newMongo(self.conf).find_one(self.dbName,self.collectionName,searchTerm)
         if(p != None):
             return self.obtainPathToRoot(p, visitor)
         else:
             raise MongoTreeCorruptException("Node [{0}] was not found".format(searchTerm))
             return visitor
    def loadComposite(self,node,level=1,visitor=None,parent=None):

        #build and load a dictionary style tree
         
        if visitor == None:
            visitor = Visitor()
            r = MNode(node)
            visitor.compositeRoot = r
            parent = r
        else:
            parent.appendChild(node) 
            parent = node

        if(level > visitor.compositeLevels): visitor.compositeLevels = level
        
        for childID in node['children']:
            
            searchTerm = {'_id':childID}
            childNode = mongo.newMongo(self.conf).find_one(self.dbName,self.collectionName,searchTerm)
            c = MNode(childNode)
            self.loadComposite(c,level + 1,visitor,parent)
                
        return visitor