import psycopg2 import os import json from flask import Flask, request, jsonify, render_template import uuid import string import random import hashlib config_dir_path = "./config/" server_config_path = config_dir_path + "server.json" onetime_config_path = config_dir_path + "onetime.json" if not os.path.isfile(server_config_path): if not os.path.isdir(config_dir_path): os.mkdir(config_dir_path) server_config = { "db": { "host": "localhost", "port": "5432", "db_name": "dislocker", "username": "user", "password": "password" }, "bot": { "token": "TYPE HERE BOTS TOKEN KEY", "activity": { "name": "Dislocker", "details": "ロック中...", "type": "playing", "state": "ロック中..." }, "log_channel_id" : "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", "config_channel_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", "config_public_channel_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)" } } with open(server_config_path, "w") as w: json.dump(server_config, w, indent=4) elif os.path.isfile(server_config_path): with open(server_config_path, "r") as r: server_config = json.load(r) class Auth(): def __init__(self, host, db, port, user, password): self.db = psycopg2.connect(f"host={host} dbname={db} port={port} user={user} password={password}") def token_generate(self, length): letters = string.ascii_letters + string.digits token = ''.join(random.choice(letters) for _ in range(length)) return token def master_password_generate(self, length): characters = string.ascii_letters + string.digits + string.punctuation master_password = ''.join(random.choice(characters) for _ in range(length)) return master_password def hash_genarate(self, source): hashed = hashlib.sha256(source.encode()) return hashed.hexdigest() def check(self, **kwargs): try: cursor = self.db.cursor() pc_number = int(kwargs["pc_number"]) pc_uuid = str(kwargs["pc_uuid"]) pc_token = str(kwargs["pc_token"]) if "device_list" in kwargs: if kwargs["device_list"] == []: device_list = None else: device_list = kwargs["device_list"] else: device_list = None keyboard_number = 0 mouse_number = 0 if "password_hash" in kwargs: password_hash = str(kwargs["password_hash"]) cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s AND password_hash = %s AND pc_uuid = %s AND pc_token = %s", (pc_number, password_hash, pc_uuid, pc_token)) pc_info = cursor.fetchall() if pc_info: if device_list == None: pass else: for device in device_list: cursor.execute("SELECT * FROM keyboard_list WHERE device_instance_path = %s", (device["device_instance_path"],)) keyboard_record = cursor.fetchall() if keyboard_record: keyboard_number = int(keyboard_record[0][0]) break else: pass for device in device_list: cursor.execute("SELECT * FROM mouse_list WHERE device_instance_path = %s", (device["device_instance_path"],)) mouse_record = cursor.fetchall() if mouse_record: mouse_number = int(mouse_record[0][0]) break else: pass return {"result": 0, "about": "ok", "output_dict": {"keyboard_number": keyboard_number, "mouse_number": mouse_number}} else: return {"result": 1, "about": "incorrect_password"} else: cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s AND pc_uuid = %s AND pc_token = %s", (pc_number, pc_uuid, pc_token)) pc_info = cursor.fetchall() if pc_info: return {"result": 0, "about": "ok"} else: return {"result": 1, "about": "unregistered_pc"} except Exception as error: print("PCの登録状況を調査中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} finally: cursor.close() def device_use_register(self, **kwargs): try: pc_number = int(kwargs["pc_number"]) if kwargs["keyboard_number"] == "own": keyboard_number = 0 else: keyboard_number = int(kwargs["keyboard_number"]) if kwargs["mouse_number"] == "own": mouse_number = 0 else: mouse_number = int(kwargs["mouse_number"]) cursor = self.db.cursor() cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_list_record = cursor.fetchall() pc_using_member_id = pc_list_record[0][1] if pc_using_member_id == None: return {"result": 1, "about": "not_used"} else: cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number)) pc_usage_history_record = cursor.fetchall() pc_usage_history_record_id = pc_usage_history_record[0][0] cursor.execute("UPDATE pc_usage_history SET keyboard_number = %s, mouse_number = %s WHERE id = %s", (keyboard_number, mouse_number, pc_usage_history_record_id)) if keyboard_number == 0: pass else: cursor.execute("UPDATE keyboard_list SET using_member_id = %s WHERE keyboard_number = %s", (pc_using_member_id, keyboard_number)) if mouse_number == 0: pass else: cursor.execute("UPDATE mouse_list SET using_member_id = %s WHERE mouse_number = %s", (pc_using_member_id, mouse_number)) self.db.commit() return {"result": 0, "about": "ok"} except Exception as error: print("デバイスの使用登録中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} def device_register(self, **kwargs): try: cursor = self.db.cursor() mode = kwargs["mode"] number = kwargs["number"] device_instance_path = kwargs["device_instance_path"] device_name = kwargs["device_name"] if mode == "keyboard": keyboard_number = int(kwargs["number"]) cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number = %s", (keyboard_number,)) keyboard_record = cursor.fetchall() if keyboard_record: cursor.execute("UPDATE keyboard_list SET device_instance_path = %s, device_name = %s WHERE keyboard_number = %s", (device_instance_path, device_name, keyboard_number)) self.db.commit() return {"result": 0, "about": "ok"} else: cursor.execute("INSERT INTO keyboard_list (keyboard_number, device_instance_path, device_name) VALUES (%s, %s, %s)", (keyboard_number, device_instance_path, device_name)) return {"result": 0, "about": "ok"} elif mode == "mouse": mouse_number = int(kwargs["number"]) cursor.execute("SELECT * FROM mouse_list WHERE mouse_number = %s", (mouse_number,)) mouse_record = cursor.fetchall() if mouse_record: cursor.execute("UPDATE mouse_list SET device_instance_path = %s, device_name = %s WHERE mouse_number = %s", (device_instance_path, device_name, mouse_number)) self.db.commit() return {"result": 0, "about": "ok"} else: cursor.execute("INSERT INTO mouse_list (mouse_number, device_instance_path, device_name) VALUES (%s, %s, %s)", (mouse_number, device_instance_path, device_name)) return {"result": 0, "about": "ok"} except Exception as error: print("停止処理中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} def delete(self, pc_number): try: cursor = self.db.cursor() cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) self.db.commit() return {"result": 0, "about": "ok"} except Exception as error: print("パスワードの削除中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} finally: cursor.close() def user_register_check(self, **kwargs): try: discord_user_id = str(kwargs["discord_user_id"]) cursor = self.db.cursor() cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) user_record = cursor.fetchall() #ユーザーデータが見つかった場合(登録済みの場合) if user_record: member_id = user_record[0][0] name = user_record[0][1] discord_user_name = user_record[0][2] return {"result": 0, "about": "exist", "user_info": {"member_id": member_id, "name": name, "discord_user_name": discord_user_name}} #ユーザーデータがなかったら(未登録の場合) else: return {"result": 1, "about": "user_data_not_found"} except Exception as error: print("ユーザーの登録状況を調査中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} finally: cursor.close() def stop(self, **kwargs): # bot側のfstopを基に try: pc_number = kwargs["pc_number"] cursor = self.db.cursor() cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_list_record = cursor.fetchall() pc_using_member_id = pc_list_record[0][1] pc_password_hash = pc_list_record[0][2] if pc_using_member_id == None: return {"result": 1, "about": "not_used"} else: cursor.execute("UPDATE pc_list SET using_member_id = NULL WHERE pc_number = %s", (pc_number,)) if pc_password_hash == None: pass else: cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number)) pc_usage_history_record = cursor.fetchall() pc_usage_history_record_id = pc_usage_history_record[0][0] keyboard_number = pc_usage_history_record[0][3] mouse_number = pc_usage_history_record[0][4] if keyboard_number == None: pass else: # keyboard_listの使用中ユーザーを消す cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,)) if mouse_number == None: pass else: # mouse_listの使用中ユーザーを消す cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE mouse_number = %s", (mouse_number,)) cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (pc_usage_history_record_id,)) self.db.commit() return {"result": 0, "about": "ok"} except Exception as error: print("停止処理中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} finally: cursor.close() def register(self, **kwargs): try: cursor = self.db.cursor() pc_number = int(kwargs["pc_number"]) pc_uuid = str(kwargs["pc_uuid"]) cursor.execute("SELECT pc_uuid FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_record = cursor.fetchall() pc_record_uuid = pc_record[0][0] cursor.execute("SELECT pc_number FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_record = cursor.fetchall() pc_record_number = pc_record[0][0] if pc_record_number == None: pc_token = self.token_generate(36) master_password = self.master_password_generate(16) master_password_hash = self.hash_genarate(master_password) cursor.execute("INSERT INTO pc_list (pc_number, pc_uuid, pc_token, master_password) VALUES (%s, %s, %s, %s)", (pc_number, pc_uuid, pc_token, master_password)) self.db.commit() return {"result": 0, "about": "ok", "output_dict": {"pc_token": pc_token, "master_password": master_password, "master_password_hash": master_password_hash}} else: if pc_record_uuid == None: pc_token = self.token_generate(36) master_password = self.master_password_generate(16) master_password_hash = self.hash_genarate(master_password) cursor.execute("UPDATE pc_list SET pc_uuid = %s, pc_token = %s, master_password = %s WHERE pc_number = %s", (pc_uuid, pc_token, master_password, pc_number)) self.db.commit() return {"result": 0, "about": "ok", "output_dict": {"pc_token": pc_token, "master_password": master_password, "master_password_hash": master_password_hash}} else: return {"result": 1, "about": "exist"} except Exception as error: print("PCの登録処理中にエラーが発生しました。\nエラー内容") print(str(error.__class__.__name__)) print(str(error.args)) print(str(error)) return {"result": 1, "about": "error"} finally: cursor.close() app = Flask(__name__, static_folder="./resource/") auth = Auth(server_config["db"]["host"], server_config["db"]["db_name"], server_config["db"]["port"], server_config["db"]["username"], server_config["db"]["password"]) @app.route('/register', methods=['POST']) def register(): pc_number = int(request.json.get('pc_number')) pc_uuid = str(request.json.get('pc_uuid')) onetime_password = str(request.json.get('onetime')) if os.path.isfile(onetime_config_path): with open(onetime_config_path, "r") as r: onetime_config = json.load(r) if onetime_password == onetime_config["onetime"]["pc_register"]["password"]: register_result = auth.register(pc_number=pc_number, pc_uuid=pc_uuid) if register_result["result"] == 0: pc_token = register_result["output_dict"]["pc_token"] master_password = register_result["output_dict"]["master_password"] master_password_hash = register_result["output_dict"]["master_password_hash"] onetime_config["onetime"]["pc_register"]["current_count"] += 1 if onetime_config["onetime"]["pc_register"]["current_count"] == onetime_config["onetime"]["pc_register"]["max_count"]: onetime_config["onetime"]["pc_register"]["password"] = None with open(onetime_config_path, "w") as w: json.dump(onetime_config, w, indent=4) return jsonify({'message': 'ok', 'pc_token': pc_token, 'master_password': master_password, 'master_password_hash': master_password_hash}), 200 else: with open(onetime_config_path, "w") as w: json.dump(onetime_config, w, indent=4) return jsonify({'message': 'ok', 'pc_token': pc_token, 'master_password': master_password, 'master_password_hash': master_password_hash}), 200 elif register_result["result"] == 1: if register_result["about"] == "exist": return jsonify({'message': 'exist'}), 401 else: return jsonify({'message': 'damedesu'}), 401 else: return jsonify({'message': 'damedesu'}), 401 else: return jsonify({'message': 'damedesu'}), 401 @app.route('/verify', methods=['POST']) def verify(): pc_number = int(request.json.get('pc_number')) password_hash = request.json.get('password') pc_uuid = request.json.get('pc_uuid') pc_token = request.json.get('pc_token') devices = request.json.get('devices') print(str(pc_number) + "の認証処理を開始...") pc_auth = auth.check(pc_number=pc_number, password_hash=password_hash, pc_uuid=pc_uuid, pc_token=pc_token, device_list=devices) if pc_auth["result"] == 0: auth.delete(pc_number) auth.device_use_register(pc_number=pc_number, keyboard_number=pc_auth["output_dict"]["keyboard_number"], mouse_number=pc_auth["output_dict"]["mouse_number"]) print(str(pc_number) + "の認証処理は成功しました.") return jsonify({'message': 'ok'}), 200 elif pc_auth["result"] == 1: if pc_auth["about"] == "incorrect_password": print(str(pc_number) + "の認証処理はパスワードが正しくないため失敗しました.") return jsonify({'message': 'incorrect_password'}), 401 else: print(str(pc_number) + "の認証処理は失敗しました.") return jsonify({'message': 'damedesu'}), 500 @app.route('/stop', methods=['POST']) def stop(): pc_number = int(request.json.get('pc_number')) pc_uuid = str(request.json.get('pc_uuid')) pc_token = str(request.json.get('pc_token')) print(str(pc_number) + "の使用停止処理を開始...") pc_auth = auth.check(pc_number=pc_number, pc_uuid=pc_uuid, pc_token=pc_token) if pc_auth["result"] == 0: pc_stop = auth.stop(pc_number=pc_number) if pc_stop["result"] == 0: print(str(pc_number) + "の使用停止処理は成功しました.") return jsonify({'message': 'ok'}), 200 else: print(str(pc_number) + "の使用停止処理は失敗しました.") return jsonify({'message': 'error'}), 500 else: return jsonify({'message': 'damedesu'}), 401 @app.route('/device_register', methods=['POST']) def device_register(): onetime_password = str(request.json.get('onetime')) mode = str(request.json.get('mode')) number = int(request.json.get('number')) device_instance_path = str(request.json.get('device_instance_path')) device_name = str(request.json.get('device_name')) if os.path.isfile(onetime_config_path): with open(onetime_config_path, "r") as r: onetime_config = json.load(r) if onetime_password == onetime_config["onetime"]["device_register"]: if mode == "keyboard": print("キーボードの登録処理を開始...") device_register = auth.device_register(mode="keyboard", number=number, device_instance_path=device_instance_path, device_name=device_name) if device_register["result"] == 0: print(f"キーボード {number} 番の登録処理は成功しました.") onetime_config["onetime"]["device_register"]["current_count"] += 1 if onetime_config["onetime"]["device_register"]["current_count"] == onetime_config["onetime"]["device_register"]["max_count"]: onetime_config["onetime"]["device_register"] = None with open(onetime_config_path, "w") as w: json.dump(onetime_config, w, indent=4) return jsonify({'message': 'ok'}), 200 else: with open(onetime_config_path, "w") as w: json.dump(onetime_config, w, indent=4) return jsonify({'message': 'ok'}), 200 else: print(f"キーボード {number} 番の登録処理は失敗しました.") return jsonify({'message': 'error'}), 500 elif mode == "mouse": print("マウスの登録処理を開始...") device_register = auth.device_register(mode="mouse", number=number, device_instance_path=device_instance_path, device_name=device_name) if device_register["result"] == 0: print(f"マウス {number} 番の登録処理は成功しました.") onetime_config["onetime"]["device_register"]["current_count"] += 1 if onetime_config["onetime"]["device_register"]["current_count"] == onetime_config["onetime"]["device_register"]["max_count"]: onetime_config["onetime"]["device_register"] = None with open(onetime_config_path, "w") as w: json.dump(onetime_config, w, indent=4) return jsonify({'message': 'ok'}), 200 else: with open(onetime_config_path, "w") as w: json.dump(onetime_config, w, indent=4) return jsonify({'message': 'ok'}), 200 else: print(f"マウス {number} 番の登録処理は失敗しました.") return jsonify({'message': 'error'}), 500 else: return jsonify({'message': 'damedesu'}), 401 if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=False)