-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backend Code
98 lines (67 loc) · 2.4 KB
/
Backend Code
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
---------------------- File 'app.py'
from flask import Flask, request, jsonify
from models import db, User
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.hazmat.primitives import serialization
import base64
app = Flask(__name__)
app.config.from_object('config.Config')
db.init_app(app)
@app.route('/register', methods=['POST'])
def register():
data = request.json
user_id = data.get('user_id')
public_key = data.get('public_key')
if not user_id or not public_key:
return jsonify({"error": "Invalid data"}), 400
# Save the public key to the database
new_user = User(user_id=user_id, public_key=public_key)
db.session.add(new_user)
db.session.commit()
return jsonify({"status": "registered"}), 201
@app.route('/authenticate', methods=['POST'])
def authenticate():
data = request.json
user_id = data.get('user_id')
signature = base64.b64decode(data.get('signature'))
challenge = base64.b64decode(data.get('challenge'))
user = User.query.filter_by(user_id=user_id).first()
if not user:
return jsonify({"error": "User not found"}), 404
public_key_bytes = base64.b64decode(user.public_key)
public_key = Ed25519PublicKey.from_public_bytes(public_key_bytes)
try:
public_key.verify(signature, challenge)
return jsonify({"status": "authenticated"}), 200
except Exception:
return jsonify({"status": "failed"}), 401
if __name__ == '__main__':
app.run(debug=True)
----------------------------- File 'models.py'
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.String(100), unique=True, nullable=False)
public_key = db.Column(db.Text, nullable=False)
---------------------------- File 'database.py'
from flask import Flask
from models import db
import config
def init_db():
app = Flask(__name__)
app.config.from_object(config.Config)
db.init_app(app)
with app.app_context():
db.create_all()
if __name__ == '__main__':
init_db()
---------------------------- File 'config.py'
import os
class Config:
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'sqlite:///webauthn.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
--------------------------- File 'requirements.txt'
Flask==2.0.3
Flask-SQLAlchemy==2.5.1
cryptography==36.0.1