From 238333a1755ce28f221fb20e7a98a3dfe07d2f12 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Thu, 29 Oct 2020 15:40:30 +0100 Subject: [PATCH] Store auth token to don't login everytime --- apps/participation/views.py | 3 +++ corres2math/matrix.py | 29 +++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/apps/participation/views.py b/apps/participation/views.py index 8767091..1353c39 100644 --- a/apps/participation/views.py +++ b/apps/participation/views.py @@ -262,6 +262,9 @@ class TeamLeaveView(LoginRequiredMixin, TemplateView): request.user.registration.team = None request.user.registration.save() get_sympa_client().unsubscribe(request.user.email, f"equipe-{team.trigram.lower()}", False) + Matrix.kick(f"#team-{team.trigram.lower()}:correspondances-maths.fr", + f"@{request.user.registration.matrix_username}:correspondances-maths.fr", + "Équipe quittée") if team.students.count() + team.coachs.count() == 0: team.delete() return redirect(reverse_lazy("index")) diff --git a/corres2math/matrix.py b/corres2math/matrix.py index 35ba498..65fa8a1 100644 --- a/corres2math/matrix.py +++ b/corres2math/matrix.py @@ -1,3 +1,4 @@ +import os from typing import Any, Dict, Optional, Union from asgiref.sync import async_to_sync @@ -6,11 +7,27 @@ from nio import AsyncClient, RoomCreateError, RoomCreateResponse, RoomKickRespon class Matrix: + _token: str = None + _device_id: str = None + @classmethod async def _get_client(cls) -> AsyncClient: - # TODO Store client = AsyncClient("https://correspondances-maths.fr", "@corres2mathbot:correspondances-maths.fr") - await client.login("toto1234") + + if os.path.isfile(".matrix_token"): + with open(".matrix_device", "r") as f: + cls._device_id = f.read().rstrip(" \t\r\n") + client.device_id = cls._device_id + with open(".matrix_token", "r") as f: + cls._token = f.read().rstrip(" \t\r\n") + client.access_token = cls._token + return client + + await client.login(password="toto1234", device_name="Plateforme") + cls._token = client.access_token + cls._device_id = client.device_id + with open(".matrix_token", "w") as f: + f.write(cls._token) return client @classmethod @@ -49,3 +66,11 @@ class Matrix: if room_id.startswith("#"): room_id = await cls.resolve_room_alias(room_id) return await client.room_invite(room_id, user_id) + + @classmethod + @async_to_sync + async def kick(cls, room_id: str, user_id: str, reason: str = None) -> Union[RoomKickResponse, RoomInviteError]: + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_kick(room_id, user_id, reason)