Created
May 10, 2019 21:24
-
-
Save nilsdebruin/0faf0b55da7eee98e71dc4a40858027b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_user_by_email(db, email: str): | |
for username, value in db.items(): | |
if value.get("email") == email: | |
user_dict = db[username] | |
return User(**user_dict) | |
def authenticate_user_email(fake_db, email: str): | |
user = get_user_by_email(fake_db, email) | |
if not user: | |
return False | |
return user | |
def create_access_token(*, data: dict, expires_delta: timedelta = None): | |
to_encode = data.copy() | |
if expires_delta: | |
expire = datetime.utcnow() + expires_delta | |
else: | |
expire = datetime.utcnow() + timedelta(minutes=15) | |
to_encode.update({"exp": expire}) | |
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
return encoded_jwt | |
async def get_current_user(token: str = Depends(oauth2_scheme)): | |
credentials_exception = HTTPException( | |
status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials" | |
) | |
try: | |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
email: str = payload.get("sub") | |
if email is None: | |
raise credentials_exception | |
token_data = TokenData(email=email) | |
except PyJWTError: | |
raise credentials_exception | |
user = get_user_by_email(fake_users_db, email=token_data.email) | |
if user is None: | |
raise credentials_exception | |
return user | |
async def get_current_active_user(current_user: User = Depends(get_current_user)): | |
if current_user.disabled: | |
raise HTTPException(status_code=400, detail="Inactive user") | |
return current_user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment