Allow usernames to be case-insensitive (#20558)

* Allow usernames to be case-insensitive

* Fix typing

* FLAKE*
This commit is contained in:
Paulus Schoutsen 2019-01-28 23:28:52 -08:00 committed by Pascal Vizeli
parent b0ff51b0ef
commit 73a0c664b8
2 changed files with 40 additions and 11 deletions

View file

@ -2,7 +2,8 @@
import base64
from collections import OrderedDict
import logging
from typing import Any, Dict, List, Optional, cast
from typing import Any, Dict, List, Optional, Set, cast # noqa: F401
import bcrypt
import voluptuous as vol
@ -52,6 +53,9 @@ class Data:
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY,
private=True)
self._data = None # type: Optional[Dict[str, Any]]
# Legacy mode will allow usernames to start/end with whitespace
# and will compare usernames case-insensitive.
# Remove in 2020 or when we launch 1.0.
self.is_legacy = False
@callback
@ -60,7 +64,7 @@ class Data:
if self.is_legacy:
return username
return username.strip()
return username.strip().casefold()
async def async_load(self) -> None:
"""Load stored data."""
@ -71,9 +75,26 @@ class Data:
'users': []
}
seen = set() # type: Set[str]
for user in data['users']:
username = user['username']
# check if we have duplicates
folded = username.casefold()
if folded in seen:
self.is_legacy = True
logging.getLogger(__name__).warning(
"Home Assistant auth provider is running in legacy mode "
"because we detected usernames that are case-insensitive"
"equivalent. Please change the username: '%s'.", username)
break
seen.add(folded)
# check if we have unstripped usernames
if username != username.strip():
self.is_legacy = True
@ -81,7 +102,7 @@ class Data:
logging.getLogger(__name__).warning(
"Home Assistant auth provider is running in legacy mode "
"because we detected usernames that start or end in a "
"space. Please change the username.")
"space. Please change the username: '%s'.", username)
break
@ -103,7 +124,7 @@ class Data:
# Compare all users to avoid timing attacks.
for user in self.users:
if username == user['username']:
if self.normalize_username(user['username']) == username:
found = user
if found is None: