def leave_room(user: OnlineUser, room: str) -> None: rooms_for_user = redis_client.hget('rooms_per_user', user.username) users_for_room = redis_client.hget('users_per_room', room) rooms_for_user.pop(rooms_for_user.index(room)) users_for_room.pop(users_for_room.index(user.username)) redis_client.hset('rooms_per_user', user.username, rooms_for_user) redis_client.hset('users_per_room', room, users_for_room)
def goto_room(user: OnlineUser, room: str) -> None: rooms_for_user = redis_client.hget('rooms_per_user', user.username) users_for_room = redis_client.hget('users_per_room', room) rooms_for_user.append(room) users_for_room.append(user.username) redis_client.hset('rooms_per_user', user.username, rooms_for_user) redis_client.hset('users_per_room', room, users_for_room)
def disable_device(device_id): device = Device.query.filter_by(id=device_id).first() if device: claims = get_jwt_claims() user_id = claims['id'] result = redis_client.hget("user_{user_id}".format(user_id=user_id), "roles") if result: roles = json.loads(result.decode('utf-8')) if "admin" in roles or device.owner_id == user_id: if request.json.get("disable") == "true": details = "禁用设备。" device.status = 0 else: details = "启用设备。" device.status = 1 try: db.session.add(device) db.session.commit() device_log = DeviceLog(device_id=device.id, operator_id=user_id, details=details) db.session.add(device_log) db.session.commit() return generate_response() except Exception as e: current_app.logger.error(str(e)) db.session.rollback() return generate_response(code_msg=Code.DISABLE_DEVICE_FAILED)
def get_roles_from_redis(user): result = redis_client.hget("user_{user_id}".format(user_id=user.id), "roles") if result: return json.loads(result.decode('utf-8')) roles = set() if user.roles: for role in user.roles: roles.add(role.name) redis_client.hset("user_{user_id}".format(user_id=user.id), "roles", json.dumps(list(sorted(roles)))) redis_client.expire("user_{user_id}".format(user_id=user.id), current_app.config['JWT_ACCESS_TOKEN_EXPIRES']) return list(sorted(roles))
def wrapper(*args, **kwargs): verify_jwt_in_request() claims = get_jwt_claims() # admin角色可以访问所有 result = redis_client.hget( "user_{user_id}".format(user_id=claims['id']), "roles") if result: roles = json.loads(result.decode('utf-8')) if "admin" in roles: return func(*args, **kwargs) # 或者有操作权限 permissions = get_permissions_from_redis(claims['id']) if permission in permissions: return func(*args, **kwargs) return generate_response(code_msg=Code.PERMISSION_DENIED), 403
def get_permissions_from_redis(user_id): result = redis_client.hget("user_{user_id}".format(user_id=user_id), "permissions") if result: return json.loads(result.decode('utf-8')) permissions = set() user = User.query.filter_by(id=user_id).first() if user.roles: for role in user.roles: for permission in role.permissions: permissions.add(permission.path) if permissions: redis_client.hset("user_{user_id}".format(user_id=user_id), "permissions", json.dumps(list(sorted(permissions)))) redis_client.expire("user_{user_id}".format(user_id=user_id), current_app.config['JWT_ACCESS_TOKEN_EXPIRES']) return list(sorted(permissions))
def process_property_listing_images(redis_img_dict_key): """ Resize the image file using the PIL image library and save it to the app server or Amazon S3 depending on the configuration. Since a property listing has many images, a directory is created with redis_img_dict_key as the directory name where the image files are saved. """ temp_image_path = Path( f"{current_app.root_path}/base/static/{temp_image_dir}") redis_images = redis_client.hgetall(redis_img_dict_key) folder_to_save_image = Path( f"{current_app.root_path}/base/static/{property_listing_images_dir}{redis_img_dict_key}" ) folder_to_save_image.mkdir(parents=True, exist_ok=True) for image_filename in redis_images.keys(): image_filename = image_filename.decode("utf-8") image_file = redis_client.hget(redis_img_dict_key, image_filename) image_obj = Image.open(io.BytesIO(image_file)) image_obj.thumbnail((800, 800)) image_obj.save( f"{current_app.root_path}/base/static/{temp_image_dir}{image_filename}" ) if image_server_config == "app_server_storage": shutil.copyfile( f"{temp_image_path}/{image_filename}", f"{folder_to_save_image}/{image_filename}", ) os.remove( f"{temp_image_path}/{image_filename}" ) # Clean up by deleting the image in the temporary folder redis_client.hdel( redis_img_dict_key, image_filename) # Clean up by deleting the image in redis elif image_server_config == "amazon_s3": # Upload the image to Amazon S3 if the configuration is set to "amazon_s3" property_image_upload_to_S3.delay(image_filename, redis_img_dict_key)
def audit(apply_id): claims = get_jwt_claims() auditor_id = claims['id'] apply_record = DeviceApplyRecord.query.filter_by(id=apply_id).first() device = Device.query.filter_by(id=apply_record.device_id).first() # 审批“申请中”、“归还中” if apply_record and apply_record.status in [1, 4] and device: auditor_is_admin = False audit_or_not = False result = redis_client.hget("user_{user_id}".format(user_id=auditor_id), "roles") if result: roles = json.loads(result.decode('utf-8')) if "admin" in roles: auditor_is_admin = True # admin角色可以审批所有申请、归还记录 if auditor_is_admin: audit_or_not = True else: # 非admin角色只能处理owner是自己的申请、归还记录。 if device.owner_id == auditor_id: audit_or_not = True if audit_or_not: # 审批申请 if apply_record.status == 1: apply_record.apply_audit_reason = request.json.get("reason") apply_record.apply_auditor_id = auditor_id if request.json.get("approval") == 1: apply_record.status = 2 device.current_user_id = apply_record.applicant_id # 若借用出去,且current_user!=owner,状态变成借用中。 if device.current_user_id != device.owner_id: device.status = 2 details = "通过{applicant}的申请".format( applicant=apply_record.applicant.realname) else: apply_record.status = 3 details = "拒绝{applicant}的申请".format( applicant=apply_record.applicant.realname) # 审批归还 else: apply_record.return_audit_reason = request.json.get("reason") apply_record.return_auditor_id = auditor_id if request.json.get("approval") == 1: apply_record.status = 5 device.current_user_id = None details = "通过{applicant}的归还".format( applicant=apply_record.applicant.realname) else: apply_record.status = 6 details = "拒绝{applicant}的归还".format( applicant=apply_record.applicant.realname) try: db.session.add(apply_record) db.session.add(device) db.session.commit() device_log = DeviceLog(device_id=device.id, operator_id=claims['id'], details=details) db.session.add(device_log) db.session.commit() return generate_response() except Exception as e: current_app.logger.error(str(e)) db.session.rollback() return generate_response(code_msg=Code.APPLY_DEVICE_AUDIT_FAILED)
def spend_today(self): report_key = KEY_SPACE_REPORT + '%s:%s' % ( self.id, datetime.utcnow().date().isoformat()) return float(redis_client.hget(report_key, 'spend') or 0)