forked from edwinperaza99/CPSC-449-Project1
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
40 lines (28 loc) · 1.36 KB
/
main.py
File metadata and controls
40 lines (28 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from fastapi import FastAPI, HTTPException, status, Depends
from models import NewAccountRequest
from http import HTTPStatus
from models import *
from helpers.db_query import *
from helpers.response import *
from helpers.auth import generate_claims, verify_password
import sqlite3
app = FastAPI()
@app.get("/")
async def root():
return {"message": "User Authentication services"}
@app.post("/register")
def register(request: NewAccountRequest, db:sqlite3.Connection = Depends(get_db)):
user = get_user_by_username(request.username, db)
if user:
raise_exception(HTTPStatus.CONFLICT, f'User with username {user["username"]} already exists')
if gracefully_handle_db_transaction(create_user_sql_script(request), db):
user = get_user_by_username(request.username, db)
return create_response(HTTPStatus.CREATED, f'{user["username"]} created!', user)
@app.post("/login")
def login(request:LoginRequest, db: sqlite3.Connection = Depends(get_db_reads)):
user = get_user_by_username(request.username, db, hide_password =False)
if not user:
raise_exception(HTTPStatus.NOT_FOUND, "User not Found")
if not verify_password(request.password, user["password"]):
raise_exception(HTTPStatus.UNAUTHORIZED, "Username or Password is not Valid")
return generate_claims(user["username"], user["user_id"], user["role"])