async def patch_meter(request: Request, meter_id: int, body: ChangeMeterModel, db: Session = Depends(get_db),): has_permission(request, PermissionSet.MeterEdit.value) meter = db.query(Meter).filter_by(id=meter_id).first() change_dict = body.dict(exclude_unset=True) electricity_dict = change_dict.pop('electricity', None) args = {k: v for k, v in change_dict.items()} for k, v in args.items(): setattr(meter, k, v) if meter.type == MeterType.Electricity: if electricity_dict: if meter.electricity: for k, v in electricity_dict.items(): setattr(meter.electricity, k, v) else: electricity = ElectricityMeter(**electricity_dict) meter.electricity = electricity elif not meter.electricity: raise HTTPException(detail='Electricity info is needed', status_code=400) elif meter.electricity: db.query(ElectricityMeter).filter_by(id=meter.electricity.id).delete() meter.electricity = None db.merge(meter) db.commit() return MeterModel.from_orm(meter)
async def remove_room(request: Request, room_id: int, db: Session = Depends(get_db)): has_permission(request, PermissionSet.RoomEdit.value) db.query(Room).filter_by(id=room_id).delete() db.commit() return ""
async def remove_building_type(request: Request, building_type_id: int, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingTypeEdit.value) db.query(BuildingType).filter_by(id=building_type_id).delete() db.commit() return ""
async def remove_location(request: Request, location_id: int, db: Session = Depends(get_db)): has_permission(request, PermissionSet.LocationEdit.value) db.query(Location).filter_by(id=location_id).delete() db.commit() return ""
async def get_floors(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.FloorRead.value) return paginate( db=db, db_model=Floor, serializer=FloorModel, request=request )
async def get_environmental_readings(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.RoomRead.value) return paginate( db=db, db_model=EnvironmentalReading, serializer=EnvironmentalReadingModel, request=request )
async def add_responsible_user( request: Request, body: AddResponsibleUserModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.BuildingEdit.value) if not (user := get_user(body.user_id)): raise HTTPException(detail='User does not exist', status_code=400)
async def get_meter_snapshots(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.MeterSnapshotRead.value) return paginate( db=db, db_model=MeterSnapshot, serializer=MeterSnapshotModel, request=request )
async def add_floor(request: Request, body: AddFloorModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.FloorEdit.value) floor = Floor(**body.dict()) db.add(floor) try: db.commit() except IntegrityError: raise HTTPException(detail='Floor already exists', status_code=400) return FloorModel.from_orm(floor)
async def remove_responsible_user_by_user_id( request: Request, user_id: int, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.BuildingEdit.value) db.query(ResponsibleUser).filter_by(user_id=user_id).delete() db.commit() return ""
async def get_building_types( request: Request, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.BuildingTypeRead.value) return paginate(db=db, db_model=BuildingType, serializer=BuildingTypeModel, request=request)
async def add_environmental_reading(request: Request, body: AddEnvironmentalReadingModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.RoomEdit.value) environmental_reading = EnvironmentalReading(**body.dict()) db.add(environmental_reading) try: db.commit() except IntegrityError: raise HTTPException(detail='EnvironmentalReading already exists', status_code=400) return EnvironmentalReadingModel.from_orm(environmental_reading)
async def get_buildings(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingRead.value) paginated = paginate(db=db, db_model=Building, serializer=BuildingModel, request=request) for index, building in enumerate(paginated['items']): for user in building.responsible_people: user.user = get_user(user.user_id) return paginated
async def add_room(request: Request, body: AddRoomModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.RoomEdit.value) room = Room(**body.dict()) db.add(room) try: db.commit() except IntegrityError: raise HTTPException(detail='Room already exists', status_code=400) return RoomModel.from_orm(room)
async def add_building(request: Request, body: AddBuildingModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingEdit.value) building = Building(**body.dict()) db.add(building) try: db.commit() except IntegrityError: raise HTTPException(detail='Building already exists', status_code=400) return BuildingModel.from_orm(building)
async def patch_environmental_reading(request: Request, environmental_reading_id: int, body: ChangeEnvironmentalReadingModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.RoomEdit.value) environmental_reading = db.query(EnvironmentalReading).filter_by(id=environmental_reading_id).first() args = {k: v for k, v in body.dict(exclude_unset=True).items()} if args: for k, v in args.items(): setattr(environmental_reading, k, v) db.add(environmental_reading) db.commit() return EnvironmentalReadingModel.from_orm(environmental_reading)
async def add_location(request: Request, body: AddLocationModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.LocationEdit.value) location = Location(name=body.name, latitude=body.latitude, longitude=body.longitude) db.add(location) try: db.commit() except IntegrityError: raise HTTPException(detail='Location already exists', status_code=400) return LocationModel.from_orm(location)
async def patch_building_type( request: Request, building_type_id: int, body: AddBuildingTypeModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.BuildingTypeEdit.value) building_type = db.query(BuildingType).filter_by( id=building_type_id).first() building_type.name = body.name db.add(building_type) db.commit() return BuildingTypeModel.from_orm(building_type)
async def patch_floor(request: Request, floor_id: int, body: ChangeFloorModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.FloorEdit.value) floor = db.query(Floor).filter_by(id=floor_id).first() if not floor: raise HTTPException(detail='Floor does not exist', status_code=404) args = {k: v for k, v in body.dict(exclude_unset=True).items()} if args: for k, v in args.items(): setattr(floor, k, v) db.add(floor) db.commit() return FloorModel.from_orm(floor)
async def patch_building(request: Request, building_id: int, body: ChangeBuildingModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingEdit.value) building = db.query(Building).filter_by(id=building_id).first() args = {k: v for k, v in body.dict(exclude_unset=True).items()} if args: for k, v in args.items(): setattr(building, k, v) db.add(building) db.commit() return BuildingModel.from_orm(building)
async def patch_responsible_user(request: Request, responsible_user_id: int, body: ChangeResponsibleUserModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingEdit.value) responsible_user = db.query(ResponsibleUser).filter_by( id=responsible_user_id).first() args = {k: v for k, v in body.dict(exclude_unset=True).items()} if args: for k, v in args.items(): setattr(responsible_user, k, v) db.add(responsible_user) db.commit() return ResponsibleUserModel.from_orm(responsible_user)
async def patch_room( request: Request, room_id: int, body: ChangeRoomModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.RoomEdit.value) room = db.query(Room).filter_by(id=room_id).first() args = {k: v for k, v in body.dict(exclude_unset=True).items()} if args: for k, v in args.items(): setattr(room, k, v) db.add(room) db.commit() return RoomModel.from_orm(room)
async def patch_location( request: Request, location_id: int, body: ChangeLocationModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.LocationEdit.value) location = db.query(Location).filter_by(id=location_id).first() args = {k: v for k, v in body.dict(exclude_unset=True).items()} if args: for k, v in args.items(): setattr(location, k, v) db.add(location) db.commit() return LocationModel.from_orm(location)
async def get_building_types_count(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingTypeRead.value) result_models, count, page_number = apply_filtering( db, BuildingType, request) items = [ BuildingTypeCountModel(id=b.id, name=b.name, buildings_count=len(b.buildings)) for b in result_models ] return { 'total_size': count, 'page_number': page_number, 'page_size': len(items), 'items': items }
async def get_responsible_users(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.BuildingRead.value) result_models, count, page_number = apply_filtering( db=db, db_model=ResponsibleUser, request=request) items = [{ 'id': user.id, 'rank': user.rank, 'building_id': user.building_id, 'user': get_user(user.user_id) } for user in result_models] return { 'total_size': count, 'page_number': page_number, 'page_size': len(items), 'items': items }
def dispatch(message, status): """ :type message: ChatMessage :type status: String """ if status == 'SENDING' or status == 'READ': return msg_time = message.Datetime if msg_time < get_minute_ago(): return logger.log_message(message) for e in events: func = events[e] regex = event_regex[e] f = re.findall(regex, message.Body) if len(f) > 0: for found in f: handler = func_handlers[func] handler.add({ 'data': message, 'type': 'event', 'extra': { 'found': found } }) return if not message.Body.startswith('!'): return # Get args and command from message words = message.Body.split() cmd = words[0] cmd = cmd[1:] args = words[1:] # Check for valid command if not cmd in commands: message.Chat.SendMessage("Command not found!") return if cmd in command_permissions: permission = command_permissions[cmd] if not permissions.has_permission(message.Sender.Handle, permission): message.Chat.SendMessage("No permission to execute this command") return # Log command #base = u'Received command \'%s\'' % cmd #if len(args) > 0: # base += u' with arguments: %s' % ' '.join(args) #logger.log(base) # Execute command func = commands[cmd] handler = func_handlers[func] handler.add({'data': message, 'type': 'command'})
async def add_meter(request: Request, body: AddMeterModel, db: Session = Depends(get_db)): has_permission(request, PermissionSet.MeterEdit.value) meter_dict = body.dict() electricity = None if body.type == MeterType.Electricity: electricity_dict = meter_dict.pop('electricity', None) if electricity_dict: electricity = ElectricityMeter(**electricity_dict) else: raise HTTPException(detail='Electricity info is needed', status_code=400) meter = Meter(**meter_dict) meter.electricity = electricity db.add(meter) try: db.commit() except IntegrityError: raise HTTPException(detail='Bad info', status_code=400) return MeterModel.from_orm(meter)
async def patch_meter_snapshot(request: Request, meter_snapshot_id: int, body: ChangeMeterSnapshotModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.MeterSnapshotEdit.value) meter_snapshot = db.query(MeterSnapshot).filter_by(id=meter_snapshot_id).first() previous_type = meter_snapshot.type snapshot_dict = body.dict(exclude_unset=True) heat_dict = snapshot_dict.pop('heat', {}) electricity_dict = snapshot_dict.pop('electricity', {}) args = {k: v for k, v in snapshot_dict.items()} for k, v in args.items(): setattr(meter_snapshot, k, v) if meter_snapshot.type != previous_type: if previous_type == MeterType.Electricity: instance_to_delete = meter_snapshot.electricity_meter_snapshot elif previous_type == MeterType.Heat: instance_to_delete = meter_snapshot.heat_meter_snapshot else: # previous_type == MeterType.Water instance_to_delete = meter_snapshot.water_meter_snapshot db.delete(instance_to_delete) if meter_snapshot.type == MeterType.Electricity: if meter_snapshot.electricity_meter_snapshot: for k, v in electricity_dict.items(): setattr(meter_snapshot.electricity_meter_snapshot, k, v) else: meter_snapshot.electricity_meter_snapshot = ElectricityMeterSnapshot(**electricity_dict) elif meter_snapshot.type == MeterType.Heat: if meter_snapshot.heat_meter_snapshot: for k, v in heat_dict.items(): setattr(meter_snapshot.heat_meter_snapshot, k, v) else: meter_snapshot.heat_meter_snapshot = HeatMeterSnapshot(**heat_dict) db.merge(meter_snapshot) db.commit() return MeterSnapshotModel.from_orm(meter_snapshot)
async def add_meter_snapshot(request: Request, body: AddMeterSnapshotModel, db: Session = Depends(get_db), ): has_permission(request, PermissionSet.MeterSnapshotEdit.value) snapshot_dict = body.dict() snapshot_dict['automatic'] = False heat_dict = snapshot_dict.pop('heat', {}) electricity_dict = snapshot_dict.pop('electricity', {}) meter_snapshot = MeterSnapshot(**snapshot_dict) if body.type == MeterType.Electricity: meter_snapshot.electricity_meter_snapshot = ElectricityMeterSnapshot(**electricity_dict) elif body.type == MeterType.Heat: meter_snapshot.heat_meter_snapshot = HeatMeterSnapshot(**heat_dict) db.add(meter_snapshot) try: db.commit() except IntegrityError: raise HTTPException(detail='Bad info', status_code=400) return MeterSnapshotModel.from_orm(meter_snapshot)
def dispatch(message, status): """ :type message: ChatMessage :type status: String """ if status == 'SENDING' or status == 'READ': return msg_time = message.Datetime if msg_time < get_minute_ago(): return logger.log_message(message) for e in events: func = events[e] regex = event_regex[e] f = re.findall(regex, message.Body) if len(f) > 0: for found in f: handler = func_handlers[func] handler.add({'data': message, 'type': 'event', 'extra': {'found': found}}) return if not message.Body.startswith('!'): return # Get args and command from message words = message.Body.split() cmd = words[0] cmd = cmd[1:] args = words[1:] # Check for valid command if not cmd in commands: message.Chat.SendMessage("Command not found!") return if cmd in command_permissions: permission = command_permissions[cmd] if not permissions.has_permission(message.Sender.Handle, permission): message.Chat.SendMessage("No permission to execute this command") return # Log command #base = u'Received command \'%s\'' % cmd #if len(args) > 0: # base += u' with arguments: %s' % ' '.join(args) #logger.log(base) # Execute command func = commands[cmd] handler = func_handlers[func] handler.add({'data': message, 'type': 'command'})
def test_ObjectBinding(self): # test that permissions can be bound to objects class TestObject(db.Model): name = db.StringProperty(required=True) def __str__(self): return "TestObject:"+self.name o1 = TestObject(name="John").put() o2 = TestObject(name="Paul").put() o3 = TestObject(name="George").put() o4 = TestObject(name="Ringo").put() p1 = permissions.create('read') p2 = permissions.create('write') permissions.bind(p1,o1,o2,o3,o4) permissions.bind(p2,o3,o4) self.assert_(permissions.has_permission(o1,p1),"should return true for permission") self.assert_(permissions.has_permission(o2,p1),"should return true for permission") self.assert_(permissions.has_permission(o3,p1),"should return true for permission") self.assert_(permissions.has_permission(o4,p1),"should return true for permission") self.assert_(permissions.has_permission(o1,p2) == False,"object 1 should not have this permission") self.assert_(permissions.has_permission(o2,p2) == False,"object 2 should not have this permission") self.assert_(permissions.has_permission(o3,p2),"should return true for permission") self.assert_(permissions.has_permission(o4,p2),"should return true for permission")
async def get_locations(request: Request, db: Session = Depends(get_db)): has_permission(request, PermissionSet.LocationRead.value) return paginate(db=db, db_model=Location, serializer=LocationModel, request=request)