from app.models.permission import Permission
from flask import current_app


def register_template_helpers(app):
    @app.context_processor
    def inject_permissions():
        def has_permission(user, permission_code):
            """检查用户是否拥有指定权限"""
            if not user or not user.is_authenticated:
                return False

            # 管理员拥有所有权限
            if user.role_id == 1:
                return True

            # 检查用户角色权限
            if user.role:
                for perm in user.role.permissions:
                    if perm.code == permission_code:
                        return True
            return False

        return dict(has_permission=has_permission)

# 在 create_app 函数中调用
# register_template_helpers(app)
