From 505ce8308f48b0c5b6dda0552f5767969944f212 Mon Sep 17 00:00:00 2001 From: tiagovla Date: Tue, 4 Oct 2022 01:24:11 -0300 Subject: [PATCH] feat: add is_logged check to methods that require auth --- ppgee/client.py | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/ppgee/client.py b/ppgee/client.py index 99b84ff..4bf43f7 100644 --- a/ppgee/client.py +++ b/ppgee/client.py @@ -2,16 +2,29 @@ import aiohttp import logging from ppgee.http import HttpClient from ppgee.pages import FrequencyPage +from functools import wraps logger = logging.getLogger(__name__) +def is_logged_check(method): + @wraps(method) + def wrapper(self, *args, **kwargs): + print("checking if logged in", self.is_logged) + if not self.is_logged: + raise Exception("You must be logged in to use this method") + return method(self, *args, **kwargs) + + return wrapper + + class PPGEE: - def __init__(self, user: str, password: str) -> None: + def __init__(self, user: str | None = None, password: str | None = None) -> None: self.user = user self.password = password self.session: aiohttp.ClientSession self.http: HttpClient + self.is_logged: bool = False async def start(self): self.session = aiohttp.ClientSession() @@ -27,18 +40,26 @@ class PPGEE: return self async def __aexit__(self, exc_type, exc, tb) -> None: - await self.logoff() + if self.is_logged: + await self.logoff() await self.close() - async def login(self) -> str: + async def login(self) -> None: logger.info("Logging in...") - return await self.http.login(self.user, self.password) + if self.user and self.password: + await self.http.login(self.user, self.password) + self.is_logged = True + else: + logger.info("Logged in without credentials") + @is_logged_check async def frequency(self) -> FrequencyPage: logger.info("Requesting frequency page...") html = await self.http.frequency() return FrequencyPage(html, self.http.frequency_confirmation) - async def logoff(self) -> str: + @is_logged_check + async def logoff(self) -> None: logger.info("Logging off...") - return await self.http.logoff() + self.is_logged = False + await self.http.logoff()