Skip to content
Merged
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
43b3f1b
WIP register - not finished
kobyfogel Jan 19, 2021
d211377
register before updated pull
kobyfogel Jan 22, 2021
2f0501a
register for review
kobyfogel Jan 22, 2021
a5a1a04
register fixed errors
kobyfogel Jan 23, 2021
5d2c52e
register fixed flake-8
kobyfogel Jan 23, 2021
eafbe37
register fixed tests flake8
kobyfogel Jan 23, 2021
56d0ca3
register fixed tests issues
kobyfogel Jan 23, 2021
00d9e7d
register placeholders fix
kobyfogel Jan 23, 2021
c9c777e
register flake8 fix
kobyfogel Jan 23, 2021
bb2b52d
register flake8 more fixes
kobyfogel Jan 23, 2021
a32c9c4
fixed CR suggestions
kobyfogel Jan 24, 2021
deee638
first commit
kobyfogel Jan 24, 2021
7ca40e1
fixed check_jwt_token
kobyfogel Jan 25, 2021
1bdbc54
Not Finshed
kobyfogel Jan 26, 2021
eed52e2
minor fix
kobyfogel Jan 26, 2021
b793e2c
starting dependancy
kobyfogel Jan 31, 2021
46820e1
dependancies working
kobyfogel Feb 1, 2021
68e40fe
redirectin and user messages
kobyfogel Feb 1, 2021
b7e7e60
async fixing
kobyfogel Feb 1, 2021
e3c620a
exception handler
kobyfogel Feb 1, 2021
b6b7441
quary parameters
kobyfogel Feb 2, 2021
d1849bb
Documentation added
kobyfogel Feb 3, 2021
8d7f135
after pull and fixing conflicts
kobyfogel Feb 3, 2021
84db349
fixed pep8
kobyfogel Feb 3, 2021
d9ae477
pep8 more fixes
kobyfogel Feb 3, 2021
d7465b5
pep8 config fix
kobyfogel Feb 3, 2021
9d735b1
pep8 jwt fix
kobyfogel Feb 3, 2021
4f5a127
pep8 jwt final fix
kobyfogel Feb 3, 2021
4392974
pep8 final fix
kobyfogel Feb 3, 2021
b9ee9d3
CR fixes, tests added
kobyfogel Feb 7, 2021
94eb29a
after merge conflicts
kobyfogel Feb 7, 2021
97d8aff
flake8 fixes
kobyfogel Feb 7, 2021
8b54f67
flake8 fixes2
kobyfogel Feb 7, 2021
b46d679
updating requirements
kobyfogel Feb 7, 2021
73f53c1
test added
kobyfogel Feb 7, 2021
c15a451
conflicts fixed
kobyfogel Feb 7, 2021
c3cad9d
flake8 fix
kobyfogel Feb 7, 2021
befd5f9
CR fixing
kobyfogel Feb 9, 2021
063489f
conflicts fixed
kobyfogel Feb 9, 2021
da12351
flake8 fixes
kobyfogel Feb 9, 2021
cc4fdae
flake8 fix2
kobyfogel Feb 9, 2021
0ae794a
flake8 fixes3
kobyfogel Feb 9, 2021
7a47985
flake8 fixes4
kobyfogel Feb 9, 2021
e7bc55a
flake8 fixes5
kobyfogel Feb 9, 2021
8fbe36a
CR fix
kobyfogel Feb 9, 2021
f203c38
Revert "CR fix"
kobyfogel Feb 9, 2021
bbb241b
CR fixes
kobyfogel Feb 10, 2021
b00439d
conflicts fix
kobyfogel Feb 10, 2021
84a6fa7
Merge branch 'develop' of https://github.com/PythonFreeCourse/calenda…
kobyfogel Feb 10, 2021
5f3e3e1
many CR fixes
kobyfogel Feb 11, 2021
5d47833
conflicts fixed
kobyfogel Feb 11, 2021
2488679
CR fixes
kobyfogel Feb 12, 2021
7d5395c
changed dependencies according to CR
kobyfogel Feb 14, 2021
8f59086
fix conflicts
kobyfogel Feb 14, 2021
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ dmypy.json
# Pyre type checker
.pyre/


# register stuff
run.txt
# VScode
.vscode/
app/.vscode/
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,22 @@ uvicorn app.main:app --reload
python -m pytest --cov-report term-missing --cov=app tests
```

### Generating personal JWT Secret Key
'''shell
python
import secrets
secrets.token_hex(32)
# copy generated string.
# in config.py file, replace JWT_KEY value with generated string
'''

## Using security dependencies:
'''
from app.internal.security.dependencies:
use current_user_required and current_user functions as a route dependencies.
an example for how to use can be found at tests.security_testing_routes file.
'''

## Contributing
View [contributing guidelines](https://github.com/PythonFreeCourse/calendar/blob/master/CONTRIBUTING.md).

7 changes: 7 additions & 0 deletions app/config.py.example
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ email_conf = ConnectionConfig(
USE_CREDENTIALS=True,
)

# register
DATABASE_CONNECTION_STRING = "sqlite:///calendar.db"

# security
JWT_KEY = "c06857128217c661de43d746ecdbe9f1dbc3b3685957fab64512456f639b1881"
JWT_ALGORITHM = "HS256"
JWT_MIN_EXP = 60 * 24 * 7
templates = Jinja2Templates(directory=os.path.join("app", "templates"))

# application name
Expand Down
90 changes: 90 additions & 0 deletions app/database/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from typing import Optional, Union
from pydantic import BaseModel, validator, EmailStr, EmailError


EMPTY_FIELD_STRING = 'field is required'
MIN_FIELD_LENGTH = 3
MAX_FIELD_LENGTH = 20


def fields_not_empty(field: Optional[str]) -> Union[ValueError, str]:
"""Global function to validate fields are not empty."""
if not field:
raise ValueError(EMPTY_FIELD_STRING)
return field


class UserBase(BaseModel):
"""
Validating fields types
Returns a User object without sensitive information
"""
username: str
email: str
full_name: str
description: Optional[str] = None

class Config:
orm_mode = True


class UserCreate(UserBase):
"""Validating fields types"""
password: str
confirm_password: str

"""
Calling to field_not_empty validaion function,
for each required field.
"""
_fields_not_empty_username = validator(
'username', allow_reuse=True)(fields_not_empty)
_fields_not_empty_full_name = validator(
'full_name', allow_reuse=True)(fields_not_empty)
_fields_not_empty_password = validator(
'password', allow_reuse=True)(fields_not_empty)
_fields_not_empty_confirm_password = validator(
'confirm_password', allow_reuse=True)(fields_not_empty)
_fields_not_empty_email = validator(
'email', allow_reuse=True)(fields_not_empty)

@validator('confirm_password')
def passwords_match(
cls, confirm_password: str,
values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
if 'password' in values and confirm_password != values['password']:
raise ValueError("doesn't match to password")
return confirm_password

@validator('username')
def username_length(cls, username: str) -> Union[ValueError, str]:
"""Validating username length is legal"""
if not (MIN_FIELD_LENGTH < len(username) < MAX_FIELD_LENGTH):
raise ValueError("must contain between 3 to 20 charactars")
return username

@validator('password')
def password_length(cls, password: str) -> Union[ValueError, str]:
"""Validating username length is legal"""
if not (MIN_FIELD_LENGTH < len(password) < MAX_FIELD_LENGTH):
raise ValueError("must contain between 3 to 20 charactars")
return password

@validator('email')
def confirm_mail(cls, email: str) -> Union[ValueError, str]:
"""Validating email is valid mail address."""
try:
EmailStr.validate(email)
return email
except EmailError:
raise ValueError("address is not valid")


class User(UserBase):
"""
Validating fields types
Returns a User object without sensitive information
"""
id: int
is_active: bool
Empty file.
33 changes: 33 additions & 0 deletions app/internal/security/dependancies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import Union
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe some problems in this CR could be resolved with better naming.

We should also rethink a bit about the design: there are some functions that it's hard to tell why they're different one from another.


from app.database.database import get_db
from app.internal.security.ouath2 import (
Depends, Session, check_jwt_token, get_cookie)
from app.internal.security.schema import CurrentUser
from starlette.requests import Request


async def current_user_required(
request: Request,
db: Session = Depends(get_db),
jwt: str = Depends(get_cookie)) -> CurrentUser:
"""A dependency function protecting routes for only logged in user"""
user = await check_jwt_token(db, jwt, path=request.url.path)
if user:
return user


async def current_user(
request: Request,
db: Session = Depends(get_db),) -> Union[CurrentUser, bool]:
"""
A dependency function.
Returns logged in User object if exists.
None if not.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer a docstring that matches the guidelines in PEP 257:

    """Return the currently logged in user.

    Return logged in User object if exists, None if not.
    A dependency function.
    """

if 'Authorization' in request.cookies:
jwt = request.cookies['Authorization']
else:
return None
user = await check_jwt_token(db, jwt)
return user
127 changes: 127 additions & 0 deletions app/internal/security/ouath2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from datetime import datetime, timedelta
from typing import Union

from app.config import JWT_ALGORITHM, JWT_KEY, JWT_MIN_EXP
from passlib.context import CryptContext
from app.database.models import User
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt
from jwt.exceptions import InvalidSignatureError
from sqlalchemy.orm import Session
from starlette.requests import Request
from starlette.responses import RedirectResponse
from starlette.status import HTTP_401_UNAUTHORIZED
from .schema import LoginUser, CurrentUser


pwd_context = CryptContext(schemes=["bcrypt"])
oauth_schema = OAuth2PasswordBearer(tokenUrl="/login")


async def get_db_user_by_username(db: Session, username: str) -> User:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this function should be inside the User model, or on /app/internal/users.py, and named by_username.

Keep it simple and think about other developers who want to use it :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know it does.
The reason i have it there is because i though that it will be 'more corrects' to build the login and authentication systems as a stand-alone system. A code that needs the minimum changes if someone wants to use it in another project.
I will delete it if you prefer, and use the other function.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do prioritize DRY code in this case :)

"""Checking database for user by username field"""
user = db.query(User).filter_by(username=username).first()
return user


def get_hashed_password(password) -> str:
"""Hashing user password"""
return pwd_context.hash(password)


def verify_password(plain_password, hashed_password) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add type annotations

"""Verifying password and hashed password are equal"""
return pwd_context.verify(plain_password, hashed_password)


async def authenticate_user(
db: Session, user: LoginUser) -> Union[LoginUser, bool]:
"""Verifying user is in database and password is correct"""
db_user = await get_db_user_by_username(db=db, username=user.username)
if db_user:
if verify_password(user.password, db_user.password):
return LoginUser(
username=user.username, password=db_user.password)
return False


def create_jwt_token(
user: LoginUser, JWT_MIN_EXP: int = JWT_MIN_EXP,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't call parameters with ALL_CAPS. you can use jwt_expiration_time and jwt_key

JWT_KEY: str = JWT_KEY) -> str:
"""Creating jwt-token out of user unique data"""
expiration = datetime.utcnow() + timedelta(minutes=JWT_MIN_EXP)
jwt_payload = {
"sub": user.username,
"hashed_password": user.password,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a good reason to store the user's password in the token?

"exp": expiration}
jwt_token = jwt.encode(
jwt_payload, JWT_KEY, algorithm=JWT_ALGORITHM)
return jwt_token


async def check_jwt_token(
db: Session,
token: str = Depends(oauth_schema),
path: bool = None) -> CurrentUser:
"""
Check whether JWT token is correct. Returns User object if yes.
Returns None or raises HTTPException,
depanding which depandency activated this function.
"""
try:
jwt_payload = jwt.decode(
token, JWT_KEY, algorithms=JWT_ALGORITHM)
jwt_username = jwt_payload.get("sub")
jwt_hashed_password = jwt_payload.get("hashed_password")
db_user = await get_db_user_by_username(db, username=jwt_username)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? Please read about JWT tokens - one of the main benefits is the performance boost gain from not talking with the DB

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validating the token is the lesser reason for that. I can do it by comparing to to the SECRET_KEY, and just by successfully decoding the token.
The main reason for that is: Already using the authentication function to return the User instance to the protected route. This way everybody can use it for other functionalities, without the need to query in each route. The dependency itself, is already returning the pydantic object with all the Base.User object parameters, just without the password.
I found it extremely useful in other functionalities.
Do you prefer that i will change that?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, but I still unable to understand why.

Why not having one method to check the username and the password against the database (which happens only if the user asks to log-in), and another method to check if the user is authenticated (have a valid JWT token)?

if db_user and db_user.password == jwt_hashed_password:
return CurrentUser(**db_user.__dict__)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the difference between CurrentUser and LoginUser?

Copy link
Contributor Author

@kobyfogel kobyfogel Feb 10, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LoginUser is a pydantic object for internal actions management of the security system.
CurrentUser is the Object that will be returned to the routes from the dependencies functions, after verifying JWT token. It's purpose is to return a User Base Model object to the routed, minus the password column, and keep the workflow with pydantic models.
I'm thinking maybe to re-change it to a Base Model object, as the code is keep on changing by other. And this object has to be maintained in order to keep it's functionality.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are the downsides of having only one of them? Currently having two different classes for two similar objects is a bit confusing from the developer side

Copy link
Contributor Author

@kobyfogel kobyfogel Feb 10, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If by 'them' you mean LoginUser and CurrentUser, so they are not the same at all. LoginUser is created from the login form, and verifies that required information was given by the user. It is essential for this action. As CurrentUser supposed to return all the User information to the routes, after jwt verification.
Maybe it will be better to delete CurrentUser, and just return the User Base Object? It's a db object, no confusions there. That will be also much easy to understand just by looking at the type annotations.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the major source of confusion is in the object's name. Maybe we should find a better name which describes it better and which highlights the differences between them.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if it ok by you, i will just return db_user. otherwise, every change in User base model will have to be updated in CurrentUser, in order for it to return the new column.

Copy link
Member

@yammesicka yammesicka Feb 11, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just be sure to name stuff very indicatively. Otherwise it'll be really PITA to maintain :)

else:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
headers=path,
detail="Your token is incorrect. Please log in again")
except InvalidSignatureError:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
headers=path,
detail="Your token is incorrect. Please log in again")
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
headers=path,
detail="Your token has expired. Please log in again")
except jwt.DecodeError:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
headers=path,
detail="Your token is incorrect. Please log in again")


async def get_cookie(request: Request) -> str:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name should be get_authorization_cookie (this function's purpose is not "getting any cookie")

"""
Extracts jwt from HTTPONLY cookie, if exists.
Raises HTTPException if not.
"""
if 'Authorization' in request.cookies:
return request.cookies['Authorization']
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
headers=request.url.path,
detail="Please log in to enter this page")


async def my_exception_handler(
request: Request,
exc: HTTP_401_UNAUTHORIZED) -> RedirectResponse:
"""
Whenever HTTP_401_UNAUTHORIZED is raised,
redirecting to login route, with original requested url,
and details for why original request failed.
"""
paramas = f"?next={exc.headers}&message={exc.detail}"
url = f"/login{paramas}"
response = RedirectResponse(url=url)
response.delete_cookie('Authorization')
return response
37 changes: 37 additions & 0 deletions app/internal/security/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from typing import List, Optional

from app.database.models import UserEvent
from pydantic import BaseModel


class LoginUser(BaseModel):
"""
Validating fields types
Returns a User object for signing in.
"""
username: str
password: str

class Config:
orm_mode = True


class CurrentUser(BaseModel):
"""
Security dependencies will return this object,
instead of db object.
Returns all User's parameters, except password.
"""
id: int
username: str
full_name: str
email: str
language: str = None
description: str = None
avatar: str
telegram_id: str = None
events = Optional[List[UserEvent]]

class Config:
orm_mode = True
arbitrary_types_allowed = True
46 changes: 46 additions & 0 deletions app/internal/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from app.database import models, schemas
from app.internal.security.ouath2 import get_hashed_password
from sqlalchemy.orm import Session


def get_by_id(db: Session, user_id: int) -> models.User:
"""query database for a user by unique id"""
return db.query(models.User).filter(models.User.id == user_id).first()


def get_by_username(db: Session, username: str) -> models.User:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this function is different from get_db_user_by_username?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can use this one, but i tried to explain above why i did that.

"""query database for a user by unique username"""
return db.query(models.User).filter(
models.User.username == username).first()


def get_by_mail(db: Session, email: str) -> models.User:
"""query database for a user by unique email"""
return db.query(models.User).filter(models.User.email == email).first()


def create(db: Session, user: schemas.UserCreate) -> models.User:
"""
creating a new User object in the database, with hashed password
"""
unhashed_password = user.password.encode('utf-8')
hashed_password = get_hashed_password(unhashed_password)
user_details = {
'username': user.username,
'full_name': user.full_name,
'email': user.email,
'password': hashed_password,
'description': user.description
}
db_user = models.User(**user_details)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user


def delete_by_mail(db: Session, email: str) -> None:
"""deletes a user from database by unique email"""
db_user = get_by_mail(db=db, email=email)
db.delete(db_user)
db.commit()
Loading