import psycopg2 import os import json from flask import Flask, request, jsonify, render_template import uuid import string import random 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 password = ''.join(random.choice(letters) for _ in range(length)) return password 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 "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() 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 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] if pc_record_uuid == None: pc_token = self.token_generate(36) cursor.execute("UPDATE pc_list SET pc_uuid = %s, pc_token = %s WHERE pc_number = %s", (pc_uuid, pc_token, pc_number)) self.db.commit() os.remove(onetime_config_path) return {"result": 0, "about": "ok", "output_dict": {"pc_token": pc_token}} else: return {"result": 1, "about": "exist"} 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() 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"]: register_result = auth.register(pc_number=pc_number, pc_uuid=pc_uuid) pc_token = register_result["output_dict"]["pc_token"] return jsonify({'message': 'ok', 'pc_token': pc_token}), 200 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') print(str(pc_number) + "の認証処理を開始...") pc_auth = auth.check(pc_number=pc_number, password_hash=password_hash, pc_uuid=pc_uuid, pc_token=pc_token) if pc_auth["result"] == 0: auth.delete(pc_number) print(str(pc_number) + "の認証処理は成功しました.") return jsonify({'message': 'ok'}), 200 else: print(str(pc_number) + "の認証処理は失敗しました.") return jsonify({'message': 'damedesu'}), 401 @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 if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=False)