Compare commits
16 Commits
Author | SHA1 | Date | |
---|---|---|---|
8a7da6e146 | |||
b0a0e23090 | |||
846e9a7aa5 | |||
f6d119c852 | |||
5b697d7810 | |||
a089ffa884 | |||
6a1429614b | |||
1af66916a9 | |||
24300ca596 | |||
0d5b83e054 | |||
91ac771400 | |||
4ef416f3ee | |||
d0f1d74ca3 | |||
926bd613a8 | |||
6e9a8b5b97 | |||
d044943309 |
0
backend/__init__.py
Normal file
0
backend/__init__.py
Normal file
@ -1,6 +1,4 @@
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Union
|
||||
|
||||
import bcrypt
|
||||
@ -9,6 +7,8 @@ from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer
|
||||
from jwt.exceptions import InvalidTokenError
|
||||
|
||||
import backend.queries as queries
|
||||
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutes
|
||||
ALGORITHM = "HS256"
|
||||
JWT_SECRET_KEY = 'abcdefghijklmnopqrstuvwxyz'
|
||||
@ -47,19 +47,14 @@ def get_current_user(token: str = Depends(security)) -> dict:
|
||||
except InvalidTokenError:
|
||||
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 = [i for i in data if i['id']==user_id]
|
||||
if not user:
|
||||
user = queries.GET_USER_BY_ID({'user_id': user_id})
|
||||
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
|
||||
cur_user = {'id': user_id}
|
||||
cur_user['username'] = user[0]['username']
|
||||
cur_user['username'] = user['username']
|
||||
cur_user['encryption_key'] = payload['key']
|
||||
|
||||
return cur_user
|
169
backend/main.py
Normal file
169
backend/main.py
Normal file
@ -0,0 +1,169 @@
|
||||
import json
|
||||
from sqlite3 import IntegrityError
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, status
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
import backend.queries as queries
|
||||
from backend.auth import Hasher, create_access_token, get_current_user
|
||||
from backend.crypto import (deserialize_into_bytes, fernet_decrypt,
|
||||
fernet_encrypt, generate_random_encryption_key,
|
||||
generate_user_passkey, serialize_bytes)
|
||||
from backend.models import Key, Secret, User, UserLogin
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
origins = [
|
||||
'http://localhost',
|
||||
'http://localhost:5173',
|
||||
"*"
|
||||
]
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=['*'],
|
||||
allow_headers=['*']
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"'message'": "Hello World"}
|
||||
|
||||
|
||||
@app.post('/register')
|
||||
async def register(user: User):
|
||||
"""Registers a user"""
|
||||
|
||||
plain_text_password = user.password
|
||||
user.password = Hasher.get_password_hash(plain_text_password)
|
||||
|
||||
try:
|
||||
user = queries.CREATE_USER(user.model_dump())
|
||||
user_id = user['id']
|
||||
except IntegrityError as e:
|
||||
raise HTTPException(status_code=400, detail="Username already in use")
|
||||
|
||||
encryption_key = generate_random_encryption_key()
|
||||
salt, master_key = generate_user_passkey(plain_text_password)
|
||||
|
||||
key = Key(
|
||||
user_id=user_id,
|
||||
encryption_key=fernet_encrypt(encryption_key, master_key).decode('utf-8'),
|
||||
encryption_key_salt=serialize_bytes(salt)
|
||||
)
|
||||
|
||||
try:
|
||||
queries.CREATE_KEY(key.model_dump())
|
||||
except Exception as e:
|
||||
print('failed to create key', e)
|
||||
|
||||
return {'user_id': user_id}
|
||||
|
||||
|
||||
@app.post('/login')
|
||||
async def login(user: UserLogin):
|
||||
"""logs in the user"""
|
||||
|
||||
login_exception = HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
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()
|
||||
salt = deserialize_into_bytes(cur_user['encryption_key_salt'])
|
||||
_, master_key = generate_user_passkey(user.password, salt)
|
||||
encryption_key = fernet_decrypt(encrypted_encryption_key, master_key)
|
||||
access_token = create_access_token(subject=cur_user['id'], encryption_key=encryption_key)
|
||||
|
||||
response = {
|
||||
'message': 'authenticated',
|
||||
'accessToken': access_token
|
||||
}
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@app.post("/secret")
|
||||
async def create_secret(secret: Secret, current_user: dict = Depends(get_current_user)):
|
||||
"""
|
||||
Stores an encrypted secret for the user.
|
||||
"""
|
||||
|
||||
secret.user_id = current_user['id']
|
||||
encryption_key = current_user['encryption_key'].encode()
|
||||
|
||||
encrypted_data = fernet_encrypt(secret.data.encode(), encryption_key)
|
||||
|
||||
secret.data = encrypted_data.decode('utf-8')
|
||||
|
||||
queries.CREATE_SECRET(secret.model_dump())
|
||||
|
||||
return secret
|
||||
|
||||
|
||||
@app.put("/secret")
|
||||
async def update_secret(secret: Secret, current_user: dict = Depends(get_current_user)):
|
||||
"""
|
||||
Updates an encrypted secret for the user.
|
||||
"""
|
||||
|
||||
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']
|
||||
|
||||
encryption_key = current_user['encryption_key'].encode()
|
||||
encrypted_data = fernet_encrypt(secret.data.encode(), encryption_key)
|
||||
secret.data = encrypted_data.decode('utf-8')
|
||||
|
||||
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.delete('/secret')
|
||||
async def delete_secret(secret: Secret, current_user: dict = Depends(get_current_user)):
|
||||
"""Deletes the secret with the given id"""
|
||||
secret.user_id = current_user['id']
|
||||
# print(secret.model_dump())
|
||||
user_id, secret_id = queries.DELETE_SECRET(secret.model_dump())
|
||||
|
||||
|
||||
@app.get('/secret')
|
||||
async def list_secret(current_user: dict = Depends(get_current_user)):
|
||||
"""Returns the encrypted secrets of the 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']
|
||||
decrypted_data = fernet_decrypt(cur_data, encryption_key)
|
||||
secret['data'] = decrypted_data
|
||||
|
||||
return user_secrets
|
||||
|
||||
|
||||
@app.get('/validate-token')
|
||||
async def validate_token(current_user: dict = Depends(get_current_user)):
|
||||
user_id = current_user['id']
|
||||
if user_id is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
return {'message': 'authenticated'}
|
85
backend/migration.py
Normal file
85
backend/migration.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""Create the necessary tables in an SQLite database"""
|
||||
|
||||
|
||||
import sqlite3
|
||||
|
||||
|
||||
def connect_db():
|
||||
conn = sqlite3.connect('database/database.sqlite')
|
||||
conn.execute("PRAGMA foreign_keys = 1")
|
||||
return conn
|
||||
|
||||
|
||||
def create_user_table():
|
||||
query = """
|
||||
create table if not exists users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT,
|
||||
email TEXT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
created_on TEXT default CURRENT_TIMESTAMP,
|
||||
active BOOLEAN default TRUE
|
||||
)
|
||||
"""
|
||||
|
||||
try:
|
||||
connection = connect_db()
|
||||
connection.execute(query)
|
||||
connection.commit()
|
||||
except Exception as e:
|
||||
print("Error creating users table", e)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def create_keys_table():
|
||||
query = """
|
||||
create table if not exists keys (
|
||||
user_id INTEGER,
|
||||
encryption_key TEXT,
|
||||
encryption_key_salt TEXT,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
ON DELETE CASCADE
|
||||
)
|
||||
"""
|
||||
try:
|
||||
connection = connect_db()
|
||||
connection.execute(query)
|
||||
connection.commit()
|
||||
except Exception as e:
|
||||
print("Error creating keys table", e)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def create_secrets_table():
|
||||
query = """
|
||||
create table if not exists secrets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
data TEXT NOT NULL,
|
||||
added_on TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
modified_on TEXT,
|
||||
active BOOLEAN DEFAULT TRUE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
ON DELETE CASCADE
|
||||
)
|
||||
"""
|
||||
try:
|
||||
connection = connect_db()
|
||||
connection.execute(query)
|
||||
connection.commit()
|
||||
except Exception as e:
|
||||
print("Error creating secrets tabe", e)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
create_user_table()
|
||||
create_keys_table()
|
||||
create_secrets_table()
|
@ -5,13 +5,20 @@ from pydantic import BaseModel
|
||||
|
||||
class User(BaseModel):
|
||||
id: int = None
|
||||
name: str = None
|
||||
email: str = None
|
||||
username: str
|
||||
password: str
|
||||
encryption_key: str = None
|
||||
salt: str = None
|
||||
created_on: str = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
active: bool = True
|
||||
|
||||
|
||||
class Key(BaseModel):
|
||||
user_id: int
|
||||
encryption_key: str
|
||||
encryption_key_salt: str
|
||||
|
||||
|
||||
class UserLogin(BaseModel):
|
||||
username: str
|
||||
password: str
|
168
backend/queries.py
Normal file
168
backend/queries.py
Normal file
@ -0,0 +1,168 @@
|
||||
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
|
||||
)
|
||||
|
||||
UPDATE_SECRET = DbQuery(
|
||||
"""
|
||||
UPDATE secrets
|
||||
SET
|
||||
data = :data,
|
||||
modified_on = CURRENT_TIMESTAMP
|
||||
WHERE
|
||||
id = :id
|
||||
RETURNING *
|
||||
""",
|
||||
type='write',
|
||||
returns=True,
|
||||
rows='single'
|
||||
)
|
||||
|
||||
DELETE_SECRET = DbQuery(
|
||||
"""
|
||||
DELETE from secrets
|
||||
WHERE
|
||||
user_id = :user_id
|
||||
and id = :id
|
||||
RETURNING user_id, id
|
||||
""",
|
||||
type='write',
|
||||
returns=True,
|
||||
rows='single'
|
||||
)
|
||||
|
||||
GET_SECRETS = DbQuery(
|
||||
"""
|
||||
SELECT *
|
||||
FROM secrets
|
||||
WHERE user_id = :user_id
|
||||
""",
|
||||
type='read',
|
||||
returns=True,
|
||||
rows=None
|
||||
)
|
@ -1,6 +1,7 @@
|
||||
<script setup>
|
||||
import CreateSecret from "./components/CreateSecret.vue";
|
||||
import HomePage from "./components/HomePage.vue";
|
||||
import ImportSecrets from "./components/ImportSecrets.vue";
|
||||
import ListSecrets from "./components/ListSecrets.vue";
|
||||
</script>
|
||||
|
||||
@ -18,14 +19,33 @@ import ListSecrets from "./components/ListSecrets.vue";
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="creationDialog" title="Add a new TOTP secret" width="80vw">
|
||||
<el-dialog
|
||||
v-model="creationDialog"
|
||||
title="Add a new TOTP secret"
|
||||
destroy-on-close
|
||||
width="80vw"
|
||||
>
|
||||
<CreateSecret @close="secretSaved" />
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="editDialog" title="Edit TOTP secret" width="80vw">
|
||||
<el-dialog
|
||||
v-model="editDialog"
|
||||
title="Edit TOTP secret"
|
||||
destroy-on-close
|
||||
width="80vw"
|
||||
>
|
||||
<CreateSecret :editSecret="editingSecret" @close="secretSaved" />
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="importDialog"
|
||||
title="Import TOTP secrets"
|
||||
destroy-on-close
|
||||
width="80vw"
|
||||
>
|
||||
<ImportSecrets @close="secretsImported" />
|
||||
</el-dialog>
|
||||
|
||||
<div class="container">
|
||||
<div class="timer" v-if="loggedin" :style="{ width: timerWidth + '%' }"></div>
|
||||
<HomePage
|
||||
@ -43,11 +63,13 @@ import ListSecrets from "./components/ListSecrets.vue";
|
||||
<ListSecrets :key="listUpdated" v-if="showSecrets && loggedin" @edit="editSecret" />
|
||||
</div>
|
||||
<button class="create-floating" @click="creationDialog = true">+</button>
|
||||
<button class="create-floating mb50" @click="importDialog = true">i</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
components: { ImportSecrets },
|
||||
data() {
|
||||
return {
|
||||
loggedin: false,
|
||||
@ -57,6 +79,7 @@ export default {
|
||||
apiBaseUrl: "http://localhost:8000",
|
||||
editDialog: false,
|
||||
editingSecret: {},
|
||||
importDialog: false,
|
||||
timerWidth: 0,
|
||||
};
|
||||
},
|
||||
@ -72,6 +95,11 @@ export default {
|
||||
this.listUpdated += 1;
|
||||
},
|
||||
|
||||
secretsImported() {
|
||||
this.importDialog = false;
|
||||
this.listUpdated += 1;
|
||||
},
|
||||
|
||||
async validateToken() {
|
||||
const url = `${this.apiBaseUrl}/validate-token`;
|
||||
const token = sessionStorage.getItem("token");
|
||||
@ -204,4 +232,8 @@ export default {
|
||||
border: none;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.mb50 {
|
||||
margin-bottom: 50px;
|
||||
}
|
||||
</style>
|
||||
|
@ -14,6 +14,22 @@
|
||||
<el-form-item label="Notes">
|
||||
<el-input v-model="form.notes" />
|
||||
</el-form-item>
|
||||
<el-form-item label="Algorithm">
|
||||
<el-select v-model="form.algorithm" placeholder="Select">
|
||||
<el-option
|
||||
v-for="item in algorithms"
|
||||
:key="item"
|
||||
:label="item"
|
||||
:value="item"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="Digits">
|
||||
<el-input v-model="form.digits" />
|
||||
</el-form-item>
|
||||
<el-form-item label="Seconds">
|
||||
<el-input v-model="form.seconds" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-button @click="createSecret" type="primary" v-if="showAddMore"
|
||||
>Save & Add More</el-button
|
||||
@ -26,6 +42,15 @@
|
||||
type="primary"
|
||||
>Save & Close</el-button
|
||||
>
|
||||
<el-button
|
||||
type="danger"
|
||||
@click="
|
||||
deleteSecret();
|
||||
closeDialog();
|
||||
"
|
||||
v-if="this.method === 'PUT'"
|
||||
>Delete</el-button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@ -45,9 +70,13 @@ export default {
|
||||
username: "",
|
||||
secret: "",
|
||||
notes: "",
|
||||
algorithm: "SHA1",
|
||||
digits: 6,
|
||||
seconds: 30,
|
||||
},
|
||||
method: "POST",
|
||||
showAddMore: true,
|
||||
algorithms: ["SHA1", "SHA256", "SHA512"],
|
||||
};
|
||||
},
|
||||
|
||||
@ -67,7 +96,7 @@ export default {
|
||||
},
|
||||
body: JSON.stringify(bodyData),
|
||||
};
|
||||
console.log(requestOptions);
|
||||
// console.log(requestOptions);
|
||||
await fetch(url, requestOptions)
|
||||
.then((response) => response.json())
|
||||
.then((data) => console.log(data));
|
||||
@ -80,6 +109,25 @@ export default {
|
||||
(this.form.secret = "");
|
||||
this.$emit("close", true);
|
||||
},
|
||||
|
||||
async deleteSecret() {
|
||||
const url = `${this.apiBaseUrl}/secret`;
|
||||
const token = sessionStorage.getItem("token");
|
||||
const bodyData = { data: btoa(JSON.stringify(this.form)) };
|
||||
bodyData["id"] = this.id;
|
||||
const requestOptions = {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(bodyData),
|
||||
};
|
||||
// console.log(requestOptions);
|
||||
await fetch(url, requestOptions)
|
||||
.then((response) => response.json())
|
||||
.then((data) => console.log(data));
|
||||
},
|
||||
},
|
||||
|
||||
created() {
|
||||
|
@ -20,7 +20,7 @@ export default {
|
||||
message: "Hello world!",
|
||||
apiBaseUrl: "http://localhost:8000",
|
||||
form: {
|
||||
username: "gourav",
|
||||
username: "gouravkr",
|
||||
password: "hello123",
|
||||
},
|
||||
};
|
||||
|
142
frontend/src/components/ImportSecrets.vue
Normal file
142
frontend/src/components/ImportSecrets.vue
Normal file
@ -0,0 +1,142 @@
|
||||
<template>
|
||||
<div class="import-container">
|
||||
<!-- <h3>Select a File to Read</h3> -->
|
||||
<input type="file" id="fileInput" @change="readFile" /> <br />
|
||||
|
||||
<button @click="parseTotpUri">Parse tokens</button>
|
||||
<button @click="saveImportedSecrets">Save tokens</button>
|
||||
<div class="token-list">
|
||||
<span v-for="token in parsedTokens" :key="token.issuer">
|
||||
<p v-for="(value, name) in token" :key="name">{{ name }}: {{ value }}</p>
|
||||
<br />
|
||||
</span>
|
||||
<!-- <span>{{ parsedTokens }}</span> -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
apiBaseUrl: "http://localhost:8000",
|
||||
message: "hello",
|
||||
file: null,
|
||||
fileContent: null,
|
||||
allTokens: [],
|
||||
parsedTokens: [],
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
parseFile() {
|
||||
var authArr = this.fileContent.split("\r\n");
|
||||
authArr.forEach((ele) => {
|
||||
if (ele.length > 80) {
|
||||
this.allTokens.push(decodeURIComponent(ele));
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
readFile(e) {
|
||||
const file = e.target.files[0]; // Get the selected file
|
||||
if (file) {
|
||||
var reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
this.fileContent = reader.result;
|
||||
};
|
||||
reader.readAsText(file);
|
||||
} else {
|
||||
document.getElementById("fileContent").textContent = "No file selected";
|
||||
}
|
||||
},
|
||||
|
||||
parseTotpUri() {
|
||||
this.parseFile();
|
||||
this.allTokens.forEach((token) => {
|
||||
const url = new URL(token);
|
||||
const scheme = url.protocol.slice(0, -1);
|
||||
var label = decodeURIComponent(url.pathname.slice(1)); // Remove the leading '/'
|
||||
const type = label.slice(1, -1).split("/")[0];
|
||||
label = label.slice(6);
|
||||
let username, issuerFromLabel;
|
||||
const labelParts = label.split(":");
|
||||
if (labelParts.length === 2) {
|
||||
issuerFromLabel = labelParts[0];
|
||||
username = labelParts[1];
|
||||
} else {
|
||||
username = label;
|
||||
}
|
||||
|
||||
const params = {};
|
||||
url.searchParams.forEach((value, key) => {
|
||||
params[key] = value;
|
||||
});
|
||||
|
||||
console.log(params);
|
||||
|
||||
const secret = params.secret;
|
||||
const issuer = params.issuer || issuerFromLabel;
|
||||
const algorithm = params.algorithm || "SHA1";
|
||||
const digits = params.digits || "6";
|
||||
const period = params.period || "30";
|
||||
const counter = params.counter;
|
||||
|
||||
const parts = {
|
||||
scheme,
|
||||
type,
|
||||
label,
|
||||
username,
|
||||
issuer,
|
||||
secret,
|
||||
algorithm,
|
||||
digits,
|
||||
period,
|
||||
counter,
|
||||
};
|
||||
|
||||
this.parsedTokens.push(parts);
|
||||
});
|
||||
},
|
||||
|
||||
async createSecret(formData) {
|
||||
const url = `${this.apiBaseUrl}/secret`;
|
||||
const token = sessionStorage.getItem("token");
|
||||
const bodyData = { data: btoa(JSON.stringify(formData)) };
|
||||
const requestOptions = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(bodyData),
|
||||
};
|
||||
console.log("this request sent\n", requestOptions);
|
||||
await fetch(url, requestOptions)
|
||||
.then((response) => response.json())
|
||||
.then((data) => console.log(data));
|
||||
},
|
||||
|
||||
async saveImportedSecrets() {
|
||||
for (var i = 0; i < this.parsedTokens.length; i++) {
|
||||
await this.createSecret(this.parsedTokens[i]);
|
||||
}
|
||||
this.$emit("close", true);
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.import-container {
|
||||
/* max-height: 60vh; */
|
||||
overflow: hidden;
|
||||
margin-top: 1vh;
|
||||
}
|
||||
|
||||
.token-list {
|
||||
height: 60vh;
|
||||
margin-top: 10px;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
</style>
|
@ -17,25 +17,21 @@
|
||||
</el-button-group>
|
||||
<div>
|
||||
<el-form-item label="Show OTPs">
|
||||
<el-switch v-model="showSecrets" active-value="yes" inactive-value="no" />
|
||||
<el-switch
|
||||
v-model="showSecrets"
|
||||
active-value="yes"
|
||||
inactive-value="no"
|
||||
style="--el-switch-on-color: #67c23a"
|
||||
/>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="sort-options">
|
||||
<span>
|
||||
<el-form-item label="Sort">
|
||||
<el-select
|
||||
v-model="currentSort"
|
||||
placeholder="Select"
|
||||
style="width: 80px"
|
||||
@change="sortItems"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in sortOptions"
|
||||
:key="item.key"
|
||||
:label="item.name"
|
||||
:value="item.key"
|
||||
/>
|
||||
</el-select>
|
||||
<el-radio-group v-model="currentSort" @change="sortItems" fill="#67c23a">
|
||||
<el-radio-button label="A > Z" value="asc" />
|
||||
<el-radio-button label="Z > A" value="desc" />
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</span>
|
||||
</div>
|
||||
|
@ -107,6 +107,7 @@ export default {
|
||||
|
||||
.issuer {
|
||||
font-weight: 700;
|
||||
/* max-width: 140px; */
|
||||
}
|
||||
|
||||
.user {
|
||||
@ -122,6 +123,8 @@ export default {
|
||||
.card-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
max-width: 140px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.card-button {
|
||||
position: relative;
|
||||
|
216
main.py
216
main.py
@ -1,216 +0,0 @@
|
||||
import json
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, status
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
|
||||
from auth import Hasher, create_access_token, get_current_user
|
||||
from crypto import (
|
||||
deserialize_into_bytes,
|
||||
fernet_decrypt,
|
||||
fernet_encrypt,
|
||||
generate_random_encryption_key,
|
||||
generate_user_passkey,
|
||||
serialize_bytes,
|
||||
)
|
||||
from models import Secret, User, UserLogin
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
origins = [
|
||||
'http://localhost',
|
||||
'http://localhost:5173',
|
||||
"*"
|
||||
]
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=['*'],
|
||||
allow_headers=['*']
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"'message'": "Hello World"}
|
||||
|
||||
|
||||
@app.post('/register')
|
||||
async def register(user: User):
|
||||
"""Registers a user"""
|
||||
|
||||
users = []
|
||||
with open('database/users.json', 'r') as f:
|
||||
text = f.read()
|
||||
if text:
|
||||
users = json.loads(text)
|
||||
|
||||
if user.id is not None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
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")
|
||||
|
||||
encryption_key = generate_random_encryption_key()
|
||||
|
||||
salt, master_key = generate_user_passkey(user.password)
|
||||
encrypted_encryption_key = fernet_encrypt(encryption_key, master_key)
|
||||
|
||||
user.password = Hasher.get_password_hash(user.password)
|
||||
user.encryption_key = encrypted_encryption_key.decode('utf-8')
|
||||
user.salt = serialize_bytes(salt)
|
||||
|
||||
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')
|
||||
async def login(user: UserLogin):
|
||||
"""logs in the user"""
|
||||
|
||||
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,
|
||||
detail="username or password is incorrect"
|
||||
)
|
||||
|
||||
encrypted_encryption_key = cur_user['encryption_key'].encode()
|
||||
salt = deserialize_into_bytes(cur_user['salt'])
|
||||
_, master_key = generate_user_passkey(user.password, salt)
|
||||
encryption_key = fernet_decrypt(encrypted_encryption_key, master_key)
|
||||
access_token = create_access_token(subject=cur_user['id'], encryption_key=encryption_key)
|
||||
|
||||
response = {
|
||||
'message': 'authenticated',
|
||||
'accessToken': access_token
|
||||
}
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@app.post("/secret")
|
||||
async def create_secret(secret: Secret, current_user: dict = Depends(get_current_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']
|
||||
encryption_key = current_user['encryption_key'].encode()
|
||||
|
||||
encrypted_data = fernet_encrypt(secret.data.encode(), encryption_key)
|
||||
|
||||
secret.data = encrypted_data.decode('utf-8')
|
||||
data.append(jsonable_encoder(secret))
|
||||
|
||||
with open('database/secrets.json', 'w') as f:
|
||||
json.dump(data, f)
|
||||
return secret
|
||||
|
||||
|
||||
@app.put("/secret")
|
||||
async def update_secret(secret: Secret, current_user: dict = Depends(get_current_user)):
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
@app.get('/secret')
|
||||
async def list_secret(current_user: dict = Depends(get_current_user)):
|
||||
"""Returns the encrypted secrets of the user."""
|
||||
|
||||
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()
|
||||
|
||||
user_secrets = [i for i in data if i['user_id']==user_id and i['active']]
|
||||
for secret in user_secrets:
|
||||
cur_data = secret['data']
|
||||
decrypted_data = fernet_decrypt(cur_data, encryption_key)
|
||||
secret['data'] = decrypted_data
|
||||
|
||||
return user_secrets
|
||||
|
||||
|
||||
@app.get('/validate-token')
|
||||
async def validate_token(current_user: dict = Depends(get_current_user)):
|
||||
user_id = current_user['id']
|
||||
print("user_id: ", user_id)
|
||||
if user_id is not None:
|
||||
return {'message': 'authenticated'}
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|
Loading…
Reference in New Issue
Block a user