add user-related DB Storage & Manager

ref #3078

Change-Id: Idd0272f501545a9e8fa156008400b42cf0ea10ef
diff --git a/device_storage.py b/device_storage.py
index 3de7c54..85ad39e 100644
--- a/device_storage.py
+++ b/device_storage.py
@@ -78,7 +78,7 @@
 
 class DeviceStorage(object):
     """
-    Create a new DeviceUserStorage to work with an SQLite file.
+    Create a new DeviceStorage to work with an SQLite file.
     :param str databaseFilePath: (optional) The path of the SQLite file. If ommitted, use the default path.
     """
     def __init__(self, databaseFilePath = None):
@@ -95,6 +95,7 @@
             databaseFilePath = os.path.join(dbDirectory, 'ndnhome-controller.db')
 
         self._database =  sqlite3.connect(databaseFilePath)
+        self._database.text_factory = str
         
         #Check if the Device table exists
         cursor = self._database.cursor()
@@ -471,7 +472,9 @@
         #if not count > 0:
             #return None
         cursor.execute(operation, (deviceId,))
-        result = cursor.fetchall()                    
+        result = cursor.fetchall()
+        cursor.close()
+                    
         #print result
         commandList = []
         if result == None:
@@ -482,6 +485,65 @@
     
         return commandList
 
+    def getCommandIdsOfDevice(self, deviceId):
+        """
+        get all the id of  commands of a specified device
+        :param int deviceId: device id of the command
+        :return command id list if any commands exist, otherwise None
+
+        """
+        operation = "SELECT id FROM Command WHERE device_id = ?"
+       
+        cursor = self._database.cursor()
+        
+        cursor.execute(operation, (deviceId,))
+        result = cursor.fetchall()
+        cursor.close()
+
+        #print result
+        commandIdList = []
+        if result == None:
+           return commandIdList
+        else:
+           for row in result:
+               commandIdList.append(row[0])
+
+        return commandIdList
+
+    def getCommandId(self, deviceId, commandName):
+        """
+        get the id of a specified command
+        :param int deviceId: device id of the command
+        :param str commandName: command name  
+        :return command id if the command exist, otherwise 0
+        """
+        operation = "SELECT id FROM Command WHERE device_id=? AND name=?"
+        cursor = self._database.cursor()
+        cursor.execute(operation,(deviceId,commandName))
+        result = cursor.fetchone()
+        cursor.close()
+       
+        if result == None:
+            return 0
+        commandId = result[0]
+        return commandId
+
+    def getCommandNameFromId(self, commandId):
+        """
+        get command Name given a command id
+        :param int commandId: command id
+        :return command name        
+        :rtype str
+        """
+        operation = "SELECT name from Command WHERE id = ?"
+        cursor =  self._database.cursor()
+        cursor.execute(operation,(commandId,))
+        result = cursor.fetchone()
+        if result == None:
+            return None
+        commandName = result[0]
+        return commandName
+
     def getCommandToken(self, deviceId, commandName):
         """
         get command token of a specified command 
@@ -494,6 +556,8 @@
         cursor = self._database.cursor()
         cursor.execute(operation, (deviceId, commandName))
         result = cursor.fetchone()
+        cursor.close()
+
         if result == None:
             return None
         else:
diff --git a/device_user_access_manager.py b/device_user_access_manager.py
index 1d14c73..4fcc0a9 100644
--- a/device_user_access_manager.py
+++ b/device_user_access_manager.py
@@ -23,18 +23,24 @@
 """
 
 import sys
+import hmac
+from hashlib import sha256
 from pyndn.name import Name
 from device_profile import DeviceProfile
 from device_storage import DeviceStorage
+from hmac_key import HMACKey
+from user_access_storage import UserAccessStorage
 
 class DeviceUserAccessManager(object):
     """
     Create a new DeviceUserAccessManager
     """
     def __init__(self, databaseFilePath = None):
-        deviceUserAccessStorage = DeviceStorage(databaseFilePath)
-        self._deviceUserAccessStorage = deviceUserAccessStorage
-    
+        deviceStorage = DeviceStorage(databaseFilePath)
+        self._deviceStorage = deviceStorage
+        userAccessStorage  = UserAccessStorage(databaseFilePath)
+        self._userAccessStorage =  userAccessStorage 
+ 
     def createDevice(self, deviceProfile, seed, configurationToken, commandList = None):
         """
         Create a device in the database, including it's corresponding commands and serrvice profiles
@@ -47,7 +53,7 @@
         result = False
 
         #add device
-        deviceId =  self._deviceUserAccessStorage.addDevice(deviceProfile, seed, configurationToken)  
+        deviceId =  self._deviceStorage.addDevice(deviceProfile, seed, configurationToken)  
         if deviceId == 0:
            raise RuntimeError("device already exists in database") 
            return result
@@ -58,16 +64,23 @@
         #add service profile
         serviceProfileList = deviceProfile.getServiceProfileList()
         for serviceProfileName in serviceProfileList:
-            serviceProfileId = self._deviceUserAccessStorage.addServiceProfile(deviceId, serviceProfileName)
+            serviceProfileId = self._deviceStorage.addServiceProfile(deviceId, serviceProfileName)
             if serviceProfileId == 0:
                 raise RuntimeError("service profile: " + serviceProfileName + " already exists in database")
                 return result
             elif serviceProfileId == -1:
                 raise RuntimeError("error occured during adding service profile :" + serviceProfileName)
                 return result
+
         #add command
-        for commandTuple in commandList:
-            commandId = self._deviceUserAccessStorage.addCommand(deviceId, commandTuple[0], commandTuple[1])
+        for command in commandList:
+            #generate command token,firstt generate command token name
+            prefix = deviceProfile.getPrefix()
+            commandTokenName = prefix.toUri()+"/"+command+"/token/0"
+            commandTokenKey = hmac.new(seed.getKey(), commandTokenName,sha256).digest()
+            commandToken = HMACKey(0,0,commandTokenKey,commandTokenName)
+
+            commandId = self._deviceStorage.addCommand(deviceId, command, commandToken)
             if commandId == 0:
                 raise RuntimeError("command: " + commandTuple[0] + " already exists in database")
                 return result
@@ -84,16 +97,16 @@
         :return device profile of the device if exists, otherwise return None
         :rtype: DeviceProfile
         """
-        deviceProfile = self._deviceUserAccessStorage.getDeviceProfileFromDevice(prefix)
+        deviceProfile = self._deviceStorage.getDeviceProfileFromDevice(prefix)
         if deviceProfile == None:
             return deviceProfile
         else:
             # get device Id 
-            deviceId = self._deviceUserAccessStorage.getDeviceId(deviceProfile.getPrefix())
+            deviceId = self._deviceStorage.getDeviceId(deviceProfile.getPrefix())
             if deviceId == 0:
                 raise RuntimeError("device doesn't exist")
              
-            serviceProfileList = self._deviceUserAccessStorage.getServiceProfilesOfDevice(deviceId)
+            serviceProfileList = self._deviceStorage.getServiceProfilesOfDevice(deviceId)
             deviceProfile.setServiceProfile(serviceProfileList)
        
         return deviceProfile
@@ -105,7 +118,7 @@
         :return seed of the device if exists, otherwise return None
         :rtype: SymmetricKey
         """
-        return self._deviceUserAccessStorage.getSeed(prefix)
+        return self._deviceStorage.getSeed(prefix)
 
     def getConfigurationToken(self, prefix):
         """
@@ -114,7 +127,7 @@
         :return seed of the device if exists, otherwise return None
         :rtype: SymmetricKey
         """
-        return self._deviceUserAccessStorage.getConfigurationToken(prefix)
+        return self._deviceStorage.getConfigurationToken(prefix)
 
     def getCommandToken(self, prefix, commandName):
         """
@@ -124,10 +137,10 @@
         :return command token if command existsm, otherwise None
         :rtype SymmetricKey
         """
-        deviceId = self._deviceUserAccessStorage.getDeviceId(prefix)
+        deviceId = self._deviceStorage.getDeviceId(prefix)
         if deviceId == 0:
             return None
-        return self._deviceUserAccessStorage.getCommandToken(deviceId, commandName)
+        return self._deviceStorage.getCommandToken(deviceId, commandName)
 
     def getCommandsOfDevice(self, prefix):
         """
@@ -135,10 +148,10 @@
         :param Name prefix: the device prefix
         :return command name list if any commands exist, otherwise None
         """
-        deviceId = self._deviceUserAccessStorage.getDeviceId(prefix)
+        deviceId = self._deviceStorage.getDeviceId(prefix)
         if deviceId == 0:
             return None
-        return self._deviceUserAccessStorage.getCommandsOfDevice(deviceId)
+        return self._deviceStorage.getCommandsOfDevice(deviceId)
     
     def getServiceProfilesOfDevice(self, prefix):
         """
@@ -146,8 +159,88 @@
         :param Name prefix: the device prefix
         :return service profiles name list if any service profiles exist, otherwise None
         """
-        deviceId = self._deviceUserAccessStorage.getDeviceId(prefix)
+        deviceId = self._deviceStorage.getDeviceId(prefix)
         if deviceId == 0:
             return None
-        return self._deviceUserAccessStorage.getServiceProfilesOfDevice(deviceId)
-    
+        return self._deviceStorage.getServiceProfilesOfDevice(deviceId)
+ 
+    def addUser(self, prefix, username, hash_, salt, type_):
+        """ 
+        Add a new user to User table, do nothing if the user already exists
+        
+        :param Name prefix: the prefix of the user
+        :param str username: username
+        :param hash_: 
+        :param salt: 
+        :param str type: the type of user, either guest or user
+        :return the user id if it's added successfully, 0 if prefix conflict exists, -1 if username conflict exists
+        :rtype: INTEGER
+        """
+        return self._userAccessStorage.addUser(prefix, username, hash_, salt, type_)
+
+    def addAccess(self, devicePrefix, commandName, userPrefix, userDevice, accessToken):
+        """ 
+        Add a new access to the Access table, do nothing if the access already exists
+        :param Name devicePrefix: the device prefix
+        :param str command name : the command name
+        :param Name userPrefix: the user prefix
+        :param int userDevice: the user device
+        :param HMACKey accessToken: the access token
+        :return the access id if it's added successfully, 0 if the access already exists, otherwise -1
+        :rtype: int
+        """
+        #get device Id
+        deviceId = self._deviceStorage.getDeviceId(devicePrefix)
+        if deviceId == 0:
+            print 1
+            return -1
+        
+        #get command id
+        commandId = self._deviceStorage.getCommandId(deviceId, commandName)
+        if commandId == 0:
+            print 2
+            return -1
+
+        #get user id 
+        userId = self._userAccessStorage.getUserId(userPrefix)
+        if userId ==0:
+            print 3
+            return -1 
+       
+        return self._userAccessStorage.addAccess(commandId, userId, userDevice, accessToken)
+  
+    def getAccessInfo(self, userPrefix, devicePrefix):
+        """
+        get all aceess info for pair(user, device)
+        :param Name userPrefix: the prefix of user
+        :param Name devicePrefix: the prefix of device
+        :return a list of tuples of form (str commandName,str userDevice, HmacKey accessToken). e.g. [('turn_on','laptop'. AccessToken1), ('turn_off','laptop' AccessToken2)], return None if no such access exists     
+        :rtype list 
+        """
+        #get device Id
+        deviceId = self._deviceStorage.getDeviceId(devicePrefix)
+        
+        #get user Id 
+        userId = self._userAccessStorage.getUserId(userPrefix)
+        
+        if userId <= 0 or deviceId <= 0:
+            #either user or device doesn't exist in table 
+            return None
+     
+       #get command id list of device 
+        commandIdList = self._deviceStorage.getCommandIdsOfDevice(deviceId)
+        if commandIdList == []:
+           return None
+       
+        accessList =[]
+        for commandId in commandIdList:
+            doesExist = self._userAccessStorage.doesAccessExist(commandId, userId)
+            if doesExist: 
+                commandName = self._deviceStorage.getCommandNameFromId(commandId)
+                userDeviceList =  self._userAccessStorage.getUserDevices(commandId, userId)
+                for userDevice in userDeviceList:
+                     accessToken = self._userAccessStorage.getAccessToken(commandId, userId, userDevice)
+                     accessTuple  =  (commandName, userDevice, accessToken)
+                     accessList.append(accessTuple)
+        
+        return accessList
diff --git a/fill_database_for_test.py b/fill_database_for_test.py
index 9a021a3..a8838e9 100644
--- a/fill_database_for_test.py
+++ b/fill_database_for_test.py
@@ -22,6 +22,7 @@
 from pyndn import Name
 from device_storage import DeviceStorage
 from device_profile import DeviceProfile
+from user_access_storage import UserAccessStorage
 from hmac_key import HMACKey
 
 
@@ -43,28 +44,46 @@
             os.remove(self.databaseFilePath)
 
         self.storage = DeviceStorage()
-
+        self.userStorage = UserAccessStorage()
     def fillDatabase(self):
         count = self.count
         prefixStrBase = 'home/sensor/LED/'
         serviceProfileNameBase = '/standard/sensor/simple-LED-control/v'
         commandNameBase = 'turn_on'
         commandNameBase2 = 'turn_off'
+
+        prefixBase = '/home'  
+        hash_ = 'EEADFADSFAGASLGALS'
+        salt = 'adfafdwekldsfljcdc'
+        type_ = 'guest'
+
         for i in range(1, count+1):
+             #add device 
              prefixStr = prefixStrBase + str(i)
              self.add_a_default_device(prefixStr)
              name = Name(prefixStr)
              deviceId = self.storage.getDeviceId(name)
+             #add service profile
              serviceProfileName = serviceProfileNameBase + str(i)
              self.storage.addServiceProfile(deviceId, serviceProfileName)
-
+             #add command
              commandName = commandNameBase + str(i)
              commandName2 = commandNameBase2 + str(i)
              commandToken = self.create_a_default_key(commandName)
              commandToken2 = self.create_a_default_key(commandName2)
              self.storage.addCommand(deviceId, commandName, commandToken)
              self.storage.addCommand(deviceId,commandName2,commandToken2)
-
+             #add user
+             username = 'user' + str(i)
+             prefixStr =prefixBase +'/' + username
+             prefixName = Name(prefixStr)
+             self.userStorage.addUser(prefixName, username, hash_, salt, type_)
+           
+             #add access
+             accessTokenName = 'accessToken' + str(i)
+             accessToken = self.create_a_default_key(accessTokenName)
+             self.userStorage.addAccess(i, i, 'laptop', accessToken )
+             
     def add_a_default_device(self, prefixStr):
         name = Name(prefixStr)
         profile = DeviceProfile(prefix = name)
diff --git a/hmac_key.py b/hmac_key.py
index 98d1b51..d5b032a 100644
--- a/hmac_key.py
+++ b/hmac_key.py
@@ -20,7 +20,7 @@
     """
     HMACKey implements the  HMAC symmetric key
     """
-    def __init__(self, sequence, counter, key, name = None):
+    def __init__(self, sequence = None, counter = None, key = None, name = None):
         self._name = name
         self._sequence = sequence
         self._counter = counter
diff --git a/show_accesses.py b/show_accesses.py
new file mode 100644
index 0000000..4c971dc
--- /dev/null
+++ b/show_accesses.py
@@ -0,0 +1,52 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2014-2015 Regents of the University of California.
+# Author: Weiwei Liu <summerwing10@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+# A copy of the GNU Lesser General Public License is in the file COPYING.
+
+import sys
+import os
+import sqlite3
+from user_access_storage import UserAccessStorage
+
+def showDefault(databaseFilePath = None):
+    if databaseFilePath == None or databaseFilePath == "":
+        if not "HOME" in os.environ:
+            home = '.'
+        else:
+            home = os.environ["HOME"]
+
+        dbDirectory = os.path.join(home, '.ndn')
+        if not os.path.exists(dbDirectory):
+            os.makedirs(dbDirectory)
+
+        databaseFilePath = os.path.join(dbDirectory, 'ndnhome-controller.db')
+
+        database =  sqlite3.connect(databaseFilePath)
+
+        cursor = database.cursor()
+        cursor.execute("SELECT command_id, user_id, user_device, access_token_name FROM Access")
+        print 'command id:  user id:     user_device,     access token name:'
+        for row in cursor.fetchall():
+            print '%d            %d            %s           %s' %(row[0], row[1], row[2], row[3])
+        cursor.close()
+
+if len(sys.argv) < 2:
+    showDefault()
+
+else:
+    raise RuntimeError("options is not implemented yet")
+
diff --git a/show_users.py b/show_users.py
new file mode 100644
index 0000000..49da51c
--- /dev/null
+++ b/show_users.py
@@ -0,0 +1,52 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2014-2015 Regents of the University of California.
+# Author: Weiwei Liu <summerwing10@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+# A copy of the GNU Lesser General Public License is in the file COPYING.
+
+import sys
+import os
+import sqlite3
+from user_access_storage import UserAccessStorage
+
+def showDefault(databaseFilePath = None):
+    if databaseFilePath == None or databaseFilePath == "":
+        if not "HOME" in os.environ:
+            home = '.'
+        else:
+            home = os.environ["HOME"]
+
+        dbDirectory = os.path.join(home, '.ndn')
+        if not os.path.exists(dbDirectory):
+            os.makedirs(dbDirectory)
+
+        databaseFilePath = os.path.join(dbDirectory, 'ndnhome-controller.db')
+
+        database =  sqlite3.connect(databaseFilePath)
+        
+        cursor = database.cursor()
+        cursor.execute("SELECT id, prefix, type FROM User")
+        print 'id:     prefix:          type:'
+        for row in cursor.fetchall():
+            print '%d      %s       %s' %(row[0], row[1], row[2])
+        cursor.close()
+
+if len(sys.argv) < 2:
+    showDefault()
+
+else:
+    raise RuntimeError("options is not implemented yet")
+
diff --git a/tests/test_manager.py b/tests/test_manager.py
index 710aa79..07083bf 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -53,7 +53,7 @@
         self.manager = DeviceUserAccessManager()
         self.assertTrue(os.path.isfile(self.databaseFilePath), 'fail to create database file')
 
-    def test_02_methods(self):
+    def test_02_device_methods(self):
         #create device
         prefixStr = '/home/sensor/LED/1'
         name = Name(prefixStr)
@@ -65,16 +65,11 @@
         keyContent = 'this is key content'
         seedName = 'led1'
         seed =  HMACKey( 0, 0 ,keyContent, seedName)
-        configurationToken =  HMACKey(0, 0, keyContent)
-        commandTokenName1 = 'commandToken1'
-        commandTokenName2 = 'commandToken2'
-        commandToken = HMACKey(0,0, keyContent, commandTokenName1)
-        commandToken2 = HMACKey(0,0,keyContent, commandTokenName2)
+        configurationToken =  HMACKey(0, 0, keyContent) 
+  
         commandName1 = 'turn_on'
-        commandName2 = 'turn_off'
-        commandTuple = (commandName1, commandToken)
-        commandTuple2 = (commandName2, commandToken2)
-        commandList =  [commandTuple, commandTuple2]
+        commandName2 = 'turn_off' 
+        commandList =  [commandName1, commandName2]
         result = self.manager.createDevice(profile, seed, configurationToken, commandList)
         self.assertTrue(result, 'fail to create device')
        
@@ -92,8 +87,11 @@
         self.assertTrue(configurationToken.getKey()== keyContent, 'wrong configration token')
        
         #getCommandToken()
-        commandToken1 = self.manager.getCommandToken(name, commandName1 )
+        commandToken1 = self.manager.getCommandToken(name, commandName1)
         commandToken2 = self.manager.getCommandToken(name, commandName2)
+        commandTokenName1 = name.toUri()+"/"+ commandName1 +"/token/0"
+        commandTokenName2 = name.toUri()+"/"+ commandName2 +"/token/0"
+
         self.assertTrue(commandToken1.getName() == commandTokenName1, 'wrong commandToken')
         self.assertTrue(commandToken2.getName() == commandTokenName2, 'wrong commandToken')
  
@@ -107,7 +105,56 @@
         self.assertTrue(serviceProfileList[0] in serviceProfileListReturned, 'service profile:' + serviceProfileList[0] + ' not found')
         self.assertTrue(serviceProfileList[1] in serviceProfileListReturned, 'service profile:' + serviceProfileList[1] + ' not found')
 
+    def test_03_user_access_methods(self):
+        #prerequisite: add device and command
+        devicePrefixStr = '/home/sensor/LED/1'
+        devicePrefix = Name(devicePrefixStr)
+        self.create_a_default_device(devicePrefix)
+        
+        #add user
+        username = 'user1'
+        userPrefixBase = '/home'
+        userPrefixStr = userPrefixBase + '/' + username
+        userPrefix = Name(userPrefixStr)
+        hash_ = 'EEADFADSFAGASLGALS'
+        salt = 'adfafdwekldsfljcdc'
+        type_ = 'guest'    
+        result = self.manager.addUser(userPrefix, username, hash_, salt, type_)
+        self.assertTrue(result > 0, 'fail to add user')
+       
+        #add access
+        commandName = 'turn_off'
+        userDevice = 'laptop'
+        keyContent = 'this is key content'
+        accessToken =  HMACKey(0, None, keyContent, 'accessToken1')
+        result = self.manager.addAccess(devicePrefix, commandName, userPrefix, userDevice, accessToken)
+        self.assertTrue(result > 0, 'fail to add acces')
 
+        #get access info 
+        accessList = self.manager.getAccessInfo(userPrefix,devicePrefix)
+        row = accessList[0]
+        self.assertTrue(row[0] == commandName, 'wrong access info: command name')
+        self.assertTrue(row[1] == userDevice, 'wrong access info: user device')
+        self.assertTrue(row[2].getName() == 'accessToken1', 'wrong access info: access token')
+
+    def create_a_default_device(self, prefixName):
+        """
+        create a default device with specified device prefix name and with two default commands 'turn_on' and 'turn_off'
+        """
+
+        name = prefixName
+        profile = DeviceProfile(prefix = name)      
+        keyContent = 'this is key content'
+        seedName = 'led1'
+        seed =  HMACKey( 0, 0 ,keyContent, seedName)
+        configurationToken =  HMACKey(0, 0, keyContent)  
+        commandName1 = 'turn_on'
+        commandName2 = 'turn_off'
+        commandList =  [commandName1, commandName2]
+        result = self.manager.createDevice(profile, seed, configurationToken, commandList)
+        self.assertTrue(result, 'fail to create device')
+        
+        
 if __name__ == '__main__':
     ut.main(verbosity=2)
 
diff --git a/tests/test_user_access_storage.py b/tests/test_user_access_storage.py
new file mode 100644
index 0000000..e060b1f
--- /dev/null
+++ b/tests/test_user_access_storage.py
@@ -0,0 +1,231 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2014 Regents of the University of California.
+# Author: Weiwei Liu <summerwing10@gmail.com>
+# 
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser 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/>.
+# A copy of the GNU General Public License is in the file COPYING.
+
+import unittest as ut
+import os.path
+from pyndn import Name
+from user_access_storage import UserAccessStorage
+from device_profile import DeviceProfile
+from hmac_key import HMACKey
+
+class TestUserAccessStorageMethods(ut.TestCase):
+    def setUp(self):
+        if not "HOME" in os.environ:
+            home = '.'
+        else:
+            home = os.environ["HOME"]
+
+        dbDirectory = os.path.join(home, '.ndn')
+        self.databaseFilePath = os.path.join(dbDirectory, 'ndnhome-controller.db')
+
+        if os.path.isfile(self.databaseFilePath):
+            os.remove(self.databaseFilePath)
+        
+        self.storage = UserAccessStorage()
+
+    def tearDown(self):
+        pass
+    
+    def test_01_storage_constructor(self):
+        
+        self.assertTrue(os.path.isfile(self.databaseFilePath), 'fail to create database file')        
+        self.assertTrue(self.storage.doesTableExist("User"), "Device table doesn't exist")  
+        self.assertTrue(self.storage.doesTableExist("Access"), "Command table doesn't exist")
+        
+        #test constructor with file path HOME/.ndn/homedb 
+        home = os.environ["HOME"]
+        dir = os.path.join(home, '.ndn')
+        dbdir = os.path.join(dir, 'homedb')
+        
+        if not os.path.exists(dbdir):
+                os.makedirs(dbdir)
+       
+        filePath = os.path.join(dbdir, 'ndnhome-controller.db')
+        storage2 = UserAccessStorage(filePath)
+        self.assertTrue(os.path.isfile(filePath), 'fail to create database file' )
+        os.remove(filePath)
+   
+    def test_02_entry_existence_methods(self):
+        # test the existence of non-existed user (prefix = /home/weiwei)
+        username = 'weiwei'
+        prefixBase = '/home'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)                
+        result1 = self.storage.doesUserExistByPrefix(prefixName)
+        result2 = self.storage.doesUserExistByUsername(username)
+        self.assertFalse(result1, "user with prefix '" + prefixStr +  "' shouldn't exist")
+        self.assertFalse(result2, "user with username '" + username + "' shouldn't exist")
+
+        #test existence of an existed user
+        self.add_a_default_user(username)  
+        result1 = self.storage.doesUserExistByPrefix(prefixName)
+        result2 = self.storage.doesUserExistByUsername(username)
+
+        self.assertTrue(result1, "user with prefix '" + prefixStr +  "' should exist")
+        self.assertTrue(result2, "user with username '" + username + "' should exist")
+
+        #test the existence of a non-existed access 
+        commandId = 1
+        userId = 1 
+        result = self.storage.doesAccessExist(commandId, userId)
+        self.assertFalse(result, "access shouldn't exist with a empty Access table")
+
+        #test the exitence of an existed access
+        accessToken = self.create_a_default_access_token('user1_command1')
+        self.storage.addAccess(1,1, 'laptop', accessToken)
+        result = self.storage.doesAccessExist(commandId, userId)
+        self.assertTrue(result, "access should exist")
+
+    def test_03_add_user(self):
+        username = 'weiwei'
+        prefixBase = '/home'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)
+        hash_ = 'EEADFADSFAGASLGALS'
+        salt = 'adfafdwekldsfljcdc'
+        type_ = 'guest'
+
+        result = self.storage.addUser(prefixName, username, hash_, salt, type_)
+
+        self.assertTrue(result > 0, 'fail to add user')             
+        self.assertTrue(self.storage.doesUserExistByPrefix(prefixName), "user doesn't exist in table")        
+        row = self.storage.getUserEntry(prefixName)
+
+        self.assertTrue(row[1] == prefixStr, "column prefix has incorrect value")
+        self.assertTrue(row[2] == username, "column username has incorrect value ")
+        self.assertTrue(row[3] == hash_, 'colum hash has incorrect value')
+        self.assertTrue(row[4] == salt, 'colum salt has incorrect value')
+        self.assertTrue(row[5] == type_, 'column type_ has incoorect value')
+        
+        #try to insert the same device
+        result = self.storage.addUser(prefixName, username, hash_, salt, type_)
+        self.assertTrue(result == 0, 'unexpected result when trying to insert an already existed user')
+
+    def test_04_delete_user(self):
+        username = 'user1'
+        self.add_a_default_user(username)
+        prefixBase = '/home'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)
+       
+        self.assertTrue(self.storage.doesUserExistByPrefix(prefixName), "user doesn't exist in table")
+        result = self.storage.deleteUser(prefixName)       
+        self.assertTrue(result == 1, 'fail to delete device')
+
+    def test_05_get_userid(self):
+        username = 'user1'
+        self.add_a_default_user(username) 
+        prefixBase = '/home'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)
+
+        userId = self.storage.getUserId(prefixName)
+        self.assertTrue(userId==1, "get a wrong user id")
+        
+        username = 'user2'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)
+        self.add_a_default_user(username)
+
+        userId = self.storage.getUserId(prefixName)
+        self.assertTrue(userId==2, "get a wrong user id")
+
+    def test_06_update_user(self):
+        username = 'user1'
+        self.add_a_default_user(username)
+        prefixBase = '/home'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)
+
+        #update hash_ salt, type_ value of user 
+        newHash = 'NNNMMHGFGKUOIPRT'
+        newSalt = 'kjkjfioewprwerke'
+        newType = 'user'
+        self.storage.updateUser(prefixName, newHash, newSalt, newType)
+        row = self.storage.getUserEntry(prefixName)
+        self.assertTrue(row[3] == newHash, "fail to update column: hash")
+        self.assertTrue(row[4] == newSalt, "fail to update column: salt")
+        self.assertTrue(row[5] == newType, "fail to update column: type")
+
+    def test_07_add_access(self):
+        username = 'user1'
+        self.add_a_default_user(username)
+
+        accessToken = self.create_a_default_access_token('user1_command1')
+        self.storage.addAccess(1,1, 'laptop', accessToken)        
+        result = self.storage.doesAccessExist(1, 1)
+        self.assertTrue(result == True, "fail to add command")
+
+    def test_08_delete_access(self):
+        username = 'user1'
+        self.add_a_default_user(username)
+
+        accessToken = self.create_a_default_access_token('user1_command1')
+        self.storage.addAccess(1,1, 'laptop', accessToken) 
+
+        self.assertTrue(self.storage.doesAccessExist(1, 1), 'before delete, the command should exist')
+        self.storage.deleteAccess(1, 1)
+        self.assertFalse(self.storage.doesAccessExist(1, 1), "after delete, the command shouldn't exist")
+
+    def test_09_get_commands_of_user(self):        
+        accessToken = self.create_a_default_access_token('token1')
+        self.storage.addAccess(1,1, 'laptop', accessToken)
+        self.storage.addAccess(1,1, 'desktop', accessToken)
+        self.storage.addAccess(2,1,'laptop', accessToken)
+        self.storage.addAccess(2,1, 'desktop', accessToken)
+        result = self.storage.getCommandsOfUser(1)
+        self.assertTrue(result == [1,2], 'wrong command list returned')
+
+    def test_10_get_access_token(self):
+        accessTokenName1 =  'accessToken1'
+        accessTokenName2 = 'accessToken2'
+        accessToken1 = self.create_a_default_access_token(accessTokenName1)
+        accessToken2 = self.create_a_default_access_token(accessTokenName2)
+        userDevice1 = 'laptop'
+        userDevice2 = 'desktop'
+        accessId1 = self.storage.addAccess(1,1, userDevice1, accessToken1)
+        accessId2 = self.storage.addAccess(1,1, userDevice2, accessToken2)
+        
+        if accessId1 <= 0 or accessId2 <= 0:
+            raise RuntimeError('fail to add access') 
+        result1 = self.storage.getAccessToken(1,1, userDevice1)
+        result2 = self.storage.getAccessToken(1,1, userDevice2)
+        if result1 == None or result2 == None:
+            self.assertTrue(False, 'no access returned')
+        self.assertTrue(result1.getName() == accessTokenName1, 'wrong access token returned')
+        self.assertTrue(result2.getName() == accessTokenName2, 'wrong access token returned')
+    
+    def add_a_default_user(self, username):
+        prefixBase = '/home'
+        prefixStr =prefixBase +'/' + username
+        prefixName = Name(prefixStr)
+        hash_ = 'EEADFADSFAGASLGALS'
+        salt = 'adfafdwekldsfljcdc'
+        type_ = 'guest'
+
+        self.storage.addUser(prefixName, username, hash_, salt, type_)
+
+    def create_a_default_access_token(self, keyName = None):
+        keyContent = 'this is key content'
+        accessToken = HMACKey(sequence = 0, key = keyContent, name = keyName)
+        return accessToken
+         
+if __name__ == '__main__':
+    ut.main(verbosity=2)
+ 
diff --git a/user_access_storage.py b/user_access_storage.py
new file mode 100644
index 0000000..3e108ef
--- /dev/null
+++ b/user_access_storage.py
@@ -0,0 +1,402 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2014 Regents of the University of California.
+# Author: Teng Liang <philoliang2011@gmail.com> 
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser 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/>.
+# A copy of the GNU General Public License is in the file COPYING.
+"""
+UserAccessStorage implements a basic storage of users and access 
+"""
+
+import os
+import sqlite3
+from pyndn import Name
+from device_profile import DeviceProfile
+from hmac_key import HMACKey
+
+INIT_USER_TABLE = ["""
+CREATE TABLE IF NOT EXISTS
+  User(
+      id                             INTEGER,
+      prefix                         BLOB NOT NULL UNIQUE,
+      username                      BLOB NOT NULL UNIQUE,
+      hash                           BLOB NOT NULL,
+      salt                           BLOB NOT NULL,
+      type                           BLOB NOT NULL,
+      
+      PRIMARY KEY (id)
+  );
+"""]
+
+INIT_ACCESS_TABLE = ["""
+CREATE TABLE IF NOT EXISTS
+  Access(
+      id                             INTEGER,
+      command_id                     INTEGER,
+      user_id                        INTEGER,
+      user_device                    BLOB NOT NULL,
+      access_token_name              BLOB,
+      access_token_sequence          INTEGER NOT NULL,
+      access_token                   BLOB NOT NULL,
+      
+      PRIMARY KEY (id)
+      FOREIGN KEY(command_id) REFERENCES Command(id)
+      FOREIGN KEY(user_id) REFERENCES User(id)
+  );
+"""]
+
+class UserAccessStorage(object):
+    """
+    Create a new UserAccessStorage to work with an SQLite file.
+    :param str databaseFilePath: (optional) The path of the SQLite file. If ommitted, use the default path.
+    """
+    def __init__(self, databaseFilePath = None):
+        if databaseFilePath == None or databaseFilePath == "":
+            if not "HOME" in os.environ:
+                home = '.'
+            else:
+                home = os.environ["HOME"]
+
+            dbDirectory = os.path.join(home, '.ndn')
+            if not os.path.exists(dbDirectory):
+                os.makedirs(dbDirectory)
+
+            databaseFilePath = os.path.join(dbDirectory, 'ndnhome-controller.db')
+
+        self._database =  sqlite3.connect(databaseFilePath)
+      
+        #Check if the User table exists
+        cursor = self._database.cursor()
+        cursor.execute("SELECT name FROM sqlite_master WHERE TYPE ='table' and NAME = 'User'")
+        if cursor.fetchone() == None:
+            #no device table exists, create one
+            for command in INIT_USER_TABLE:
+                self._database.execute(command)
+        cursor.close()
+
+        #Check if the Access table exists
+        cursor = self._database.cursor()
+        cursor.execute("SELECT name FROM sqlite_master WHERE TYPE ='table' and NAME = 'Access'")
+        if cursor.fetchone() == None:
+            #no device table exists, create one
+            for command in INIT_ACCESS_TABLE:
+                self._database.execute(command)
+        cursor.close()
+
+        self._database.commit()
+
+    def doesTableExist(self, tableName):
+        """
+        check if table exists
+        :param str tableName
+        :return True if exists, otherwise False
+        """
+        selectOperation = "SELECT name FROM sqlite_master WHERE TYPE='table' and NAME='" + tableName +"'"
+        #print selectOperation
+        cursor = self._database.cursor()
+        cursor.execute(selectOperation)
+        if cursor.fetchone() == None:
+            result = False
+        else:
+            result = True
+        cursor.close()
+        return result
+    
+    def doesUserExistByPrefix(self, prefix):
+        """
+        Check if the specified user already exists.
+       
+        :param Name prefix: the prefix of user
+        :return True if the user exists, otherwise False
+        :rtype: bool
+        """
+        result = False
+               
+        cursor = self._database.cursor()
+        cursor.execute("SELECT count(*) FROM User WHERE prefix =?", (prefix.toUri(),))
+        (count,) = cursor.fetchone()
+        if count > 0:
+            result = True
+            #print 'device with %s is founnd, count %d' %(prefix, count)
+
+        cursor.close()
+        return result
+
+    def doesUserExistByUsername(self, username):
+        """
+        Check if the specified user already exists.
+       
+        :param str username: the username of user
+        :return True if the user exists, otherwise False
+        :rtype: bool
+        """
+        result = False
+
+        cursor = self._database.cursor()
+        cursor.execute("SELECT count(*) FROM User WHERE username =?", (username,))
+        (count,) = cursor.fetchone()
+        if count > 0:
+            result = True
+            #print 'device with %s is founnd, count %d' %(prefix, count)
+
+        cursor.close()
+        return result
+
+
+    def addUser(self, prefix, username, hash_, salt, type_):        
+        """ 
+        Add a new user to User table, do nothing if the user already exists
+        
+        :param Name prefix: the prefix of the user
+        :param str username: username
+        :param hash_: 
+        :param salt: 
+        :param str type: the type of user, either guest or user
+        :return the user id if it's added successfully, 0 if prefix conflict exists, -1 if username conflict exists
+        :rtype: INTEGER
+        """
+        data = ( prefix.toUri(), username, hash_, salt, type_)
+        
+        #check if there already exists a user with the same prefix, if yes return 0 
+        if self.doesUserExistByPrefix(prefix):
+            return 0
+
+        #check if there already exists a user with the same username, if yes return -1
+        if self.doesUserExistByUsername(username):
+            return -1
+        
+        #add user to dababase
+        insertUser = (
+            "INSERT INTO User(prefix, username, hash, salt, type)"
+            "VALUES(?,?,?,?,?)"
+        )
+        cursor = self._database.cursor()
+        cursor.execute(insertUser, data)
+        self._database.commit()
+        result = cursor.lastrowid
+        cursor.close()
+        return result
+   
+    def getUserId(self, prefix):
+        """
+        get the user id of a specified user
+        :param Name prefix: the prefix of the user
+        :return id of the user, 0 if the user doesn't exist
+        :rtype: INTEGER
+        """
+        if not self.doesUserExistByPrefix(prefix):
+            return 0
+        cursor = self._database.cursor()
+        operation = "SELECT id FROM User WHERE prefix=?"
+        cursor.execute(operation, (prefix.toUri(),))
+        result = cursor.fetchone()
+        userId = result[0]
+        self._database.commit()
+        cursor.close()
+        return userId
+
+    def updateUser(self, prefix, hash_, salt, type_):
+        """
+        update specifided user
+        :param Name prefix 
+        :param hash_ 
+        :param salt
+        :param str type_: the type of the user
+        :return id of the user if successful, 0 if user not found
+        :rtype int
+        """
+        if not self.doesUserExistByPrefix(prefix):
+            return 0
+
+        updateUser = "UPDATE User Set hash=?, salt =?, type=? WHERE prefix=?"
+        cursor = self._database.cursor()
+        cursor.execute(updateUser, (hash_, salt, type_, prefix.toUri()))
+        self._database.commit()
+        result = cursor.lastrowid
+        cursor.close()
+ 
+    def getUserEntry(self, prefix):
+        """
+        get the specified User entry
+        :param Name prefix: the user prefix
+        :return the corresponding row of the device
+        :rtype: str
+        """
+        cursor = self._database.cursor()
+        cursor.execute("SELECT * FROM User WHERE prefix =?", (prefix.toUri(),))
+        row = cursor.fetchone()
+        cursor.close()
+        return row
+
+    def deleteUser(self, prefix):
+        """
+        delete specified user.
+        :param Name prefix: The user prefix
+        :return: 1 if successful, 0 if no device to delete, otherwise -1.
+        :rtype: INTEGER 
+        """
+        result = -1
+        if not self.doesUserExistByPrefix(prefix):
+            return 0
+        cursor = self._database.cursor()
+        deleteUser = "DELETE FROM User WHERE prefix=?"
+        cursor.execute(deleteUser, (prefix.toUri(),))
+        self._database.commit()
+        cursor.close()
+        return 1
+
+    def doesAccessExist(self, commandId, userId, userDevice=None):
+        """
+        check if the specified access already exists.
+       
+        :param int userId: user id
+        :param int commandId: command id
+        :param str userdevice: user device name
+        :return True if the access exists, otherwise False
+        :rtype: bool
+        """
+        result = False
+        
+        cursor = self._database.cursor()
+        if userDevice == None:
+            operation = "SELECT count(*) FROM Access WHERE user_id =? AND command_id=? "
+            data = (userId, commandId)
+        else: 
+            operation = "SELECT count(*) FROM Access WHERE user_id =? AND command_id=? AND user_device=?" 
+            data = (userId, commandId, userDevice)
+        cursor.execute(operation, data)
+
+        (count,) = cursor.fetchone()
+        if count > 0:
+            result = True
+        cursor.close()
+        return result
+    
+    def addAccess(self, commandId, userId, userDevice, accessToken):
+        """ 
+        Add a new access to the Access table, do nothing if the access already exists
+        
+        :param int commandId: the command id 
+        :param int userId: the user id
+        :param int userDevice: the user device
+        :param HMACKey accessToken: the access token
+        :return the access id if it's added successfully, 0 if the access already exists, otherwise -1
+        :rtype: int
+        """
+        result = -1
+        data = (commandId,
+               userId,
+               userDevice,
+               accessToken.getName(),
+               accessToken.getSequence(),
+               accessToken.getKey()
+               )
+
+        #check if the access already exists, if yes return 0
+        if self.doesAccessExist(commandId, userId, userDevice):
+            return 0
+
+        insertAccess = (
+            "INSERT INTO Access(command_id, user_id, user_device, access_token_name, access_token_sequence, access_token)"
+            "VALUES(?,?,?,?,?,?)"
+        )
+        cursor = self._database.cursor()
+        cursor.execute(insertAccess, data)
+        self._database.commit()
+        result = cursor.lastrowid
+        cursor.close()
+        return result
+
+    def deleteAccess(self, commandId, userId):
+        """
+        delete specified accesses.
+        :param int commandId: The command id
+        :param int userId: the user id
+        :return: 1 if successful, 0 if no access to delete.
+        :rtype: int
+        """
+        if not self.doesAccessExist(userId, userId):
+            return 0
+        cursor = self._database.cursor()
+        deleteAccess = "DELETE FROM Access WHERE command_id=? AND user_id=?"
+        cursor.execute(deleteAccess, (commandId, userId))
+        self._database.commit()
+        cursor.close()
+        return 1
+
+    def getCommandsOfUser(self, userId):
+        """
+        get all the commands to which the specified user has access.
+        :param int userId: user id
+        :return command id list if any commands exist, otherwise None
+        """
+        cursor = self._database.cursor()
+        operation = "SELECT DISTINCT command_id FROM Access WHERE user_id=?"
+        cursor.execute(operation,(userId,))
+        result = cursor.fetchall()
+        cursor.close()
+   
+        commandIdList = []
+        if result == None:
+           return commandIdList
+        else:
+           for row in result:
+               commandIdList.append(row[0])
+
+        return commandIdList
+
+    def getAccessToken(self,commandId, userId, userDevice):
+        """
+        get access token of a specified access 
+        :param int commandId: command id
+        :param int userId: user id  
+        :param str userDevice: user device
+        :return access token if access exists, otherwise None
+        :rtype HMACKey
+        """
+        operation = "SELECT access_token_sequence, access_token, access_token_name FROM Access WHERE command_id = ? AND user_id = ? AND user_device=?"
+        cursor = self._database.cursor()
+        cursor.execute(operation, (commandId, userId, userDevice))
+        result = cursor.fetchone()
+        cursor.close()
+
+        if result == None:
+            return None
+        else:
+            accessToken = HMACKey(sequence = result[0], key = result[1], name = result[2])
+        return accessToken
+   
+    def getUserDevices(self, commandId, userId):
+        """
+        get user devices given commandi id and user id
+        :param int commandId: command id
+        :param int userId: user id  
+        :return a list of user device
+        :rtype list
+        """
+        operation = "SELECT user_device from Access WHERE command_id=? AND user_id=?"
+        cursor = self._database.cursor()
+        cursor.execute(operation,(commandId, userId))
+        result = cursor.fetchall()
+        cursor.close()
+
+        userDeviceList = []        
+        if result == None: 
+            return userDeviceList
+
+        for row in result:
+            userDeviceList.append(row[0])
+
+        return userDeviceList
+