def post(self): # If the provided shared_secret is correct (According to core/api_vars) if api.payload['shared_secret'] == api_vars.SHARED_SECRET: # If the type is not device or app, then return an error if api.payload['type'] != 'device' and api.payload['type'] != 'app': return {'status': 'failed', 'error': 'Type can only be device or app'} # Generate a 40 character token token = secrets.token_hex(40) # Try to write the token to the database database = db.Database() if database.writeToken(uid=api.payload['uid'], type=api.payload['type'], token=token): # If the operation was successful return {'status': 'ok', 'token': token} else: # If there was a database error return {'status': 'failed', 'error': 'Could not write token to database'} # If the join_token was incorrect else: return {'status': 'failed', 'error': 'Incorrect shared secret.'}, 401
def decorated(*args, **kwargs): token = None if 'X-API-KEY' in request.headers: token = request.headers['X-API-KEY'] if not token: return { 'status': 'failed', 'error': 'This endpoint requires a private access token' }, 401 database = db.Database() matchedTokens = database.readToken(token=token, namespace='private') if matchedTokens == False: return { 'status': 'failed', 'error': 'Could not check if token exists in database' } else: if len(matchedTokens) == 0: return { 'status': 'failed', 'error': 'Incorrect token. Are you using a private access token?' }, 401 database.close() return f(*args, **kwargs)
def generate_sample_data(): database = db.Database() global stop_thread while True: if stop_thread: break classrooms = database.query('''SELECT classcode FROM classrooms;''') for classroom in classrooms: free = random.choice([0, 1]) if free == 0: addValue = database.query( '''INSERT INTO occupation ( classcode, free, time ) VALUES ( '{}', true, Now() ) ;''' .format(classroom[0])) addValue = database.query( '''INSERT INTO occupation ( classcode, free, time ) VALUES ( '{}', true, Now() ) ;''' .format(classroom[0])) addValue = database.query( '''INSERT INTO occupation ( classcode, free, time ) VALUES ( '{}', true, Now() ) ;''' .format(classroom[0])) elif free == 1: continue time.sleep(60) database.close()
def get(self, classcode): database = db.Database() classrooms = database.query('''SELECT * FROM classrooms WHERE classcode = '{}';'''.format(classcode)) if classrooms == False: return {'status': 'failed', 'error': 'Could not get classrooms from database'} if len(classrooms) < 1: return {'status': 'failed', 'error': 'Classroom with classcode {} does not exist'.format(classcode)} classcode = classrooms[0][0] free = "Unknown" try: freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classcode)) if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD): free = False elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD): free = True except: free = "Unknown" database.close() return {'status': 'ok', 'classcode': classcode, 'free': free}
def post(self): if 'floor_number' not in api.payload or 'building_id' not in api.payload: return { 'status': 'failed', 'error': 'You have to provide floornumber and the uuid of the building that the floor belongs to.' } database = db.Database() try: # Check if building exists try: result = database.query( '''SELECT * FROM buildings WHERE id = '{}';'''.format( api.payload['building_id'])) if len(result) < 1: return { 'status': 'failed', 'error': 'Building with UUID {} does not exist'.format( api.payload['building_id']) } except: return { 'status': 'failed', 'error': 'Building with UUID {} does not exist'.format( api.payload['building_id']) } # Check if floor already exists result = database.query( '''SELECT * FROM floors WHERE id_buildings = '{}' AND floornumber = '{}';''' .format(api.payload['building_id'], api.payload['floor_number'])) if len(result) > 0: return {'status': 'failed', 'error': 'Floor already exists.'} except Exception as err: sys.stderr.write('Database Error: {}'.format(err)) database.addFloor(floorNumber=api.payload['floor_number'], buildingId=api.payload['building_id']) result = database.query( '''SELECT * FROM floors WHERE floornumber = '{}' AND id_buildings = '{}';''' .format(api.payload['floor_number'], api.payload['building_id'])) created = { 'id': result[0][0], 'floor_number': result[0][1], 'building_id': result[0][2] } database.close() return {'status': 'ok', 'created': created}
def post(self): if 'classcode' not in api.payload or 'floor_id' not in api.payload: return { 'status': 'failed', 'error': 'You have to provide the classcode of the classroom and the uuid of the floor that the classroom belongs to.' } database = db.Database() try: # Check if floor exists try: result = database.query( '''SELECT * FROM floors WHERE id = '{}';'''.format( api.payload['floor_id'])) if len(result) < 1: return { 'status': 'failed', 'error': 'Floor with UUID {} does not exist'.format( api.payload['floor_id']) } except: return { 'status': 'failed', 'error': 'Floor with UUID {} does not exist'.format( api.payload['floor_id']) } # Check if classroom already exists result = database.query( '''SELECT * FROM classrooms WHERE id_floors = '{}' AND classcode = '{}';''' .format(api.payload['floor_id'], api.payload['classcode'])) if len(result) > 0: return { 'status': 'failed', 'error': 'Classroom already exists.' } except Exception as err: sys.stderr.write('Database Error: {}'.format(err)) database.addClassroom(classCode=api.payload['classcode'], floorId=api.payload['floor_id']) result = database.query( '''SELECT * FROM classrooms WHERE classcode = '{}' AND id_floors = '{}';''' .format(api.payload['classcode'], api.payload['floor_id'])) created = {'classcode': result[0][0], 'floor_id': result[0][1]} database.close() return {'status': 'ok', 'created': created}
def setUpClass(cls): setup_config('data/config.py') from flask import Flask cls.app = Flask(__name__) cls.app.sessions = None from core import db cls.app.database = db.Database(config.DATABASE)
def get(self, floor_id): database = db.Database() try: result = database.query('''SELECT * FROM floorplans WHERE id_floors = '{}';'''.format(floor_id)) if len(result) < 1: return {'status': 'failed', 'error': 'There is no floorplan for floor with UUID {}.'.format(floor_id)} except: return {'status': 'failed', 'error': 'Floor with UUID {} does not exist'.format(floor_id)} database.close() return {'status': 'ok', 'floorplan': str(result[0][0])}
def setUpClass(cls): setup_config('data/config.py') from flask import Flask cls.app = Flask(__name__) cls.app.sessions = None from core import db cls.app.database = db.Database(config.DATABASE) with patch('core.utils.init.home_dir', Mock(return_value=config.BASEDIR)): from vmmaster import cleanup cls.cleanup = cleanup
def get(self): token = request.headers['X-API-KEY'] database = db.Database() config = database.readConfig(token=token) database.close() if config == False: return { 'status': 'failed', 'error': 'Could not retrieve config from database' } return {'status': 'ok', 'config': config}
def get(self, floor_id): database = db.Database() floors = database.query('''SELECT * FROM floors WHERE id = '{}';'''.format(floor_id)) if floors == False: return {'status': 'failed', 'error': 'Could not get floors from database'} if len(floors) < 1: return {'status': 'failed', 'error': 'Floor with id {} does not exist'.format(floor_id)} floor_id = floors[0][0] floor_number = int(floors[0][1]) classrooms_object = [] classrooms = database.query('''SELECT * FROM classrooms WHERE id_floors = '{}';'''.format(floor_id)) if classrooms == False: return {'status': 'failed', 'error': 'Could not get classrooms from database'} if len(classrooms) < 1: return {'status': 'failed', 'error': 'Floor with id {} has no classrooms'.format(floor_id)} for classroom in classrooms: classroomdict = dict() classroomdict['classcode'] = classroom[0] free = "Unknown" try: freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classroomdict['classcode'])) if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD): free = False elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD): free = True except: free = "Unknown" classroomdict['free'] = free classrooms_object.append(classroomdict) database.close() return {'status': 'ok', 'id': floor_id, 'classrooms': classrooms_object}
def post(self): if 'sensors' not in api.payload: return {'status': 'failed', 'error': 'No sensor_values provided.'} # Check who it is token = request.headers['X-API-KEY'] database = db.Database() uidQuery = database.query( '''SELECT uid FROM tokens WHERE token = '{}';'''.format(token)) uid = uidQuery[0][0] # Check if location was set locationQuery = database.query( '''SELECT location FROM configs WHERE uid = '{}';'''.format(uid)) location = locationQuery[0][0] if location == None: return { 'status': 'failed', 'error': 'Device location was not set.' } sensors = api.payload['sensors'] motion_value = int(sensors[0]['value']) if motion_value == 100: addValue = database.query( '''INSERT INTO occupation ( classcode, free, time ) VALUES ( '{}', true, Now() ) ;''' .format(location)) if addValue == False: database.close() return { 'status': 'failed', 'error': 'Could not insert sensor value in database.' } # test = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(location)) # print(test[0][0]) database.close() return {'status': 'ok'}
def post(self): print(api.payload) if 'name' not in api.payload or 'streetname' not in api.payload or 'buildingnumber' not in api.payload: return { 'status': 'failed', 'error': 'You have to provide name, streetname and buildingnumber' } database = db.Database() try: result = database.query( '''SELECT * FROM buildings WHERE name = '{}';'''.format( api.payload['name'])) if len(result) > 0: return { 'status': 'failed', 'error': 'Building with name {} already exists.'.format( api.payload['name']) } except: pass database.addBuilding(name=api.payload['name'], streetName=api.payload['streetname'], buildingNumber=api.payload['buildingnumber']) result = database.query( '''SELECT * FROM buildings WHERE name = '{}';'''.format( api.payload['name'])) created = { 'id': result[0][0], 'name': result[0][1], 'street_name': result[0][2], 'building_number': result[0][3] } database.close() return {'status': 'ok', 'created': created}
def post(self): if 'location' not in api.payload: return { 'status': 'failed', 'error': 'You have to provide a classcode as location.' } token = request.headers['X-API-KEY'] database = db.Database() try: result = database.query( '''SELECT * FROM classrooms WHERE classcode = '{}';'''.format( api.payload['location'])) if len(result) < 1: return { 'status': 'failed', 'error': 'Classroom with classcode: {} does not exist'.format( api.payload['location']) } except: return { 'status': 'failed', 'error': 'Classroom with classcode: {} does not exist'.format( api.payload['location']) } setConfig = database.setLocation(token=token, location=api.payload['location']) database.close() if setConfig == False: return {'status': 'failed', 'error': 'Could not set location.'} return {'status': 'ok'}
def get(self): classrooms = [] database = db.Database() classroomsQuery = database.query('''SELECT classcode FROM classrooms;''') database.close() if classroomsQuery == False: return {'status': 'failed', 'error': 'Could not get classrooms from database.'} if len(classroomsQuery) < 1: return {'status': 'failed', 'error': 'There are no classrooms.'} for classroom in classroomsQuery: classroomdict = dict() classroomdict['classcode'] = classroom[0] classrooms.append(classroomdict) return {'status': 'ok', 'classrooms': classrooms}
def post(self): # We only want students and staff of the HU to be able to apply for an access token if '@student.hu.' in api.payload['email'] or '@hu.' in api.payload['email']: # Generate a 40 character token token = secrets.token_hex(40) # Try to write the token to the database database = db.Database() if database.writeToken(uid=api.payload['email'], type='user', token=token): # If the operation was successful return {'status': 'ok', 'token': token} else: # If there was a database error return {'status': 'failed', 'error': 'Could not write token to database'} # If the email wasn't of a HU student / staffmember else: return {'status': 'failed', 'error': 'You can only apply for an access token with a HU email account.'}, 401
def get(self): database = db.Database() classrooms = dict() result = database.query('''SELECT DISTINCT(classcode) FROM occupation;''') if len(result) < 1: return {'status': 'failed', 'error': 'There is no occupation data.'} for classroom in result: classrooms[classroom[0]] = [] for classroom in classrooms.keys(): detections = database.query('''SELECT time FROM occupation WHERE classcode = '{}';'''.format(classroom)) detections_formatted = [] for detection in detections: detections_formatted.append(detection[0].strftime("%x %X")) classrooms[classroom] = detections_formatted database.close() return {'status': 'ok', 'export': classrooms}
def put(self): if 'floorplan' not in api.payload or 'floor_id' not in api.payload: return { 'status': 'failed', 'error': 'You have to provide floor_id and the floorplan' } database = db.Database() try: result = database.query( '''SELECT * FROM floors WHERE id = '{}';'''.format( api.payload['floor_id'])) if len(result) < 1: return { 'status': 'failed', 'error': 'Floor with UUID {} does not exist'.format( api.payload['floor_id']) } except: return { 'status': 'failed', 'error': 'Floor with UUID {} does not exist'.format( api.payload['floor_id']) } try: result = database.query( '''SELECT * FROM floorplans WHERE id_floors = '{}';'''.format( api.payload['floor_id'])) if len(result) < 1: return { 'status': 'failed', 'error': 'There is no floorplan for floor with UUID {}.'.format( api.payload['floor_id']) } except: return { 'status': 'failed', 'error': 'There is no floorplan for floor with UUID {}.'.format( api.payload['floor_id']) } database.updateFloorplan(floorPlan=api.payload['floorplan'].replace( "'", "''"), floorId=api.payload['floor_id']) result = database.query( '''SELECT * FROM floorplans WHERE id_floors = '{}';'''.format( api.payload['floor_id'])) database.close() return {'status': 'ok', 'floorplan': result[0][0]}
def get(self): totalObject = [] database = db.Database() buildings = database.query('''SELECT * FROM buildings ORDER BY name;''') if buildings == False: return {'status': 'failed', 'error': 'Could not get buildings from database'} if len(buildings) < 1: return {'status': 'failed', 'error': 'There are no buildings.'} for building in buildings: buildingdict = dict() buildingdict['id'] = building[0] buildingdict['name'] = building[1] buildingdict['streetname'] = building[2] buildingdict['buildingnumber'] = building[3] buildingdict['floors'] = [] totalObject.append(buildingdict) floors = database.query('''SELECT * FROM floors ORDER BY floornumber;''') if floors == False: return {'status': 'failed', 'error': 'Could not get floors from database'} for floor in floors: floordict = dict() floordict['id'] = floor[0] floordict['floornumber'] = int(floor[1]) floordict['classrooms'] = [] for building in totalObject: if building['id'] == floor[2]: building['floors'].append(floordict) classrooms = database.query('''SELECT * FROM classrooms;''') if classrooms == False: return {'status': 'failed', 'error': 'Could not get classrooms from database'} for classroom in classrooms: classroomdict = dict() classroomdict['classcode'] = classroom[0] free = "Unknown" try: freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classroomdict['classcode'])) if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD): free = False elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD): free = True except: free = "Unknown" classroomdict['free'] = free for buildings in totalObject: for floor in buildings['floors']: if floor['id'] == classroom[1]: floor['classrooms'].append(classroomdict) database.close() return {'status': 'ok', 'buildings': totalObject}
classrooms = [{ "classcode": "HL15-0.063", "free": "true" }, { "classcode": "HL15-0.019", "free": "true" }, { "classcode": "PL101-1.223", "free": "true" }, { "classcode": "PL101-2.164", "free": "true" }] if __name__ == "__main__": database = db.Database() structureExists = database.query( '''SELECT to_regclass('public.buildings');''') if len(structureExists) < 1: database.query(open('project.sql', 'r').read()) # for building in buildings: # database.query('''INSERT INTO buildings ( name, streetname, buildingnumber) VALUES ( '{}', '{}', '{}' )'''.format(building['name'], # building['streetName'], # building['buildingNumber'])) # for floor in floors: # database.query('''INSERT INTO floors VALUES ( '{}', '{}', '{}', '{}' )'''.format(floor['id'], # floor['floorNumber'], # floor['name_buildings']))