Compare commits
No commits in common. "0d5b83e0545c2eb918dd99a9e4890ee95e4bf48d" and "d044943309e94fd0542b6af671333aaedc4dbbfe" have entirely different histories.
0d5b83e054
...
d044943309
15
auth.py
15
auth.py
@ -9,8 +9,6 @@ from fastapi import Depends, HTTPException, status
|
|||||||
from fastapi.security import HTTPBearer
|
from fastapi.security import HTTPBearer
|
||||||
from jwt.exceptions import InvalidTokenError
|
from jwt.exceptions import InvalidTokenError
|
||||||
|
|
||||||
import queries
|
|
||||||
|
|
||||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutes
|
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutes
|
||||||
ALGORITHM = "HS256"
|
ALGORITHM = "HS256"
|
||||||
JWT_SECRET_KEY = 'abcdefghijklmnopqrstuvwxyz'
|
JWT_SECRET_KEY = 'abcdefghijklmnopqrstuvwxyz'
|
||||||
@ -49,14 +47,19 @@ def get_current_user(token: str = Depends(security)) -> dict:
|
|||||||
except InvalidTokenError:
|
except InvalidTokenError:
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
|
|
||||||
|
with open('database/users.json', 'r') as f:
|
||||||
|
text = f.read()
|
||||||
|
if text:
|
||||||
|
data = json.loads(text)
|
||||||
|
else:
|
||||||
|
raise credentials_exception
|
||||||
|
|
||||||
user = queries.GET_USER_BY_ID({'user_id': user_id})
|
user = [i for i in data if i['id']==user_id]
|
||||||
|
if not user:
|
||||||
if user is None:
|
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
|
|
||||||
cur_user = {'id': user_id}
|
cur_user = {'id': user_id}
|
||||||
cur_user['username'] = user['username']
|
cur_user['username'] = user[0]['username']
|
||||||
cur_user['encryption_key'] = payload['key']
|
cur_user['encryption_key'] = payload['key']
|
||||||
|
|
||||||
return cur_user
|
return cur_user
|
||||||
|
124
main.py
124
main.py
@ -1,17 +1,20 @@
|
|||||||
import json
|
import json
|
||||||
from sqlite3 import IntegrityError
|
|
||||||
from typing import Literal
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
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 (deserialize_into_bytes, fernet_decrypt, fernet_encrypt,
|
from crypto import (
|
||||||
generate_random_encryption_key, generate_user_passkey,
|
deserialize_into_bytes,
|
||||||
serialize_bytes)
|
fernet_decrypt,
|
||||||
from models import Key, Secret, User, UserLogin
|
fernet_encrypt,
|
||||||
|
generate_random_encryption_key,
|
||||||
|
generate_user_passkey,
|
||||||
|
serialize_bytes,
|
||||||
|
)
|
||||||
|
from models import Secret, User, UserLogin
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
@ -39,51 +42,72 @@ async def root():
|
|||||||
async def register(user: User):
|
async def register(user: User):
|
||||||
"""Registers a user"""
|
"""Registers a user"""
|
||||||
|
|
||||||
plain_text_password = user.password
|
users = []
|
||||||
user.password = Hasher.get_password_hash(plain_text_password)
|
with open('database/users.json', 'r') as f:
|
||||||
|
text = f.read()
|
||||||
|
if text:
|
||||||
|
users = json.loads(text)
|
||||||
|
|
||||||
try:
|
if user.id is not None:
|
||||||
user = queries.CREATE_USER(user.model_dump())
|
raise HTTPException(
|
||||||
user_id = user['id']
|
status_code=400,
|
||||||
except IntegrityError as e:
|
detail="User id shall be auto generated, cannot be provided in request"
|
||||||
|
)
|
||||||
|
if not users:
|
||||||
|
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(plain_text_password)
|
|
||||||
|
|
||||||
key = Key(
|
salt, master_key = generate_user_passkey(user.password)
|
||||||
user_id=user_id,
|
encrypted_encryption_key = fernet_encrypt(encryption_key, master_key)
|
||||||
encryption_key=fernet_encrypt(encryption_key, master_key).decode('utf-8'),
|
|
||||||
encryption_key_salt=serialize_bytes(salt)
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
user.password = Hasher.get_password_hash(user.password)
|
||||||
queries.CREATE_KEY(key.model_dump())
|
user.encryption_key = encrypted_encryption_key.decode('utf-8')
|
||||||
except Exception as e:
|
user.salt = serialize_bytes(salt)
|
||||||
print('failed to create key', e)
|
|
||||||
|
|
||||||
return {'user_id': user_id}
|
users.append(jsonable_encoder(user))
|
||||||
|
# print(f"{salt=}\n{user.salt=}\n{encrypted_encryption_key=}\n{user.encryption_key=}\n{master_key=}")
|
||||||
|
with open('database/users.json', 'w') as f:
|
||||||
|
json.dump(users, f)
|
||||||
|
|
||||||
|
return {'user_id': user.id}
|
||||||
|
|
||||||
|
|
||||||
@app.post('/login')
|
@app.post('/login')
|
||||||
async def login(user: UserLogin):
|
async def login(user: UserLogin):
|
||||||
"""logs in the user"""
|
"""logs in the user"""
|
||||||
|
|
||||||
login_exception = HTTPException(
|
users = []
|
||||||
|
with open('database/users.json', 'r') as f:
|
||||||
|
text = f.read()
|
||||||
|
if text:
|
||||||
|
users.extend(json.loads(text))
|
||||||
|
|
||||||
|
cur_user = [i for i in users if i['username']==user.username]
|
||||||
|
if not cur_user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="username or password is incorrect"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur_user = cur_user[0]
|
||||||
|
|
||||||
|
password_match = Hasher.verify_password(user.password, cur_user['password'])
|
||||||
|
if not password_match:
|
||||||
|
raise HTTPException(
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
detail="username or password is incorrect"
|
detail="username or password is incorrect"
|
||||||
)
|
)
|
||||||
|
|
||||||
cur_user = queries.GET_USER_WITH_KEY(user.model_dump())
|
|
||||||
if cur_user is None:
|
|
||||||
raise login_exception
|
|
||||||
|
|
||||||
password_match = Hasher.verify_password(user.password, cur_user['password'])
|
|
||||||
if not password_match:
|
|
||||||
raise login_exception
|
|
||||||
|
|
||||||
encrypted_encryption_key = cur_user['encryption_key'].encode()
|
encrypted_encryption_key = cur_user['encryption_key'].encode()
|
||||||
salt = deserialize_into_bytes(cur_user['encryption_key_salt'])
|
salt = deserialize_into_bytes(cur_user['salt'])
|
||||||
_, master_key = generate_user_passkey(user.password, salt)
|
_, master_key = generate_user_passkey(user.password, salt)
|
||||||
encryption_key = fernet_decrypt(encrypted_encryption_key, master_key)
|
encryption_key = fernet_decrypt(encrypted_encryption_key, master_key)
|
||||||
access_token = create_access_token(subject=cur_user['id'], encryption_key=encryption_key)
|
access_token = create_access_token(subject=cur_user['id'], encryption_key=encryption_key)
|
||||||
@ -102,15 +126,27 @@ async def create_secret(secret: Secret, current_user: dict = Depends(get_current
|
|||||||
Stores an encrypted secret for the user.
|
Stores an encrypted secret for the user.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
data = []
|
||||||
|
with open('database/secrets.json', 'r') as f:
|
||||||
|
text = f.read()
|
||||||
|
if text:
|
||||||
|
data.extend(json.loads(text))
|
||||||
|
|
||||||
|
if data:
|
||||||
|
secret_id = max(i['id'] for i in data) + 1
|
||||||
|
else:
|
||||||
|
secret_id = 0
|
||||||
|
secret.id = secret_id
|
||||||
secret.user_id = current_user['id']
|
secret.user_id = current_user['id']
|
||||||
encryption_key = current_user['encryption_key'].encode()
|
encryption_key = current_user['encryption_key'].encode()
|
||||||
|
|
||||||
encrypted_data = fernet_encrypt(secret.data.encode(), encryption_key)
|
encrypted_data = fernet_encrypt(secret.data.encode(), encryption_key)
|
||||||
|
|
||||||
secret.data = encrypted_data.decode('utf-8')
|
secret.data = encrypted_data.decode('utf-8')
|
||||||
|
data.append(jsonable_encoder(secret))
|
||||||
|
|
||||||
queries.CREATE_SECRET(secret.model_dump())
|
with open('database/secrets.json', 'w') as f:
|
||||||
|
json.dump(data, f)
|
||||||
return secret
|
return secret
|
||||||
|
|
||||||
|
|
||||||
@ -152,9 +188,16 @@ async def update_secret(secret: Secret, current_user: dict = Depends(get_current
|
|||||||
async def list_secret(current_user: dict = Depends(get_current_user)):
|
async def list_secret(current_user: dict = Depends(get_current_user)):
|
||||||
"""Returns the encrypted secrets of the user."""
|
"""Returns the encrypted secrets of the user."""
|
||||||
|
|
||||||
user_secrets = queries.GET_SECRETS({'user_id': current_user['id']})
|
data = []
|
||||||
|
with open('database/secrets.json', 'r') as f:
|
||||||
|
text = f.read()
|
||||||
|
if text:
|
||||||
|
data.extend(json.loads(text))
|
||||||
|
|
||||||
|
user_id = current_user['id']
|
||||||
encryption_key = current_user['encryption_key'].encode()
|
encryption_key = current_user['encryption_key'].encode()
|
||||||
|
|
||||||
|
user_secrets = [i for i in data if i['user_id']==user_id and i['active']]
|
||||||
for secret in user_secrets:
|
for secret in user_secrets:
|
||||||
cur_data = secret['data']
|
cur_data = secret['data']
|
||||||
decrypted_data = fernet_decrypt(cur_data, encryption_key)
|
decrypted_data = fernet_decrypt(cur_data, encryption_key)
|
||||||
@ -166,7 +209,8 @@ async def list_secret(current_user: dict = Depends(get_current_user)):
|
|||||||
@app.get('/validate-token')
|
@app.get('/validate-token')
|
||||||
async def validate_token(current_user: dict = Depends(get_current_user)):
|
async def validate_token(current_user: dict = Depends(get_current_user)):
|
||||||
user_id = current_user['id']
|
user_id = current_user['id']
|
||||||
if user_id is None:
|
print("user_id: ", user_id)
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|
if user_id is not None:
|
||||||
|
|
||||||
return {'message': 'authenticated'}
|
return {'message': 'authenticated'}
|
||||||
|
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|
@ -5,9 +5,7 @@ import sqlite3
|
|||||||
|
|
||||||
|
|
||||||
def connect_db():
|
def connect_db():
|
||||||
conn = sqlite3.connect('database/database.sqlite')
|
return sqlite3.connect('database/database.sqlite')
|
||||||
conn.execute("PRAGMA foreign_keys = 1")
|
|
||||||
return conn
|
|
||||||
|
|
||||||
|
|
||||||
def create_user_table():
|
def create_user_table():
|
||||||
|
11
models.py
11
models.py
@ -5,20 +5,13 @@ from pydantic import BaseModel
|
|||||||
|
|
||||||
class User(BaseModel):
|
class User(BaseModel):
|
||||||
id: int = None
|
id: int = None
|
||||||
name: str = None
|
|
||||||
email: str = None
|
|
||||||
username: str
|
username: str
|
||||||
password: str
|
password: str
|
||||||
|
encryption_key: str = None
|
||||||
|
salt: str = None
|
||||||
created_on: str = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
created_on: str = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||||
active: bool = True
|
active: bool = True
|
||||||
|
|
||||||
|
|
||||||
class Key(BaseModel):
|
|
||||||
user_id: int
|
|
||||||
encryption_key: str
|
|
||||||
encryption_key_salt: str
|
|
||||||
|
|
||||||
|
|
||||||
class UserLogin(BaseModel):
|
class UserLogin(BaseModel):
|
||||||
username: str
|
username: str
|
||||||
password: str
|
password: str
|
||||||
|
140
queries.py
140
queries.py
@ -1,140 +0,0 @@
|
|||||||
import sqlite3
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Literal
|
|
||||||
|
|
||||||
|
|
||||||
def connect_db():
|
|
||||||
conn = sqlite3.connect('database/database.sqlite')
|
|
||||||
conn.execute("PRAGMA foreign_keys = 1")
|
|
||||||
return conn
|
|
||||||
|
|
||||||
|
|
||||||
class DbQuery:
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
query: str,
|
|
||||||
type: Literal['read', 'write'],
|
|
||||||
returns: bool,
|
|
||||||
rows: Literal['single', 'multi']
|
|
||||||
):
|
|
||||||
self.query = query
|
|
||||||
self.type = type
|
|
||||||
self.returns = returns
|
|
||||||
self.rows = rows
|
|
||||||
|
|
||||||
def __str__(self) -> str:
|
|
||||||
return self.query
|
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
|
||||||
return f"<query: '{self.query}, {self.type}, returns {self.returns}, {self.rows} row(s)"
|
|
||||||
|
|
||||||
def _read(self, params: dict) -> list[dict]|dict:
|
|
||||||
with connect_db() as conn:
|
|
||||||
cur = conn.execute(self.query, params)
|
|
||||||
data = cur.fetchall()
|
|
||||||
if not data:
|
|
||||||
return None
|
|
||||||
keys = [i[0] for i in cur.description]
|
|
||||||
|
|
||||||
data_dict = [dict(zip(keys, i)) for i in data]
|
|
||||||
|
|
||||||
if self.rows == 'single':
|
|
||||||
if len(data_dict) > 1:
|
|
||||||
raise ValueError('Query returned more than one rows.')
|
|
||||||
|
|
||||||
data_dict = data_dict[0]
|
|
||||||
|
|
||||||
return data_dict
|
|
||||||
|
|
||||||
def _write(self, params: dict) -> dict|bool:
|
|
||||||
if not isinstance(params, dict):
|
|
||||||
raise TypeError("Only dict type is supported for params")
|
|
||||||
|
|
||||||
with connect_db() as conn:
|
|
||||||
cur = conn.execute(self.query, params)
|
|
||||||
if self.returns:
|
|
||||||
data = cur.fetchone()
|
|
||||||
keys = keys = [i[0] for i in cur.description]
|
|
||||||
data_dict = dict(zip(keys, data))
|
|
||||||
conn.commit()
|
|
||||||
|
|
||||||
if self.returns:
|
|
||||||
return data_dict
|
|
||||||
return True
|
|
||||||
|
|
||||||
def __call__(self, params):
|
|
||||||
if self.type == 'read':
|
|
||||||
func = self._read
|
|
||||||
else:
|
|
||||||
func = self._write
|
|
||||||
|
|
||||||
return func(params)
|
|
||||||
|
|
||||||
|
|
||||||
CREATE_USER = DbQuery(
|
|
||||||
query="""
|
|
||||||
INSERT INTO
|
|
||||||
users (name, email, username, password)
|
|
||||||
VALUES (:name, :email, :username, :password)
|
|
||||||
RETURNING id
|
|
||||||
""",
|
|
||||||
type='write',
|
|
||||||
returns=True,
|
|
||||||
rows='single'
|
|
||||||
)
|
|
||||||
|
|
||||||
CREATE_KEY = DbQuery(
|
|
||||||
query="""
|
|
||||||
INSERT INTO
|
|
||||||
keys (user_id, encryption_key, encryption_key_salt)
|
|
||||||
VALUES (:user_id, :encryption_key, :encryption_key_salt)
|
|
||||||
""",
|
|
||||||
type='write',
|
|
||||||
returns=False,
|
|
||||||
rows=None
|
|
||||||
)
|
|
||||||
|
|
||||||
GET_USER_WITH_KEY = DbQuery(
|
|
||||||
"""
|
|
||||||
SELECT *
|
|
||||||
FROM users u
|
|
||||||
JOIN keys k on u.id = k.user_id
|
|
||||||
WHERE u.username = :username
|
|
||||||
""",
|
|
||||||
type='read',
|
|
||||||
returns=True,
|
|
||||||
rows='single'
|
|
||||||
)
|
|
||||||
|
|
||||||
GET_USER_BY_ID = DbQuery(
|
|
||||||
"""
|
|
||||||
SELECT *
|
|
||||||
FROM users
|
|
||||||
where id = :user_id
|
|
||||||
""",
|
|
||||||
type='read',
|
|
||||||
returns=True,
|
|
||||||
rows='single'
|
|
||||||
)
|
|
||||||
|
|
||||||
CREATE_SECRET = DbQuery(
|
|
||||||
"""
|
|
||||||
INSERT INTO
|
|
||||||
secrets(user_id, data)
|
|
||||||
VALUES(:user_id, :data)
|
|
||||||
""",
|
|
||||||
type='write',
|
|
||||||
returns=False,
|
|
||||||
rows=None
|
|
||||||
)
|
|
||||||
|
|
||||||
GET_SECRETS = DbQuery(
|
|
||||||
"""
|
|
||||||
SELECT *
|
|
||||||
FROM secrets
|
|
||||||
WHERE user_id = :user_id
|
|
||||||
""",
|
|
||||||
type='read',
|
|
||||||
returns=True,
|
|
||||||
rows=None
|
|
||||||
)
|
|
Loading…
Reference in New Issue
Block a user