forked from Eljan404/Backend-code-of-login-and-registration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
51 lines (40 loc) · 1.73 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
import bcrypt
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from database import SessionLocal, engine
import models
app = FastAPI()
class UserCreate(BaseModel):
username: str
password: str
class User(BaseModel):
username: str
def hash_password(password):
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed_password.decode('utf-8')
def verify_password(password, hashed_password):
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
db = SessionLocal()
@app.post('/register', status_code=status.HTTP_201_CREATED)
def register_user(user_create: UserCreate):
db_user = db.query(models.User).filter(models.User.username == user_create.username).first()
if db_user:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Username already registered")
hashed_password = hash_password(user_create.password)
new_user = models.User(username=user_create.username, password=hashed_password)
db.add(new_user)
db.commit()
db.refresh(new_user)
statement = str(new_user.username)
return statement + ' created'
@app.post('/login', response_model=User)
def login_user(user_create: UserCreate):
db_user = db.query(models.User).filter(models.User.username == user_create.username).first()
if db_user is None or not verify_password(user_create.password ,db_user.password):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
print(db_user.username)
print(db_user.password)
print(verify_password(user_create.password,db_user.password))
return User(username=db_user.username)