Skip to content

Commit

Permalink
[revert] 認証機能を全て削除
Browse files Browse the repository at this point in the history
  • Loading branch information
okaits committed Dec 16, 2022
1 parent 6f12f48 commit 12693b7
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 105 deletions.
41 changes: 4 additions & 37 deletions browser-addon/main.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,20 @@
token = ""
function beforeunload(token) {
function beforeunload() {
// navigator.sendBeacon("http://localhost:5000/video", JSON.stringify({"status": "closed"}));
body = JSON.stringify({"status": "closed"});
fetch("http://localhost:5000/video", {
method: 'POST',
body: JSON.stringify({"status": "closed"}),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer " + this.token
"Content-type": "application/json"
},
keepalive: true
});
};

function ajaxerror(xhr, testStatus, errorThrown) {
if (xhr.status == 401) {
console.log("Reloading token...")
token = gettoken("password")
};
};

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
};

async function gettoken(password) {
tokenrecv = $.ajax(
{
type: "POST",
url: "http://localhost:5000/login",
data: JSON.stringify({"user": "user1", "password": password}),
contentType: "application/json; charset=UTF-8"
}
);
while (true) {
await sleep(50);
if (tokenrecv.responseJSON == undefined) {
continue;
} else {
token = tokenrecv.responseJSON["token"];
window.addEventListener('beforeunload', {token: token, handleEvent: beforeunload});
return token
};
};
};

token = gettoken("password");

async function loop() {
var beforepaused = true;
while (true) {
Expand All @@ -66,9 +34,8 @@ async function loop() {
type: "POST",
url: "http://localhost:5000/video",
data: JSON.stringify({'status': 'opened', 'videoid': videoid, 'playing': !ispaused, 'hour': hour, 'min': min, 'sec': sec}),
headers: {"Authorization": "Bearer " + token},
contentType: "application/json; charset=UTF-8",
error: ajaxerror});
contentType: "application/json; charset=UTF-8"
});
beforepaused = ispaused;
};
};
Expand Down
30 changes: 1 addition & 29 deletions client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from __future__ import annotations

import datetime
import hashlib
import json
import time
import urllib.request
Expand All @@ -16,36 +15,9 @@
RPC = pypresence.Presence(CLIENT_ID)
RPC.connect()

class Auth():
""" Class about Auth information """
class User():
""" Class about user information """
def __init__(self, username: str, password: str):
self.username = username
self.password = hashlib.sha256()
self.password.update(password.encode())
self.password = self.password.hexdigest()
class Token():
""" JMT class """
def __init__(self):
self.token = ""
def get(self, user: Auth.User):
""" Get JMT from server """
tokenrequest = urllib.request.Request("http://localhost:5000/login", headers={"Content-type": "application/json"}, data=json.dumps({"user": user.username, "password": user.password}).encode())
self.token = json.load(urllib.request.urlopen(tokenrequest))["token"]

token = Auth.Token()
token.get(Auth.User("user1", "password"))

videodata_request = urllib.request.Request("http://localhost:5000/video", headers={"Authorization": f"Bearer {token.token}"})
beforevideodata = {'status': 'closed'}
while True:
try:
videodata = json.loads(urllib.request.urlopen(videodata_request).read().decode())
except urllib.error.HTTPError:
token.get(Auth.User("user1", "password"))
videodata_request = urllib.request.Request("http://localhost:5000/video", headers={"Authorization": f"Bearer {token.token}"})
continue
videodata = json.loads(urllib.request.urlopen("http://localhost:5000/video").read().decode())
if videodata != beforevideodata:
print(videodata)
if videodata["status"] != "opened":
Expand Down
43 changes: 4 additions & 39 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,15 @@
import xmltodict
from flask import Flask, Response, jsonify, request
from flask_cors import CORS
from flask_jwt_extended import (JWTManager, create_access_token,
get_jwt_identity, jwt_required)

app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret-password"
jwt = JWTManager(app)
CORS(app)
id_dict = {"user1": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"}
class Data():
""" Data class """
status = {"user1": {"status": "closed"}}
status = {"status": "closed"}
cache = {}


def jwt_unauthorized_loader_handler(_):
return jsonify({"msg": "unauthorized"}), "401 Unauthorized"
jwt.unauthorized_loader(jwt_unauthorized_loader_handler)

@app.route("/login", methods=["POST"])
def login():
if request.content_type.split(";")[0] == "application/json":
data = request.json
elif request.content_type.split(";")[0] == "text/plain":
data = json.loads(request.data)
else:
return jsonify({"msg": "bad content-type"}), "415 Unsupported media type"
try:
if data["user"] in id_dict:
if data["password"] == id_dict[data["user"]]:
user = data["user"]
else:
pwhash = hashlib.sha256()
pwhash.update(data["password"].encode())
if pwhash.hexdigest() == id_dict[data["user"]]:
user = data["user"]
else:
return jsonify({"msg": "Unauthorized"}), "401 Unauthorized"
except KeyError:
return jsonify({"msg": "Unprocessable json"}), "400 Bad request"
token = create_access_token(identity=user)
return jsonify({"msg": "ok", "token": token}), "200 OK"

@app.route("/video", methods=["POST", "GET"])
@jwt_required()
def video():
""" API /video """
if request.method == "POST":
Expand All @@ -67,15 +32,15 @@ def video():
print(data)
try:
if data["status"] == "closed":
Data.status[get_jwt_identity()] = {"status": data["status"]}
Data.status = {"status": data["status"]}
return jsonify({"msg": "success"}), "201 Created"
Data.status[get_jwt_identity()] = {"status": data["status"],"id": data["videoid"], "playing": data["playing"], "hour": data["hour"], "min": data["min"], "sec": str(math.floor(int(data["sec"])))}
Data.status = {"status": data["status"],"id": data["videoid"], "playing": data["playing"], "hour": data["hour"], "min": data["min"], "sec": str(math.floor(int(data["sec"])))}
except KeyError:
print(data)
return jsonify({"msg": "missing value"}), "400 Bad Request"
return jsonify({"msg": "success"}), "201 Created"
elif request.method == "GET":
return jsonify(Data.status[get_jwt_identity()]), "200 OK"
return jsonify(Data.status), "200 OK"

@app.route("/videoinfo", methods=["GET"])
def videoinfo():
Expand Down

0 comments on commit 12693b7

Please sign in to comment.