71 lines
2.1 KiB
Markdown
71 lines
2.1 KiB
Markdown
|
|||
|
|
|
||
|
|
```python
|
||
|
|
|
||
|
|
import os
|
||
|
|
from datetime import timedelta
|
||
|
|
|
||
|
|
from homeassistant import auth, core, config as conf_util
|
||
|
|
|
||
|
|
CLIENT_ID = 'long_lived_client'
|
||
|
|
LIFE_TIME = timedelta(days=3650)
|
||
|
|
|
||
|
|
|
||
|
|
async def create_refresh_token(auth_mgr: auth.AuthManager,
|
||
|
|
owner: auth.models.User):
|
||
|
|
"""Create a refresh token for owner."""
|
||
|
|
refresh_token = auth.models.RefreshToken(
|
||
|
|
user=owner,
|
||
|
|
access_token_expiration=LIFE_TIME,
|
||
|
|
client_id=CLIENT_ID,
|
||
|
|
)
|
||
|
|
owner.refresh_tokens[refresh_token.id] = refresh_token
|
||
|
|
|
||
|
|
# hack code to save refresh_token
|
||
|
|
await auth_mgr._store._store.async_save(
|
||
|
|
auth_mgr._store._data_to_save())
|
||
|
|
|
||
|
|
print('Created a new refresh token for {}: {}'.format(
|
||
|
|
CLIENT_ID, refresh_token.id))
|
||
|
|
return refresh_token
|
||
|
|
|
||
|
|
|
||
|
|
async def get_long_live_access_token(auth_mgr: auth.AuthManager):
|
||
|
|
"""Create a bearer token for owner."""
|
||
|
|
owner = [u for u in await auth_mgr.async_get_users() if u.is_owner][0]
|
||
|
|
print('Owner name is {}\n'.format(owner.name))
|
||
|
|
|
||
|
|
refresh_token = None
|
||
|
|
for token in owner.refresh_tokens.values():
|
||
|
|
if token.client_id == CLIENT_ID:
|
||
|
|
refresh_token = token
|
||
|
|
break
|
||
|
|
|
||
|
|
if not refresh_token:
|
||
|
|
refresh_token = await create_refresh_token(auth_mgr, owner)
|
||
|
|
|
||
|
|
# get access_token, it won't saved
|
||
|
|
access_token = auth_mgr.async_create_access_token(refresh_token)
|
||
|
|
print('Add following HTTP header to your REST API'
|
||
|
|
' and Websocket API request:')
|
||
|
|
print('Authorization: Bearer {}'.format(access_token))
|
||
|
|
|
||
|
|
|
||
|
|
# change to your config path
|
||
|
|
config_dir = conf_util.get_default_config_dir()
|
||
|
|
config_path = conf_util.ensure_config_exists(config_dir)
|
||
|
|
print('Loading config from {}'.format(config_path))
|
||
|
|
config_dict = conf_util.load_yaml_config_file(config_path)
|
||
|
|
core_config = config_dict.get('homeassistant', {})
|
||
|
|
|
||
|
|
hass = core.HomeAssistant()
|
||
|
|
hass.config.config_dir = os.path.abspath(os.path.dirname(config_path))
|
||
|
|
hass.loop.run_until_complete(
|
||
|
|
conf_util.async_process_ha_core_config(
|
||
|
|
hass, core_config, False, False))
|
||
|
|
hass.loop.run_until_complete(
|
||
|
|
get_long_live_access_token(hass.auth))
|
||
|
|
|
||
|
|
```
|
||
|
|
|