Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
jwt system
  • Loading branch information
otitamario committed Nov 21, 2022
commit 83c92ee841860c74d25fbdfd801ea04318e2f717
129 changes: 129 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/
3 changes: 3 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.config import settings
Expand Down Expand Up @@ -26,3 +27,5 @@
@app.get('/api/healthchecker')
def root():
return {'message': 'Hello World'}


35 changes: 23 additions & 12 deletions backend/app/routers/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from datetime import timedelta
import time
import json
import hashlib
from fastapi import APIRouter, Request, Response, status, Depends, HTTPException

Expand Down Expand Up @@ -36,7 +38,7 @@ async def create_user(payload: schemas.CreateUserSchema, request: Request, db: S
db.commit()
db.refresh(new_user)

return {'status': 'success', 'message': 'Verification token successfully'}
return {'status': 'success', 'message': 'User registered successfully'}


@router.post('/login')
Expand All @@ -56,12 +58,14 @@ def login(payload: schemas.LoginUserSchema, response: Response, db: Session = De

# Create access token
access_token = Authorize.create_access_token(
subject=str(user.id), expires_time=timedelta(minutes=ACCESS_TOKEN_EXPIRES_IN))
subject=str(user.id), expires_time=int(time.time()+ACCESS_TOKEN_EXPIRES_IN))

# Create refresh token
refresh_token = Authorize.create_refresh_token(
subject=str(user.id), expires_time=timedelta(minutes=REFRESH_TOKEN_EXPIRES_IN))

subject=str(user.id), expires_time=int(time.time()+REFRESH_TOKEN_EXPIRES_IN))

token_response={'status': 'success','user':user.username ,'token':{'access_token':access_token,'refresh_token':refresh_token}}

# Store refresh and access tokens in cookie
response.set_cookie('access_token', access_token, ACCESS_TOKEN_EXPIRES_IN * 60,
ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, True, 'lax')
Expand All @@ -71,24 +75,30 @@ def login(payload: schemas.LoginUserSchema, response: Response, db: Session = De
ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, False, 'lax')

# Send both access
return {'status': 'success', 'access_token': access_token}
return token_response


@router.get('/refresh')
@router.post('/refresh')
def refresh_token(response: Response, request: Request, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)):
try:
Authorize.jwt_refresh_token_required()

user_id = Authorize.get_jwt_subject()
if not user_id:
username = Authorize.get_jwt_subject()
if not username:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail='Could not refresh access token')
user = db.query(models.User).filter(models.User.id == user_id).first()
user = db.query(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail='The user belonging to this token no logger exist')
# Create access token
access_token = Authorize.create_access_token(
subject=str(user.id), expires_time=timedelta(minutes=ACCESS_TOKEN_EXPIRES_IN))
subject=str(user.username), expires_time=int(time.time()+ACCESS_TOKEN_EXPIRES_IN))

# Create refresh token
refresh_token = Authorize.create_refresh_token(
subject=str(user.username), expires_time=int(time.time()+REFRESH_TOKEN_EXPIRES_IN))
token_response={'status': 'success','user':user.username ,'token':{'access_token':access_token,'refresh_token':refresh_token}}
except Exception as e:
error = e.__class__.__name__
if error == 'MissingTokenError':
Expand All @@ -99,12 +109,13 @@ def refresh_token(response: Response, request: Request, Authorize: AuthJWT = Dep

response.set_cookie('access_token', access_token, ACCESS_TOKEN_EXPIRES_IN * 60,
ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, True, 'lax')

response.set_cookie('logged_in', 'True', ACCESS_TOKEN_EXPIRES_IN * 60,
ACCESS_TOKEN_EXPIRES_IN * 60, '/', None, False, False, 'lax')
return {'access_token': access_token}
return token_response


@router.get('/logout', status_code=status.HTTP_200_OK)
@router.post('/logout', status_code=status.HTTP_200_OK)
def logout(response: Response, Authorize: AuthJWT = Depends(), user_id: str = Depends(oauth2.require_user)):
Authorize.unset_jwt_cookies()
response.set_cookie('logged_in', '', -1)
Expand Down
2 changes: 1 addition & 1 deletion backend/app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class CreateUserSchema(UserBaseSchema):
passwordConfirm: str

class LoginUserSchema(BaseModel):
usernamel: str
username: str
password: constr(min_length=8)


Expand Down
2 changes: 2 additions & 0 deletions backend/readMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ alembic init alembic
alembic revision --autogenerate -m "creat users table"
<br>
alembic upgrade head
<br>
Run server: uvicorn app.main:app --host localhost --port 8000 --reload
24 changes: 24 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
Empty file added frontend/README.md
Empty file.
Loading