Add current user WS command (#15485)

This commit is contained in:
Paulus Schoutsen 2018-07-17 09:24:51 +02:00 committed by GitHub
parent 7eb5cd1267
commit 8797cb78a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 62 additions and 1 deletions

View File

@ -194,9 +194,14 @@ class AuthManager:
tkn = self._access_tokens.get(token)
if tkn is None:
_LOGGER.debug('Attempt to get non-existing access token')
return None
if tkn.expired or not tkn.refresh_token.user.is_active:
if tkn.expired:
_LOGGER.debug('Attempt to get expired access token')
else:
_LOGGER.debug('Attempt to get access token for inactive user')
self._access_tokens.pop(token)
return None

View File

@ -113,6 +113,7 @@ from homeassistant import data_entry_flow
from homeassistant.core import callback
from homeassistant.helpers.data_entry_flow import (
FlowManagerIndexView, FlowManagerResourceView)
from homeassistant.components import websocket_api
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.util import dt as dt_util
@ -122,6 +123,12 @@ from . import indieauth
DOMAIN = 'auth'
DEPENDENCIES = ['http']
WS_TYPE_CURRENT_USER = 'auth/current_user'
SCHEMA_WS_CURRENT_USER = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_CURRENT_USER,
})
_LOGGER = logging.getLogger(__name__)
@ -136,6 +143,11 @@ async def async_setup(hass, config):
hass.http.register_view(GrantTokenView(retrieve_credentials))
hass.http.register_view(LinkUserView(retrieve_credentials))
hass.components.websocket_api.async_register_command(
WS_TYPE_CURRENT_USER, websocket_current_user,
SCHEMA_WS_CURRENT_USER
)
return True
@ -383,3 +395,20 @@ def _create_cred_store():
return None
return store_credentials, retrieve_credentials
@callback
def websocket_current_user(hass, connection, msg):
"""Return the current user."""
user = connection.request.get('hass_user')
if user is None:
connection.to_write.put_nowait(websocket_api.error_message(
msg['id'], 'no_user', 'Not authenticated as a user'))
return
connection.to_write.put_nowait(websocket_api.result_message(msg['id'], {
'id': user.id,
'name': user.name,
'is_owner': user.is_owner,
}))

View File

@ -257,7 +257,7 @@ async def async_setup(hass, config):
await asyncio.wait(
[async_register_built_in_panel(hass, panel) for panel in (
'dev-event', 'dev-info', 'dev-service', 'dev-state',
'dev-template', 'dev-mqtt', 'kiosk', 'lovelace')],
'dev-template', 'dev-mqtt', 'kiosk', 'lovelace', 'profile')],
loop=hass.loop)
hass.data[DATA_FINALIZE_PANEL] = async_finalize_panel

View File

@ -2,6 +2,7 @@
from datetime import timedelta
from unittest.mock import patch
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from homeassistant.components import auth
@ -66,3 +67,29 @@ def test_credential_store_expiration():
with patch('homeassistant.util.dt.utcnow',
return_value=now + timedelta(minutes=9, seconds=59)):
assert retrieve(client_id, code) == credentials
async def test_ws_current_user(hass, hass_ws_client, hass_access_token):
"""Test the current user command."""
assert await async_setup_component(hass, 'auth', {
'http': {
'api_password': 'bla'
}
})
with patch('homeassistant.auth.AuthManager.active', return_value=True):
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth.WS_TYPE_CURRENT_USER,
})
result = await client.receive_json()
assert result['success'], result
user = hass_access_token.refresh_token.user
user_dict = result['result']
assert user_dict['name'] == user.name
assert user_dict['id'] == user.id
assert user_dict['is_owner'] == user.is_owner