Commit existing codebase

This commit is contained in:
Andrey Chervyakov 2021-02-25 01:39:14 +06:00
commit 49bc902bb9
24 changed files with 1208 additions and 0 deletions

39
app/auth/service.py Normal file
View file

@ -0,0 +1,39 @@
import os
from datetime import datetime, timedelta
from typing import Optional
from jose import jwt
from jose.constants import ALGORITHMS
from sqlalchemy.orm import Session
from app.auth.dto import Credentials
from app.config import config
from app.user.service import get_user_by_username, passwords_match
JWT_SECRET = config["CGNO_ID_JWT_SECRET"]
JWT_ISSUER = "Energia"
def authenticate(credentials: Credentials, db: Session) -> Optional[str]:
user = get_user_by_username(db, credentials.username)
if passwords_match(user.password, credentials.password):
token = issue_token(user.id)
return token
else:
return None
def issue_token(user_id: int) -> str:
now = datetime.utcnow()
claims = {
"sub": str(user_id),
"iss": JWT_ISSUER,
"iat": now,
"nbf": now,
"exp": now + timedelta(weeks=1)
}
return jwt.encode(claims, JWT_SECRET, algorithm=ALGORITHMS.HS256)
def verify_token(token: str) -> dict:
return jwt.decode(token, JWT_SECRET, algorithms=ALGORITHMS.HS256, issuer=JWT_ISSUER)