create a new token if credentials are given once current one expired

This commit is contained in:
əlemi 2021-12-15 13:06:01 +01:00
parent 12878d856d
commit 7621021b83

View file

@ -83,6 +83,9 @@ class MinecraftClient(CallbacksHolder, Runnable):
self.password = password self.password = password
self.online_mode = online_mode self.online_mode = online_mode
if self.online_mode and not self.token and not self.username and not self.password:
raise ValueError("Cannot instantiate an online-mode client without token or credentials")
self.dispatcher = Dispatcher() self.dispatcher = Dispatcher()
self._processing = False self._processing = False
self._authenticated = False self._authenticated = False
@ -115,24 +118,30 @@ class MinecraftClient(CallbacksHolder, Runnable):
return fun return fun
return wrapper return wrapper
async def authenticate(self) -> bool: async def authenticate(self):
if self._authenticated: if self._authenticated:
return True # Don't spam Auth endpoint! return # Don't spam Auth endpoint!
if not self.token: if self.token:
if self.username and self.password: try:
self.token = await Token.authenticate(self.username, self.password) await self.token.validate() # will raise an exc if token is invalid
self._logger.info("Authenticated from credentials")
self._authenticated = True self._authenticated = True
return True return
raise AuthException("No token or credentials provided") except AuthException:
try: try:
await self.token.validate() # will raise an exc if token is invalid await self.token.refresh()
self._logger.warning("Refreshed Token")
self._authenticated = True
return
except AuthException as e:
self._logger.warning("Token is not refreshable : %s", e.message)
if not self.username and not self.password:
raise e # we don't have credentials to make a new token, nothing we can really do here
if self.username and self.password:
self.token = await Token.authenticate(self.username, self.password)
self._logger.info("Authenticated from credentials")
self._authenticated = True self._authenticated = True
except AuthException: return
await self.token.refresh() raise ValueError("No token or credentials to authenticate") # This should never happen
self._authenticated = True
self._logger.warning("Refreshed Token")
return True
async def change_server(self, server:str): async def change_server(self, server:str):
restart = self.started restart = self.started