Update API now uses sqlite db, removed json

This commit is contained in:
Gourav Kumar 2024-07-01 10:56:09 +05:30
parent 0d5b83e054
commit 24300ca596
2 changed files with 21 additions and 17 deletions

23
main.py
View File

@ -120,32 +120,19 @@ async def update_secret(secret: Secret, current_user: dict = Depends(get_current
Updates 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 secret.id is None:
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="Id must be passed for updating secret")
secret.user_id = current_user['id']
found_secrets = [(i, j) for i, j in enumerate(data) if j['user_id'] == secret.user_id and j['id']==secret.id]
if not found_secrets:
raise HTTPException(status.HTTP_400_BAD_REQUEST, deatil="Secret with this Id not found for this user")
secret_pos = found_secrets[0][0]
encryption_key = current_user['encryption_key'].encode()
encrypted_data = fernet_encrypt(secret.data.encode(), encryption_key)
secret.data = encrypted_data.decode('utf-8')
data[secret_pos] = jsonable_encoder(secret)
with open('database/secrets.json', 'w') as f:
json.dump(data, f)
return secret
token = queries.UPDATE_SECRET(secret.model_dump())
if not token:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Token not found for this user")
return token
@app.get('/secret')
@ -154,6 +141,8 @@ async def list_secret(current_user: dict = Depends(get_current_user)):
user_secrets = queries.GET_SECRETS({'user_id': current_user['id']})
encryption_key = current_user['encryption_key'].encode()
if not user_secrets:
return {'message': 'No tokens stored yet'}
for secret in user_secrets:
cur_data = secret['data']

View File

@ -128,6 +128,21 @@ CREATE_SECRET = DbQuery(
rows=None
)
UPDATE_SECRET = DbQuery(
"""
UPDATE secrets
SET
data = :data,
modified_on = CURRENT_TIMESTAMP
WHERE
id = :id
RETURNING *
""",
type='write',
returns=True,
rows='single'
)
GET_SECRETS = DbQuery(
"""
SELECT *