Dislocker/dislocker_auth.py

182 lines
No EOL
7.4 KiB
Python

import psycopg2
import os
import json
from flask import Flask, request, jsonify, render_template
config_dir_path = "./config/"
server_config_path = config_dir_path + "server.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 check(self, pc_number, password):
try:
cursor = self.db.cursor()
cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s AND password_hash = %s", (pc_number, password))
pc_info = cursor.fetchall()
if pc_info:
return {"result": 0, "about": "ok"}
else:
return {"result": 1, "about": "unregistered_pc"}
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 keyboard_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()
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('/verify', methods=['POST'])
def verify():
pc_number = int(request.json.get('pc_number'))
password = request.json.get('password')
print(str(pc_number) + "の認証処理を開始...")
pc_auth = auth.check(pc_number, password)
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'))
print(str(pc_number) + "の使用停止処理を開始...")
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
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=False)