Home Assistant Unofficial Reference 2024.12.1
decorators.py
Go to the documentation of this file.
1 """Decorators for the Home Assistant API."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 from functools import wraps
7 from typing import Any, Concatenate, overload
8 
9 from aiohttp.web import Request, Response, StreamResponse
10 
11 from homeassistant.auth.models import User
12 from homeassistant.exceptions import Unauthorized
13 
14 from .view import HomeAssistantView
15 
16 type _ResponseType = Response | StreamResponse
17 type _FuncType[_T, **_P, _R] = Callable[
18  Concatenate[_T, Request, _P], Coroutine[Any, Any, _R]
19 ]
20 
21 
22 @overload
24  _HomeAssistantViewT: HomeAssistantView,
25  **_P,
26  _ResponseT: _ResponseType,
27 ](
28  _func: None = None,
29  *,
30  error: Unauthorized | None = None,
31 ) -> Callable[
32  [_FuncType[_HomeAssistantViewT, _P, _ResponseT]],
33  _FuncType[_HomeAssistantViewT, _P, _ResponseT],
34 ]: ...
35 
36 
37 @overload
38 def require_admin[
39  _HomeAssistantViewT: HomeAssistantView,
40  **_P,
41  _ResponseT: _ResponseType,
42 ](
43  _func: _FuncType[_HomeAssistantViewT, _P, _ResponseT],
44 ) -> _FuncType[_HomeAssistantViewT, _P, _ResponseT]: ...
45 
46 
47 def require_admin[
48  _HomeAssistantViewT: HomeAssistantView,
49  **_P,
50  _ResponseT: _ResponseType,
51 ](
52  _func: _FuncType[_HomeAssistantViewT, _P, _ResponseT] | None = None,
53  *,
54  error: Unauthorized | None = None,
55 ) -> (
56  Callable[
57  [_FuncType[_HomeAssistantViewT, _P, _ResponseT]],
58  _FuncType[_HomeAssistantViewT, _P, _ResponseT],
59  ]
60  | _FuncType[_HomeAssistantViewT, _P, _ResponseT]
61 ):
62  """Home Assistant API decorator to require user to be an admin."""
63 
64  def decorator_require_admin(
65  func: _FuncType[_HomeAssistantViewT, _P, _ResponseT],
66  ) -> _FuncType[_HomeAssistantViewT, _P, _ResponseT]:
67  """Wrap the provided with_admin function."""
68 
69  @wraps(func)
70  async def with_admin(
71  self: _HomeAssistantViewT,
72  request: Request,
73  *args: _P.args,
74  **kwargs: _P.kwargs,
75  ) -> _ResponseT:
76  """Check admin and call function."""
77  user: User = request["hass_user"]
78  if not user.is_admin:
79  raise error or Unauthorized()
80 
81  return await func(self, request, *args, **kwargs)
82 
83  return with_admin
84 
85  # See if we're being called as @require_admin or @require_admin().
86  if _func is None:
87  # We're called with brackets.
88  return decorator_require_admin
89 
90  # We're called as @require_admin without brackets.
91  return decorator_require_admin(_func)
const .WebSocketCommandHandler require_admin(const .WebSocketCommandHandler func)
Definition: decorators.py:56