def timetableStudent(id): Mrows = Database.getRows( 'SELECT module FROM `studentModule` WHERE `student` = %s', (id, )) if len(Mrows) == 0: return None module = rows[0] srows = Database.getRows( 'SELECT id FROM `moduleSession` WHERE `module` = %s', (module, )) if len(srows) == 0: return None session = rows[0] rows = Database.getRows( 'SELECT all FROM `roombooking` WHERE `module_session` = %s', (session, )) if len(srows) == 0: return None times = timetable() times.setmodule(rows[0]['id']) times.setStart(rows[0]['identifier']) times.setEnd(rows[0]['building_floor']) times.setRoom(rows[0]['building']) return times
def save(self): if self.id == None: # insert Database.execute('INSERT INTO `Campus` (`name`) VALUES (%s)', (self.row['name'],)) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute('UPDATE `Campus` SET `name` = %s WHERE `id` = %s', (self.row['name'], self.id))
def save(self): if self.id == None: # insert Database.execute('INSERT INTO `Building` (`name`, `floor_count`, `campus`) VALUES (%s, %s, %s)', (self.row['name'], self.row['floor_count'], self.row['campus'],)) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute('UPDATE `Building` SET `name` = %s, `floor_count` = %s, `campus` = %s WHERE `id` = %s', (self.row['name'],self.row['floor_count'],self.row['campus'], self.id))
def save(self): if self.id == None: # insert Database.execute('INSERT INTO `PasswordReset` (`token`, `user_id`, `user_type`,`expires`) VALUES (%s, %s, %s, %s)', (self.row['token'], self.row['user_id'], self.row['user_type'], self.row['expires'],)) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute('UPDATE `PasswordReset` SET `token` = %s, `user_id` = %s, `user_type` = %s , `expires` = %s WHERE `id` = %s', (self.row['token'],self.row['user_id'],self.row['user_type'], self.row['expires'], self.id))
def create(user_id, user_type, ip_addr, user_agent): """ Creates a session in the database """ signature = ip_addr + user_agent signature = hashlib.sha256(signature.encode('utf-8')).hexdigest() token = str(uuid.uuid4()).replace('-', '') expires = time.time() + 30 * 60 Database.execute( 'INSERT INTO `ApiSession` (`user_id`, `user_type`, `signature`, `expires`, `token`) VALUES (%s, %s, %s, %s, %s)', (int(user_id), user_type, signature, expires, token)) return token
def save(self): if self.id == None: # insert Database.execute( 'INSERT INTO `StudentModule` (`module`,`student`, `enrolment_date`) VALUES (%s, %s, %s)', (self.row['module'], self.row['student'], self.row['enrolment_date'])) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute( 'UPDATE `StudentModule` SET `module` = %s ,`student` = %s, `enrolment_date` = %s WHERE `id` = %s', (self.row['module'], self.row['student'], self.row['enrolment_date'], self.id))
def save(self): if self.id == None: # insert Database.execute( 'INSERT INTO `Room` (`identifier`, `building_floor`, `building`, `capacity`) VALUES (%s, %s, %s, %s)', (self.row['identifier'], self.row['building_floor'], self.row['building'], self.row['capacity'])) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute( 'UPDATE `Room` SET `identifier` = %s, `building_floor` = %s, `building` = %s, `capacity` = %s WHERE `id` = %s', (self.row['identifier'], self.row['building_floor'], self.row['building'], self.row['capacity'], self.id))
def launchFile(self): ## Prompts a file dialog with only 2 available file types ## Once file is selected, dialog returns the file's path (filename) filename = tkFileDialog.askopenfilename( filetypes=[('word files', '.docx'), ('text files', '.txt')]) ## Splits file's path into a tuple of directory string and extension string filepath, file_ext = os.path.splitext(filename) if filename: if file_ext == ".txt": ## Executable file for notepad program filepath = "C:/Windows/notepad.exe" elif file_ext == ".docx": ## Executable file for Microsoft Word program filepath = "C:/Program Files (x86)/Microsoft Office/root/Office16/WINWORD.EXE" try: ## Create sub process proc = subprocess.Popen([filepath, filename]) proc.wait() except (OSError, subprocess.CalledProcessError): return "Failed, file is damaged or program has crashed!" ## Prompts dialog for user to input revision message message = tkSimpleDialog.askstring("Commit message", "What are the changes?") rcsFile = File(filename, Database()) rcsFile.add(message) ## Update file list with the new changes self.updatefileList()
def save(self): if self.id == None: # insert Database.execute( 'INSERT INTO `ModuleSessionType` (`name`, `display_name`) VALUES (%s, %s)', ( self.row['name'], self.row['display_name'], )) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute( 'UPDATE `ModuleSessionType` SET `name` = %s, `display_name` = %s WHERE `id` = %s', (self.row['name'], self.row['display_name'], self.id))
def hook(): if not request.endpoint == 'static': Database.connect() #return if request.endpoint == 'static': return if request.endpoint is None: return if request.endpoint.startswith('Api.') or request.endpoint.startswith( 'Auth.'): return if not Authorization.isLoggedIn(session.get('user')): return redirect(url_for('Auth.Login'))
def isValidToken(token, ip_addr, user_agent): """ Checks if the specified authentication token is valid """ session = Database.getRows( 'SELECT `user_id`, `signature`, `expires` FROM `ApiSession` WHERE `token` = %s LIMIT 1', (token, )) # Check if session exists if len(session) != 1: return False # Check if session expired if session[0]['expires'] < time.time(): Database.execute('DELETE FROM `ApiSession` WHERE token = %s', (token, )) return False # Check if signature matches signature = ip_addr + user_agent signature = hashlib.sha256(signature.encode('utf-8')).hexdigest() if signature != session[0]['signature']: Database.execute('DELETE FROM `ApiSession` WHERE token = %s', (token, )) # Everything is okay, Renew the token Database.execute('UPDATE `ApiSession` SET expires = %s WHERE token = %s', (time.time() + 30 * 60, token)) return True
def __init__(self, core, name): # Expose core and plugin name for subclasses self.core = core self.name = name self.database = Database(databaseName="databases/" + self.name + ".db") # Expose logger for subclasses self.logger = logging.getLogger("plugins." + self.name)
def save(self): if self.id == None: # insert Database.execute( 'INSERT INTO `ModuleSession` (`module`, `staff`, `type`) VALUES (%s, %s, %s)', ( self.row['module'], self.row['staff'], self.row['type'], )) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute( 'UPDATE `ModuleSession` SET `module` = %s, `staff` = %s, `type` = %s WHERE `id` = %s', (self.row['module'], self.row['staff'], self.row['type'], self.id))
def __init__(self, method): self.db = Database.Db() if method == "newContact": self.newContact() elif method == "listContact": self.listContact() elif method == "searchContact": self.searchContact()
async def on_ready(self): print(f"\tClient Name:\t{self.user.name}") print(f"\tClient ID:\t{self.user.id}") print(f"\tClient Disc:\t{self.user.discriminator}\n") await self.load_extensions() self.redditCmd = RedditCommandsManager( self, os.getenv("REDDIT_CLIENT_ID"), os.getenv("REDDIT_CLIENT_SECRET"), os.getenv("REDDIT_NAME"), os.getenv("REDDIT_PASS"), ) self.musicCmd = MusicCommandsManager(self) await self.musicCmd.init() self.db = Database()
def save(self): if self.id == None: # insert Database.execute( 'INSERT INTO `Term` (`start_date`, `end_date`, `term`) VALUES (%s, %s, %s)', ( self.row['start_date'], self.row['end_date'], self.row['term'], )) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute( 'UPDATE `Term` SET `start_date` = %s, `end_date` = %s, `term` = %s WHERE `id` = %s', (self.row['start_date'], self.row['end_date'], self.row['term'], self.id))
def addFile(self): ## Prompts a file dialog with only 2 available file types filename = tkFileDialog.askopenfilename( filetypes=[('text files', '.txt'), ('word files', '.docx')]) ## Prompts dialog for user to input revision message message = tkSimpleDialog.askstring("First commit", "What are the details?") rcsFile = File(filename, Database()) rcsFile.add(message) ## Update file list with the new changes self.updatefileList()
def save(self): if self.id == None: # insert Database.execute( 'INSERT INTO `RoomBooking` (`room`, `time_from`, `time_to`,`module_session`) VALUES (%s, %s, %s, %s)', ( self.row['room'], self.row['time_from'], self.row['time_to'], self.row['module_session'], )) rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id') self.id = rows[0]['insert_id'] else: # update Database.execute( 'UPDATE `RoomBooking` SET `room` = %s, `time_from` = %s, `time_to` = %s, `module_session` = %s WHERE `id` = %s', (self.row['room'], self.row['time_from'], self.row['time_to'], self.row['module_session'], self.id))
def getUserId(token): """ Gets the user ID that is assigned to the token """ session = Database.getRows( 'SELECT `user_id`, `user_type` FROM `ApiSession` WHERE token = %s', (token, )) # Do a sanity check if len(session) != 1: return None return int(session[0]['user_id']), session[0]['user_type']
def get_old_game(self, message, client): try: game = Database.get_game(message['id']) except KeyError: return self.send_reply(client, "error", "'id'-parameter is missing") if game: self.send_reply(client, "info", game) else: self.send_reply(client, "error", "Game id doesn't exist")
def findById(id): rows = Database.getRows('SELECT * FROM `Campus` WHERE `id` = %s', (id,)) if len(rows) == 0: return None campus = Campus() campus.setId(rows[0]['id']) campus.setName(rows[0]['name']) return campus
def findBy(field, value): rows = Database.getRows('SELECT * FROM `Campus` WHERE ' + field +' = %s', (value,)) out = [] for i in rows: campus = Campus() campus.setId(i['id']) campus.setName(i['name']) out.append(campus) return out
def all(): rows = Database.getRows('SELECT * FROM `Campus`') out = [] for i in rows: campus = Campus() campus.setId(i['id']) campus.setName(i['name']) out.append(campus) return out
def all(): rows = Database.getRows('SELECT * FROM `ModuleSessionType`') out = [] for i in rows: sessionType = ModuleSessionType() sessionType.setId(i['id']) sessionType.setName(i['name']) sessionType.setDisplayName(i['display_name']) out.append(sessionType) return out
def findById(id): rows = Database.getRows('SELECT * FROM `Term` WHERE `id` = %s', (id, )) if len(rows) == 0: return None term = Term() term.setId(rows[0]['id']) term.setStartDate(rows[0]['start_date']) term.setEndDate(rows[0]['end_date']) term.setTerm(rows[0]['term']) return term
def findById(id): rows = Database.getRows( 'SELECT * FROM `ModuleSessionType` WHERE `id` = %s', (id, )) if len(rows) == 0: return None sessionType = ModuleSessionType() sessionType.setId(rows[0]['id']) sessionType.setName(rows[0]['name']) sessionType.setDisplayName(rows[0]['display_name']) return sessionType
def all(): rows = Database.getRows('SELECT * FROM `StaffRole`') out = [] for i in rows: staffRole = StaffRole() staffRole.setId(i['id']) staffRole.setName(i['name']) staffRole.setDisplayName(i['display_name']) out.append(staffRole) return out
def findById(id): rows = Database.getRows('SELECT * FROM `StaffRole` WHERE `id` = %s', (id, )) if len(rows) == 0: return None staffRole = StaffRole() staffRole.setId(rows[0]['id']) staffRole.setName(rows[0]['name']) staffRole.setDisplayName(rows[0]['display_name']) return staffRole
def all(): rows = Database.getRows('SELECT * FROM `Module`') out = [] for i in rows: module = Module() module.setId(i['id']) module.setName(i['name']) module.setLeader(i['leader']) out.append(module) return out
def findById(id): rows = Database.getRows('SELECT * FROM `Module` WHERE `id` = %s', (id, )) if len(rows) == 0: return None module = Module() module.setId(rows[0]['id']) module.setName(rows[0]['name']) module.setLeader(rows[0]['leader']) return module
class ACL(): def __init__(self): self.database = Database(databaseName="databases/ACL.db") self.database.addTable(ACLUser) def getOwner(self): """ Summary: Returns the ID of the bot owner if there is one Args: None Returns: (String): ID of bot owner """ try: user = ACLUser.get(owner=True) return user.id except: return None def setOwner(self, uid): """ Summary: Sets the bot owner Args: uid (str): ID of the target user Returns: None """ user, created = self.database.ACLUser.get_or_create(id=uid) if(created): user.id = uid user.access = 1000 user.owner = True user.save() else: user.owner = True user.save() def setAccess(self, uid, access, cname=""): """ Summary: Sets the database access for a specific user Args: uid (str): ID of the target user Returns: (Bool): Successful or Not """ # Check if trying to change owner if(self.getOwner == uid): return False # Set user access user, created = self.database.ACLUser.get_or_create(id=uid) if(created): user.id = uid user.access = access user.cname = cname user.save() else: user.access = access user.cname = cname user.save() return True def getAccess(self, uid): """ Summary: Gets the database access for the specified user Args: uid (str): ID of the target user Returns: (Int): Access level of the target user, or -1 if not found """ try: user = ACLUser.get(id=uid) return user.access except: return -1 def deleteUser(self, uid): """ Summary: Deletes a user from the ACL database Args: uid (str): ID of the target user Returns: (Bool): Successful or Not """ try: user = self.database.ACLUser.get(id=uid) if(user): user.delete_instance() return True else: return False except: return False
def __init__(self): self.database = Database(databaseName="databases/ACL.db") self.database.addTable(ACLUser)