Advertisement
Guest User

Untitled

a guest
Mar 1st, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.50 KB | None | 0 0
  1. # DatabaseInit
  2. # main program
  3.  
  4. #This tidies all of the SQL queries into another namespace.
  5. import SqlDictionary
  6. import random
  7. import hashlib
  8. import sqlite3
  9.  
  10. def gen_pw_hash(password):
  11.     phash = hashlib.md5()
  12.     phash.update(bytes(password, "UTF-8"))
  13.     return phash.hexdigest()
  14.  
  15. class Database:
  16.     """This is the general database wrapper that I'll use throughout the system"""
  17.     def __init__(self, child, database_name="cmsdb.db"):
  18.         #print("[INFO] Created database object")
  19.  
  20.         self.db_name = database_name
  21.  
  22.     def _connect_and_execute(self, sql="", database_name=None):
  23.         #print(sql)
  24.         if database_name == None:
  25.             database_name = self.db_name
  26.  
  27.         with sqlite3.connect(self.db_name) as dbcon:
  28.             cursor = dbcon.cursor()
  29.             cursor.execute(sql)
  30.             results = cursor.fetchall()
  31.  
  32.         #print("[INFO] Executed SQL query \"{0}\"".format(sql))
  33.         return results
  34.  
  35.  
  36. class ResourcesInfo(Database):
  37.     def __init__(self):
  38.         super().__init__(self)
  39.         self.create_table()
  40.  
  41.     def create_table(self):
  42.         self._connect_and_execute(SqlDictionary.CREATE_RESOURCES)
  43.  
  44.     def get_all_resources(self):
  45.         return self._connect_and_execute(SqlDictionary.GET_ALL_RESOURCES)
  46.  
  47.  
  48. class UsersInfo(Database):
  49.     def __init__(self, uid = 0):
  50.         super().__init__(self)
  51.         self.create_table()
  52.  
  53.     # NB: all input MUST be sanitized at this point.
  54.     def create_table(self):
  55.         self._connect_and_execute(SqlDictionary.CREATE_USERS)
  56.         self._create_initial_admin_user()
  57.  
  58.     def _create_initial_admin_user(self):
  59.         # This is to create an initial administrative user in case something happens to the database
  60.         pwd = "".join([chr(random.choice(range(ord('A'), ord('z')))) for c in range(10)])
  61.  
  62.         new_user_info = {"Name":"ADMIN - TMP", "Username":"default_admin", "Password": gen_pw_hash(pwd), "Permissions": 29}
  63.  
  64.         if len(self.get_all_users("WHERE(Username = 'default_admin')")) == 0:
  65.             print("[INFO] Empty users table detected, adding default user...")
  66.             self.add_user(new_user_info)
  67.             print("[INFO] Default user added,\n\tUsername: 'default_admin'\n\tPassword: '{0}'".format(pwd))
  68.  
  69.     def get_all_users(self, condition = ""): # Add a SQL condition? maybe? TODO: refactor this bit
  70.         return self._connect_and_execute(SqlDictionary.GET_ALL_USERS.format(condition))
  71.  
  72.     def get_uid_by_username(self, username=""):
  73.         return self._connect_and_execute((SqlDictionary.GET_USER_ID.format(username)))[0][0]
  74.  
  75.     def get_username_by_uid(self, uid=None):
  76.         return self._connect_and_execute(SqlDictionary.GET_USERNAME_BY_UID.format(uid))[0][0]
  77.  
  78.     def add_user(self, info):
  79.         #info follows the format {"SQL value":Data value}
  80.         values = "'{0}', '{1}', '{2}', {3}".format(info["Name"], info["Username"], info["Password"], info["Permissions"])
  81.  
  82.         return self._connect_and_execute(SqlDictionary.ADD_USER.format(values))
  83.  
  84.     def update_user_password(self, password, uid):
  85.         sql = SqlDictionary.UPDATE_PASSWORD.format("'{0}'".format(password), uid)
  86.         return self._connect_and_execute(sql)
  87.  
  88.     # TODO: Add more features as they become necessary.
  89.  
  90. class TasksInfo(Database):
  91.  
  92.     def __init__(self):
  93.         super().__init__(self)
  94.         self.create_table()
  95.  
  96.     def create_table(self):
  97.         self._connect_and_execute(SqlDictionary.CREATE_TASKS)
  98.         self._connect_and_execute(SqlDictionary.CREATE_TASKATTENDEE)
  99.  
  100.     def get_info_by_id(self, task_id):
  101.         sql = SqlDictionary.GET_TASK.format("WHERE (TaskID = {0})".format(task_id))
  102.         raw = self._connect_and_execute(sql)[0]
  103.         return {"TaskID":raw[0], "Title":raw[1], "Description":raw[2], "OwnerID":raw[3], "Attendees":raw[4]}
  104.  
  105.     def get_ids_by_owner(self, owner_id):
  106.         sql = SqlDictionary.GET_TASK_ID_LIST.format("WHERE Owner = {0}".format(owner_id))
  107.         output_ids = []
  108.         for row in self._connect_and_execute(sql):
  109.             output_ids.append(row[0])
  110.         return output_ids
  111.  
  112.     def add_task(self, info):
  113.         SQL_DATA = """'{0}', '{1}', {2}, {3}""".format(info["Title"], info["Description"], info["OwnerID"], info["Attendees"])
  114.         self._connect_and_execute(SqlDictionary.ADD_TASK.format(SQL_DATA))
  115.  
  116.  
  117.  
  118. class MeetingsInfo(Database):
  119.     def __init__(self, meeting_info = None):
  120.         super().__init__(self)
  121.         self.create_table()
  122.         self.meeting_info = meeting_info
  123.         self.id = None
  124.  
  125.     def create_table(self):
  126.         self._connect_and_execute(SqlDictionary.CREATE_MEETINGS)
  127.         self._connect_and_execute(SqlDictionary.CREATE_MEETINGS_ATTENEDEES)
  128.  
  129.     def add_meeting(self):
  130.         SQL_DATA = "{0}, '{1}', '{2}', '{3}'".format(self.meeting_info["OwnerID"],
  131.             self.meeting_info["Title"],
  132.             self.meeting_info["ISOTime"],
  133.             self.meeting_info["Location"])
  134.         self._connect_and_execute(SqlDictionary.ADD_MEETING.format(SQL_DATA)) #TODO Sort out the formatting.
  135.         self.id = self._connect_and_execute("SELECT Max(MeetingID) FROM Meetings;")[0][0]
  136.  
  137.     def get_meeting_info(self):
  138.         sql_condition = "WHERE (MeetingID = {0})".format(self.meeting_info['MeetingID'])
  139.         q = SqlDictionary.GET_MEETING.format(sql_condition)
  140.         results = self._connect_and_execute(q)
  141.         return results[0]
  142.  
  143.     def add_meeting_attendee(self, user_id):
  144.         sql_values = """{0}, {1}, 0""".format(self.id, user_id)
  145.         return self._connect_and_execute(SqlDictionary.ADD_MEETING_ATTENDEE.format(sql_values))
  146.  
  147.  
  148.     def get_meetings_by_owner(self, OwnerID):
  149.         sql_condition = "WHERE (OwnerID = {0})".format(OwnerID)
  150.         q = SqlDictionary.GET_MEETING_ID_LIST.format(sql_condition)
  151.         return self._connect_and_execute(q)
  152.  
  153.     def get_outstanding_meetings(self, OwnerID):
  154.         results = self._connect_and_execute(SqlDictionary.GET_OUTSTANDING_MEETINGS_TO_BE_ATTENDED.format(OwnerID))
  155.         return results
  156.  
  157.     def get_meeting_attendees(self, MeetingID):
  158.         return self._connect_and_execute(SqlDictionary.GET_MEETING_ATTENDEES.format(MeetingID))
  159.  
  160.     def respond_to_attendance_request(self, attending, MeetingID, UserID):
  161.         if attending:
  162.             self._connect_and_execute(SqlDictionary.ACCEPT_MEETING.format("UserID = {0} AND MeetingID = {1}".format(UserID, MeetingID)))
  163.         else:
  164.             self._connect_and_execute(SqlDictionary.REJECT_MEETING.format("UserID = {0} AND MeetingID = {1}".format(UserID, MeetingID)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement