Compare commits

..

No commits in common. "httpcookie" and "master" have entirely different histories.

4 changed files with 38 additions and 79 deletions

39
auth.py
View File

@ -5,8 +5,8 @@ from typing import Any, Union
import bcrypt
import jwt
from fastapi import Cookie, Depends, HTTPException, status
from fastapi.security import HTTPBearer, OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
from jwt.exceptions import InvalidTokenError
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutes
@ -38,7 +38,6 @@ def get_current_user(token: str = Depends(security)) -> dict:
headers={'WWW-Authenticate': 'Bearer'}
)
credential = token.credentials
try:
payload = jwt.decode(credential, JWT_SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
@ -66,40 +65,6 @@ def get_current_user(token: str = Depends(security)) -> dict:
return cur_user
def get_current_user2(token: str = Cookie(default=None)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={'WWW-Authenticate': 'Bearer'}
)
print('TOKEN: ', token)
try:
payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
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:
raise credentials_exception
cur_user = {'id': user_id}
cur_user['username'] = user[0]['username']
cur_user['encryption_key'] = payload['key']
return cur_user
class Hasher:
"""Class for hashing and verifying passwords"""

View File

@ -29,14 +29,10 @@ export default {
methods: {
async login() {
const url = `${this.apiBaseUrl}/login`;
var formData = new FormData();
for (var key in this.form) {
formData.append(key, this.form[key]);
}
const requestOptions = {
method: "POST",
// headers: { "Content-Type": "application/json" },
body: formData,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(this.form),
};
const response = await fetch(url, requestOptions)
@ -51,10 +47,9 @@ export default {
});
console.log("response: ", response);
if ("message" in response) {
if (response.message === "Authenticated") {
// const token = response.accessToken;
// sessionStorage.setItem("token", token);
sessionStorage.setItem("authenticated", true);
if (response.message === "authenticated") {
const token = response.accessToken;
sessionStorage.setItem("token", token);
this.$emit("loggedin", true);
}
}

View File

@ -100,14 +100,13 @@ export default {
methods: {
async listSecrets() {
const url = `${this.apiBaseUrl}/secret`;
// const token = sessionStorage.getItem("token");
const token = sessionStorage.getItem("token");
const requestOptions = {
method: "GET",
credentials: "include",
// headers: {
// // "Content-Type": "application/json",
// // Authorization: `Bearer ${token}`,
// },
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
};
console.log(requestOptions);
const response = await fetch(url, requestOptions)

50
main.py
View File

@ -1,15 +1,19 @@
import json
from fastapi import Depends, FastAPI, HTTPException, Response, status
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.security import OAuth2PasswordBearer
from auth import (Hasher, create_access_token, get_current_user,
get_current_user2)
from crypto import (deserialize_into_bytes, fernet_decrypt, fernet_encrypt,
generate_random_encryption_key, generate_user_passkey,
serialize_bytes)
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()
@ -18,7 +22,7 @@ app = FastAPI()
origins = [
'http://localhost',
'http://localhost:5173',
# "*"
"*"
]
app.add_middleware(
CORSMiddleware,
@ -77,7 +81,7 @@ async def register(user: User):
@app.post('/login')
async def login(response: Response, form_data: OAuth2PasswordRequestForm = Depends()):
async def login(user: UserLogin):
"""logs in the user"""
users = []
@ -86,10 +90,7 @@ async def login(response: Response, form_data: OAuth2PasswordRequestForm = Depen
if text:
users.extend(json.loads(text))
username = form_data.username
password = form_data.password
cur_user = [i for i in users if i['username']==username]
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,
@ -98,7 +99,7 @@ async def login(response: Response, form_data: OAuth2PasswordRequestForm = Depen
else:
cur_user = cur_user[0]
password_match = Hasher.verify_password(password, cur_user['password'])
password_match = Hasher.verify_password(user.password, cur_user['password'])
if not password_match:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@ -107,16 +108,16 @@ async def login(response: Response, form_data: OAuth2PasswordRequestForm = Depen
encrypted_encryption_key = cur_user['encryption_key'].encode()
salt = deserialize_into_bytes(cur_user['salt'])
_, master_key = generate_user_passkey(password, 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
# }
response.set_cookie('token', value=access_token, max_age=1800, httponly=True, path='/')
return {'message': 'Authenticated'}
response = {
'message': 'authenticated',
'accessToken': access_token
}
return response
@app.post("/secret")
@ -184,9 +185,9 @@ async def update_secret(secret: Secret, current_user: dict = Depends(get_current
@app.get('/secret')
async def list_secret(current_user: dict = Depends(get_current_user2)):
async def list_secret(current_user: dict = Depends(get_current_user)):
"""Returns the encrypted secrets of the user."""
print('cuuuuuurrrrr', current_user)
data = []
with open('database/secrets.json', 'r') as f:
text = f.read()
@ -206,11 +207,10 @@ async def list_secret(current_user: dict = Depends(get_current_user2)):
@app.get('/validate-token')
async def validate_token(current_user: dict = Depends(get_current_user2)):
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)
# return {'message': "hello"}