Skip to content

Commit

Permalink
Add check for token age (#217)
Browse files Browse the repository at this point in the history
* Add check for token age

* Adjust tests
  • Loading branch information
epenet authored Nov 27, 2023
1 parent f6351b4 commit be510d8
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/sfrbox_api/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import logging
import time
from functools import wraps
from typing import Any
from typing import Awaitable
Expand Down Expand Up @@ -58,6 +59,7 @@ class SFRBox:
"""SFR Box bridge."""

_token: str | None = None
_token_time: float
_username: str | None = None
_password: str | None = None

Expand All @@ -74,8 +76,11 @@ async def authenticate(self, *, username: str = "admin", password: str) -> None:
await self._ensure_token()

async def _ensure_token(self) -> str:
if not self._token:
# La durée de validité du token semble être de 10 minutes.
# On met 5 minutes (300 secondes) pour éviter les surprises.
if not self._token or (time.time() - self._token_time) > 300:
self._token = await self._get_token()
self._token_time = time.time()
return self._token

async def _get_token(self) -> str:
Expand Down
5 changes: 5 additions & 0 deletions tests/test_bridge.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Test cases for the __main__ module."""
import pathlib
import re
import time

import httpx
import pytest
Expand Down Expand Up @@ -211,6 +212,7 @@ async def test_system_reboot() -> None:
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
box._token = "afd1baa4cb261bfc08ec2dc0ade3b4" # noqa: S105
box._token_time = time.time()
await box.system_reboot()


Expand All @@ -224,6 +226,7 @@ async def test_system_reboot_bad_auth() -> None:
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
box._token = "invalid_token" # noqa: S105
box._token_time = time.time()
with pytest.raises(
SFRBoxAuthenticationError,
match=re.escape("Api call failed: [115] Authentication needed"),
Expand Down Expand Up @@ -264,6 +267,7 @@ async def test_wlan_getclientlist() -> None:
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
box._token = "afd1baa4cb261bfc08ec2dc0ade3b4" # noqa: S105
box._token_time = time.time()
info = await box.wlan_get_client_list()
assert info == WlanClientList(
clients=[
Expand All @@ -283,6 +287,7 @@ async def test_wlan_getinfo() -> None:
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
box._token = "afd1baa4cb261bfc08ec2dc0ade3b4" # noqa: S105
box._token_time = time.time()
info = await box.wlan_get_info()
assert info == WlanInfo(
active="on",
Expand Down

0 comments on commit be510d8

Please sign in to comment.