attempt to make client module use server endpoint

This commit is contained in:
PC-Admin 2023-08-13 00:53:50 +08:00
parent c46e73865f
commit 17a750eb54

View File

@ -1,34 +1,29 @@
import logging import logging
import hashlib import hashlib
import json
import http.client
from typing import Union from typing import Union
from synapse.module_api import ModuleApi from synapse.module_api import ModuleApi
from synapse.api.errors import AuthError from synapse.api.errors import AuthError
from twisted.internet import defer
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class RedlightClientModule: class RedlightClientModule:
def __init__(self, config: dict, api: ModuleApi): def __init__(self, config: dict, api: ModuleApi):
self._api = api self._api = api
self._redlight_url = config.get("redlight_url", "https://duckdomain.xyz/_matrix/loj/v1/abuse_lookup")
# Log a message to indicate the module's initialization
logger.info("RedLightClientModule initialized.") logger.info("RedLightClientModule initialized.")
# Register the spam checker callback
api.register_spam_checker_callbacks( api.register_spam_checker_callbacks(
user_may_join_room=self.user_may_join_room user_may_join_room=self.user_may_join_room
) )
@staticmethod @staticmethod
def double_hash_sha256(data: str) -> str: def double_hash_sha256(data: str) -> str:
"""
Double hash the given data using SHA-256.
Args:
data (str): The data to hash.
Returns:
str: The double-hashed data in hexadecimal format.
"""
first_hash = hashlib.sha256(data.encode()).digest() first_hash = hashlib.sha256(data.encode()).digest()
double_hashed = hashlib.sha256(first_hash).hexdigest() double_hashed = hashlib.sha256(first_hash).hexdigest()
return double_hashed return double_hashed
@ -37,28 +32,36 @@ class RedlightClientModule:
self, user: str, room: str, is_invited: bool self, user: str, room: str, is_invited: bool
) -> Union["synapse.module_api.NOT_SPAM", "synapse.module_api.errors.Codes"]: ) -> Union["synapse.module_api.NOT_SPAM", "synapse.module_api.errors.Codes"]:
# Log the event of a user trying to join a room
logger.info(f"User {user} is attempting to join room {room}. Invitation status: {is_invited}.") logger.info(f"User {user} is attempting to join room {room}. Invitation status: {is_invited}.")
# Here's how you can use the double hashing function:
hashed_room_id = self.double_hash_sha256(room) hashed_room_id = self.double_hash_sha256(room)
logger.info(f"Double hashed room ID: {hashed_room_id}")
# Double hash the username
hashed_user_id = self.double_hash_sha256(user) hashed_user_id = self.double_hash_sha256(user)
logger.info(f"Double hashed user ID: {hashed_user_id}")
# Log the desired message # Send the PUT request
logger.info("Hello World!") connection = http.client.HTTPSConnection("localhost:8008")
headers = {
"Content-Type": "application/json"
}
body = json.dumps({
"room_id_hash": hashed_room_id,
"user_id_hash": hashed_user_id
})
connection.request("PUT", "/_matrix/loj/v1/abuse_lookup", body, headers)
response = connection.getresponse()
response_body = response.read()
# Raise an AuthError to indicate the operation is forbidden # Process the response from the server
raise AuthError(403, "User not allowed to join this room") result = json.loads(response_body.decode())
#logger.info(f'response.status = {response.status} and result["error"] = {result["error"]}')
# If you wish to allow the operation at some point, you can return: if response.status == 200:
# return self._api.NOT_SPAM # Raise an AuthError if the API returns OK 200
raise AuthError(403, "User not allowed to join this room")
else:
# Allow joining if no issue detected
return self._api.NOT_SPAM
def parse_config(config: dict) -> dict: def parse_config(config: dict) -> dict:
return config return config
def create_module(api: ModuleApi, config: dict) -> RedlightClientModule: def create_module(api: ModuleApi, config: dict) -> RedlightClientModule:
return RedlightClientModule(config, api) return RedlightClientModule(config, api)