Skip to content

Commit

Permalink
feat: add signup
Browse files Browse the repository at this point in the history
  • Loading branch information
chanh-1 committed Apr 14, 2023
1 parent 7768322 commit b6d115e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
34 changes: 34 additions & 0 deletions server/api/auth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import jwt
import database
from database import User
from fastapi import HTTPException
from typing import Annotated
from passlib.hash import sha256_crypt
from sqlalchemy.orm import Session
Expand All @@ -20,6 +21,12 @@ class AuthModel(BaseModel):
password: str


class SignUpModal(BaseModel):
username: str
email: str
password: str


@auth_router.post("/login", status_code=200)
def login(auth: AuthModel, db: Session = Depends(database.db_session)):
user: User = db.query(User).filter(User.username == auth.username).first() # type: ignore
Expand All @@ -41,3 +48,30 @@ def decode_token(token: Annotated[str, Header()]):
response = {"msg": "failed"}
response = {"msg": "success", "username": username}
return response


@auth_router.post("/signup", status_code=200)
def sign_up(auth: SignUpModal, db: Session = Depends(database.db_session)):
user_exists = False
email_exists = False
user: User = db.query(User).filter(User.username == auth.username).first() # type: ignore
if user is not None:
user_exists = True
user: User = db.query(User).filter(User.email == auth.email).first() # type: ignore
if user is not None:
email_exists = True
if user_exists and email_exists:
raise HTTPException(status_code=400, detail="Username and email already registered")
elif user_exists:
raise HTTPException(status_code=400, detail="Username is taken")
elif email_exists:
raise HTTPException(status_code=400, detail="Email already registered")
if not user_exists and not email_exists: # type: ignore
user: User = User(username=auth.username, email=auth.email, password=sha256_crypt.hash(auth.password)) # type: ignore
db.add(user)
db.commit()
token = jwt.encode(payload={"username": auth.username}, key=c.JWT_SECRET)
response = {"msg": "success", "token": token}
else:
response = {"msg": "failed"}
return response
3 changes: 2 additions & 1 deletion server/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@ class User(Base):
__tablename__ = "user"

id = Column(Integer, primary_key=True)
email = Column(String(80), unique=True, nullable=False)
username = Column(String(80), unique=True, nullable=False)
password = Column(String(80), nullable=False)
meta = Column(JSON)

def __repr__(self):
return f"User(id={self.id}, username={self.username}, password={self.password}, meta={self.meta})"
return f"User(id={self.id}, username={self.username}, meta={self.meta})"


class ChatBot(Base):
Expand Down

0 comments on commit b6d115e

Please sign in to comment.