-
-
Notifications
You must be signed in to change notification settings - Fork 37.2k
Hassio auth #17274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Hassio auth #17274
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
160f16a
Create auth.py
pvizeli 88582d8
Update auth.py
pvizeli c3ea7b9
Update auth.py
pvizeli bec27ae
Update __init__.py
pvizeli 900cf1a
Update auth.py
pvizeli 4a35ea9
Update auth.py
pvizeli 8dae06d
Update auth.py
pvizeli bc72cfd
Update auth.py
pvizeli 6d56ce5
Update auth.py
pvizeli c9aafbf
Update auth.py
pvizeli fd989f4
Update auth.py
pvizeli 683c927
Update auth.py
pvizeli cbf4a67
Update auth.py
pvizeli 09e39a8
Add tests
pvizeli 311014d
Update test_auth.py
pvizeli 7ed5cc8
Update auth.py
pvizeli e6f89b9
Update test_auth.py
pvizeli 9ed9133
Update auth.py
pvizeli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| """Implement the auth feature from Hass.io for Add-ons.""" | ||
| import logging | ||
| from ipaddress import ip_address | ||
| import os | ||
|
|
||
| from aiohttp import web | ||
| from aiohttp.web_exceptions import ( | ||
balloob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| HTTPForbidden, HTTPNotFound, HTTPUnauthorized) | ||
| import voluptuous as vol | ||
|
|
||
| from homeassistant.core import callback | ||
| import homeassistant.helpers.config_validation as cv | ||
| from homeassistant.exceptions import HomeAssistantError | ||
| from homeassistant.components.http import HomeAssistantView | ||
| from homeassistant.components.http.const import KEY_REAL_IP | ||
| from homeassistant.components.http.data_validator import RequestDataValidator | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| ATTR_USERNAME = 'username' | ||
| ATTR_PASSWORD = 'password' | ||
|
|
||
|
|
||
| SCHEMA_API_AUTH = vol.Schema({ | ||
| vol.Required(ATTR_USERNAME): cv.string, | ||
| vol.Required(ATTR_PASSWORD): cv.string, | ||
| }) | ||
|
|
||
|
|
||
| @callback | ||
| def async_setup_auth(hass): | ||
| """Auth setup.""" | ||
| hassio_auth = HassIOAuth(hass) | ||
| hass.http.register_view(hassio_auth) | ||
|
|
||
|
|
||
| class HassIOAuth(HomeAssistantView): | ||
| """Hass.io view to handle base part.""" | ||
|
|
||
| name = "api:hassio_auth" | ||
| url = "/api/hassio_auth" | ||
|
|
||
| def __init__(self, hass): | ||
| """Initialize WebView.""" | ||
| self.hass = hass | ||
|
|
||
| @RequestDataValidator(SCHEMA_API_AUTH) | ||
| async def post(self, request, data): | ||
| """Handle new discovery requests.""" | ||
| hassio_ip = os.environ['HASSIO'].split(':')[0] | ||
| if request[KEY_REAL_IP] != ip_address(hassio_ip): | ||
| _LOGGER.error( | ||
| "Invalid auth request from %s", request[KEY_REAL_IP]) | ||
| raise HTTPForbidden() | ||
|
|
||
| await self._check_login(data[ATTR_USERNAME], data[ATTR_PASSWORD]) | ||
| return web.Response(status=200) | ||
|
|
||
| def _get_provider(self): | ||
| """Return Homeassistant auth provider.""" | ||
| for prv in self.hass.auth.auth_providers: | ||
| if prv.type == 'homeassistant': | ||
| return prv | ||
|
|
||
| _LOGGER.error("Can't find Home Assistant auth.") | ||
| raise HTTPNotFound() | ||
|
|
||
| async def _check_login(self, username, password): | ||
| """Check User credentials.""" | ||
| provider = self._get_provider() | ||
|
|
||
pvizeli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| try: | ||
| await provider.async_validate_login(username, password) | ||
| except HomeAssistantError: | ||
| raise HTTPUnauthorized() from None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| """The tests for the hassio component.""" | ||
| from unittest.mock import patch, Mock | ||
|
|
||
| from homeassistant.const import HTTP_HEADER_HA_AUTH | ||
| from homeassistant.exceptions import HomeAssistantError | ||
|
|
||
| from tests.common import mock_coro, register_auth_provider | ||
| from . import API_PASSWORD | ||
|
|
||
|
|
||
| async def test_login_success(hass, hassio_client): | ||
| """Test no auth needed for .""" | ||
| await register_auth_provider(hass, {'type': 'homeassistant'}) | ||
|
|
||
| with patch('homeassistant.auth.providers.homeassistant.' | ||
| 'HassAuthProvider.async_validate_login', | ||
| Mock(return_value=mock_coro())) as mock_login: | ||
| resp = await hassio_client.post( | ||
| '/api/hassio_auth', | ||
| json={ | ||
| "username": "test", | ||
| "password": "123456" | ||
| }, | ||
| headers={ | ||
| HTTP_HEADER_HA_AUTH: API_PASSWORD | ||
| } | ||
| ) | ||
|
|
||
| # Check we got right response | ||
| assert resp.status == 200 | ||
| mock_login.assert_called_with("test", "123456") | ||
|
|
||
|
|
||
| async def test_login_error(hass, hassio_client): | ||
| """Test no auth needed for error.""" | ||
| await register_auth_provider(hass, {'type': 'homeassistant'}) | ||
|
|
||
| with patch('homeassistant.auth.providers.homeassistant.' | ||
| 'HassAuthProvider.async_validate_login', | ||
| Mock(side_effect=HomeAssistantError())) as mock_login: | ||
| resp = await hassio_client.post( | ||
| '/api/hassio_auth', | ||
| json={ | ||
| "username": "test", | ||
| "password": "123456" | ||
| }, | ||
| headers={ | ||
| HTTP_HEADER_HA_AUTH: API_PASSWORD | ||
| } | ||
| ) | ||
|
|
||
| # Check we got right response | ||
| assert resp.status == 401 | ||
| mock_login.assert_called_with("test", "123456") | ||
|
|
||
|
|
||
| async def test_login_no_data(hass, hassio_client): | ||
| """Test auth with no data -> error.""" | ||
| await register_auth_provider(hass, {'type': 'homeassistant'}) | ||
|
|
||
| with patch('homeassistant.auth.providers.homeassistant.' | ||
| 'HassAuthProvider.async_validate_login', | ||
| Mock(side_effect=HomeAssistantError())) as mock_login: | ||
| resp = await hassio_client.post( | ||
| '/api/hassio_auth', | ||
| headers={ | ||
| HTTP_HEADER_HA_AUTH: API_PASSWORD | ||
| } | ||
| ) | ||
|
|
||
| # Check we got right response | ||
| assert resp.status == 400 | ||
| assert not mock_login.called | ||
|
|
||
|
|
||
| async def test_login_no_username(hass, hassio_client): | ||
| """Test auth with no username in data -> error.""" | ||
| await register_auth_provider(hass, {'type': 'homeassistant'}) | ||
|
|
||
| with patch('homeassistant.auth.providers.homeassistant.' | ||
| 'HassAuthProvider.async_validate_login', | ||
| Mock(side_effect=HomeAssistantError())) as mock_login: | ||
| resp = await hassio_client.post( | ||
| '/api/hassio_auth', | ||
| json={ | ||
| "password": "123456" | ||
| }, | ||
| headers={ | ||
| HTTP_HEADER_HA_AUTH: API_PASSWORD | ||
| } | ||
| ) | ||
|
|
||
| # Check we got right response | ||
| assert resp.status == 400 | ||
| assert not mock_login.called |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.