Home Assistant Unofficial Reference 2024.12.1
insecure_example.py
Go to the documentation of this file.
1 """Example auth module."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 import voluptuous as vol
8 
9 from homeassistant.core import HomeAssistant
10 
11 from . import (
12  MULTI_FACTOR_AUTH_MODULE_SCHEMA,
13  MULTI_FACTOR_AUTH_MODULES,
14  MultiFactorAuthModule,
15  SetupFlow,
16 )
17 
18 CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend(
19  {
20  vol.Required("data"): [
21  vol.Schema({vol.Required("user_id"): str, vol.Required("pin"): str})
22  ]
23  },
24  extra=vol.PREVENT_EXTRA,
25 )
26 
27 
28 @MULTI_FACTOR_AUTH_MODULES.register("insecure_example")
29 class InsecureExampleModule(MultiFactorAuthModule):
30  """Example auth module validate pin."""
31 
32  DEFAULT_TITLE = "Insecure Personal Identify Number"
33 
34  def __init__(self, hass: HomeAssistant, config: dict[str, Any]) -> None:
35  """Initialize the user data store."""
36  super().__init__(hass, config)
37  self._data_data = config["data"]
38 
39  @property
40  def input_schema(self) -> vol.Schema:
41  """Validate login flow input data."""
42  return vol.Schema({vol.Required("pin"): str})
43 
44  @property
45  def setup_schema(self) -> vol.Schema:
46  """Validate async_setup_user input data."""
47  return vol.Schema({vol.Required("pin"): str})
48 
49  async def async_setup_flow(self, user_id: str) -> SetupFlow:
50  """Return a data entry flow handler for setup module.
51 
52  Mfa module should extend SetupFlow
53  """
54  return SetupFlow(self, self.setup_schemasetup_schema, user_id)
55 
56  async def async_setup_user(self, user_id: str, setup_data: Any) -> Any:
57  """Set up user to use mfa module."""
58  # data shall has been validate in caller
59  pin = setup_data["pin"]
60 
61  for data in self._data_data:
62  if data["user_id"] == user_id:
63  # already setup, override
64  data["pin"] = pin
65  return
66 
67  self._data_data.append({"user_id": user_id, "pin": pin})
68 
69  async def async_depose_user(self, user_id: str) -> None:
70  """Remove user from mfa module."""
71  found = None
72  for data in self._data_data:
73  if data["user_id"] == user_id:
74  found = data
75  break
76  if found:
77  self._data_data.remove(found)
78 
79  async def async_is_user_setup(self, user_id: str) -> bool:
80  """Return whether user is setup."""
81  return any(data["user_id"] == user_id for data in self._data_data)
82 
83  async def async_validate(self, user_id: str, user_input: dict[str, Any]) -> bool:
84  """Return True if validation passed."""
85  return any(
86  data["user_id"] == user_id and data["pin"] == user_input["pin"]
87  for data in self._data_data
88  )
bool async_validate(self, str user_id, dict[str, Any] user_input)
None __init__(self, HomeAssistant hass, dict[str, Any] config)
bool remove(self, _T matcher)
Definition: match.py:214