forked from Rits1272/FastApi_Authentication
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
61 lines (46 loc) · 1.65 KB
/
main.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from typing import List
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
import models, schemas
from database import SessionLocal, engine
app = FastAPI()
# Creating the database tables
models.Base.metadata.create_all(bind=engine)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=True,
)
# Handling Session
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
@app.post("/api/register/")
def register(username: str, role: str, password: str, db: Session = Depends(get_db)):
student = models.Student(username=username, role=role)
student.hash_password(password)
student.create_access_token(data={"sub": username})
print(student.jwt_token)
db.add(student)
db.commit()
db.refresh(student)
return {"message": "Student registered successfully"}
@app.post("/api/login/")
def login(username: str, password: str, db: Session = Depends(get_db)):
student = db.query(models.Student).filter(models.Student.username == username).first()
if student.verify_password(password):
return {"message": "Login Successfull", "status": 200, "token": student.jwt_token}
else:
return {"message": "Invalid Credentials", "status": 503}
@app.post("/api/valid/")
def check(token: str, db: Session = Depends(get_db)):
student = db.query(models.Student).filter(models.Student.jwt_token == token).first()
if student:
return {"message" : "Yes", "role": student.role}
return {"message" : "No"}