mirror of
https://github.com/home-assistant/core.git
synced 2025-12-27 14:31:13 +00:00
Add a service require_admin wrapper (#21953)
* Add a service require_admin wrapper * Allow it to be used as a decorator * Lint * Add comment * Add docstring * Update syntax
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
"""Service calling related helpers."""
|
||||
import asyncio
|
||||
from functools import wraps
|
||||
import logging
|
||||
from os import path
|
||||
from typing import Callable
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
@@ -10,7 +12,7 @@ from homeassistant.const import (
|
||||
ATTR_ENTITY_ID, ENTITY_MATCH_ALL, ATTR_AREA_ID)
|
||||
import homeassistant.core as ha
|
||||
from homeassistant.exceptions import TemplateError, Unauthorized, UnknownUser
|
||||
from homeassistant.helpers import template
|
||||
from homeassistant.helpers import template, typing
|
||||
from homeassistant.loader import get_component, bind_hass
|
||||
from homeassistant.util.yaml import load_yaml
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
@@ -335,3 +337,25 @@ async def _handle_service_platform_call(func, data, entities, context):
|
||||
assert not pending
|
||||
for future in done:
|
||||
future.result() # pop exception if have
|
||||
|
||||
|
||||
@bind_hass
|
||||
@ha.callback
|
||||
def async_register_admin_service(hass: typing.HomeAssistantType, domain: str,
|
||||
service: str, service_func: Callable,
|
||||
schema: vol.Schema) -> None:
|
||||
"""Register a service that requires admin access."""
|
||||
@wraps(service_func)
|
||||
async def admin_handler(call):
|
||||
if call.context.user_id:
|
||||
user = await hass.auth.async_get_user(call.context.user_id)
|
||||
if user is None:
|
||||
raise UnknownUser(context=call.context)
|
||||
if not user.is_admin:
|
||||
raise Unauthorized(context=call.context)
|
||||
|
||||
await hass.async_add_job(service_func, call)
|
||||
|
||||
hass.services.async_register(
|
||||
domain, service, admin_handler, schema
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user