user cration queries

This commit is contained in:
Gourav Kumar 2024-06-21 10:12:19 +05:30
parent 926bd613a8
commit d0f1d74ca3
2 changed files with 50 additions and 37 deletions

62
main.py
View File

@ -1,20 +1,17 @@
import json import json
from sqlite3 import IntegrityError
from fastapi import Depends, FastAPI, HTTPException, status from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.encoders import jsonable_encoder from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
import queries
from auth import Hasher, create_access_token, get_current_user from auth import Hasher, create_access_token, get_current_user
from crypto import ( from crypto import (deserialize_into_bytes, fernet_decrypt, fernet_encrypt,
deserialize_into_bytes, generate_random_encryption_key, generate_user_passkey,
fernet_decrypt, serialize_bytes)
fernet_encrypt, from models import Key, Secret, User, UserLogin
generate_random_encryption_key,
generate_user_passkey,
serialize_bytes,
)
from models import Secret, User, UserLogin
app = FastAPI() app = FastAPI()
@ -42,42 +39,33 @@ async def root():
async def register(user: User): async def register(user: User):
"""Registers a user""" """Registers a user"""
users = [] plain_text_password = user.password
with open('database/users.json', 'r') as f: user.password = Hasher.get_password_hash(plain_text_password)
text = f.read()
if text:
users = json.loads(text)
if user.id is not None: conn = queries.connect_db()
raise HTTPException( try:
status_code=400, cur = conn.execute(queries.CREATE_USER_QUERY, jsonable_encoder(user))
detail="User id shall be auto generated, cannot be provided in request" user_id = cur.fetchall()[0][0]
) conn.commit()
if not users: except IntegrityError as e:
user.id = 0
else:
max_user_id = max([i['id'] for i in users])
user.id = max_user_id + 1
user_exists = [i for i in users if i['username'] == user.username]
if user_exists:
raise HTTPException(status_code=400, detail="Username already in use") raise HTTPException(status_code=400, detail="Username already in use")
encryption_key = generate_random_encryption_key() encryption_key = generate_random_encryption_key()
salt, master_key = generate_user_passkey(user.password) salt, master_key = generate_user_passkey(plain_text_password)
encrypted_encryption_key = fernet_encrypt(encryption_key, master_key)
user.password = Hasher.get_password_hash(user.password) key = Key(
user.encryption_key = encrypted_encryption_key.decode('utf-8') user_id=user_id,
user.salt = serialize_bytes(salt) encryption_key=fernet_encrypt(encryption_key, master_key).decode('utf-8'),
encryption_key_salt = serialize_bytes(salt)
)
users.append(jsonable_encoder(user)) try:
# print(f"{salt=}\n{user.salt=}\n{encrypted_encryption_key=}\n{user.encryption_key=}\n{master_key=}") conn.execute(queries.CREATE_KEY_QUERY, jsonable_encoder(key))
with open('database/users.json', 'w') as f: except Exception as e:
json.dump(users, f) print('failed to create key', e)
return {'user_id': user.id} return {'user_id': user_id}
@app.post('/login') @app.post('/login')

25
queries.py Normal file
View File

@ -0,0 +1,25 @@
import sqlite3
def connect_db():
conn = sqlite3.connect('database/database.sqlite')
conn.execute("PRAGMA foreign_keys = 1")
return conn
CREATE_USER_QUERY = """
INSERT INTO
users (
name, email, username, password
)
VALUES (
:name, :email, :username, :password
)
returning id
"""
CREATE_KEY_QUERY = """
INSERT INTO
keys (user_id, encryption_key, encryption_key_salt)
VALUES (:user_id, :encryption_key, :encryption_key_salt)
"""