-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
99 lines (83 loc) · 2.9 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import datetime
import hashlib
import sqlite3
import jwt
from flask import Flask, jsonify, request, session
app = Flask(__name__)
app.secret_key = 'secretkey!'
@app.route("/api/stage/", methods=['GET', 'POST'])
def api():
if request.method == "GET":
if 'tokens' in session:
# génération de hello world + confirmation de la validité du token
api1 = {
"title": "stage_copernic",
"valeur1": "HELLO WORLD",
"tokens": "valid"
}
return jsonify(api1)
else:
return 'please authenticate you'
else:
return 'error'
@app.route("/api/stage/token", methods=['GET', 'POST'])
def tokens():
token_get = request.headers.get('tokens')
try:
jwt.decode(token_get, app.secret_key, algorithms=["HS256"])
token_used = hashlib.sha256(token_get.encode()).hexdigest()
connn = sqlite3.connect("userdata.db")
cur = connn.cursor()
username = token_used
password = token_used
# vérification du token
cur.execute("SELECT * FROM userdata WHERE username = ? AND password = ?", (username, password))
if cur.fetchall():
session['tokens'] = token_get
return api()
else:
return authenticate()
except jwt.exceptions.ExpiredSignatureError:
expired_cookie = {
"title": "stage_copernic",
"tokens": "invalid",
"valeur1": "invalid"
}
return jsonify(expired_cookie)
except Exception as error:
return f'{error}'
@app.route("/api/authenticate", methods=['GET', 'POST'])
def authenticate():
if request.method == "GET":
if 'tokens' in session:
return api()
else:
# creation du token et de la session
tokenss = jwt.encode(
{"passw": 'nottoken', 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)},
app.secret_key, algorithm="HS256")
hashage = hashlib.sha256(tokenss.encode()).hexdigest()
session['tokens'] = tokenss
# enregistrement du token dans la base de donné hashé
connec = sqlite3.connect("userdata.db")
cur = connec.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS userdata (
id INTEGRER PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
)
""")
username = hashage
password = hashage
cur.execute("INSERT INTO userdata (username, password) VALUES (?, ?)", (username, password))
connec.commit()
token_json = {
"title": "stage_copernic",
"tokens": f"{tokenss}"
}
return jsonify(token_json)
else:
return 'error 401'
if __name__ == "__main__":
app.run(port=8000)