Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add config option for JWT expire length #44 #146

Merged
merged 1 commit into from
Sep 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ from flask import Flask
from flask_jwt_router import JwtRoutes

app = Flask(__name__)
# You are required to always set a unique SECRET_KEY for your app
app.config["SECRET_KEY"] = "your_app_secret_key"

JwtRoutes(app)

Expand Down Expand Up @@ -177,6 +179,24 @@ If you are handling a request without a token in the headers you can call::
jwt_routes.create_token(entity_id=user_data.id, table_name="users")
```

# Setting the Token Expire Duration
There are two ways to set the expire duration of the JWT.

from your app config
```python
# Set the token expire duration to 7 days
app.config["JWT_EXPIRE_DAYS"] = 7
```
calling the `set_exp`
```python

# Set the token expire duration to 14 days
jwt_routes = JwtRoutes()
# jwt_routes.init_app( ...etc
jwt_routes.set_exp(expire_days=14)
```
By default the expire duration is set to 30 days

An Example configuration for registering & logging in users of different types:
```python
app.config["IGNORED_ROUTES"] = [("GET", "/")]
Expand Down
29 changes: 19 additions & 10 deletions flask_jwt_router/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,14 @@ def __init__(self):


class _Config:
"""
:param secret_key: User defined secret key
:param entity_key: The name of the model's entity attribute
:param whitelist_routes: List of tuple pairs of verb & url path
:param api_name: the api name prefix e.g `/api/v1`
:param ignored_routes: Opt our routes from api name prefixing
:param entity_models: Multiple entities to be authenticated
"""
def __init__(self,
secret_key=None,
entity_key="id",
whitelist_routes=None,
api_name=None,
ignored_routes=None,
entity_models=None,
expire_days=None,
):

self.secret_key = secret_key
Expand All @@ -39,24 +32,38 @@ def __init__(self,
self.api_name = api_name
self.ignored_routes = ignored_routes
self.entity_models = entity_models
self.expire_days = expire_days


class BaseConfig(ABC):
"""Abstract Base Class for Extensions"""

def __init__(self):
self.expire_days = None

@abstractmethod
def init_config(self, config: Dict[str, Any], **kwargs) -> None:
# pylint: disable=missing-function-docstring
pass


class Config(BaseConfig):
"""Contains the main configuration values"""
entity_models: List[_ORMType]
"""
:param secret_key: User defined secret key
:param entity_key: The name of the model's entity attribute
:param whitelist_routes: List of tuple pairs of verb & url path
:param api_name: the api name prefix e.g `/api/v1`
:param ignored_routes: Opt our routes from api name prefixing
:param entity_models: Multiple entities to be authenticated
:param expire_days: Expire time for the token in days
"""
secret_key: str
entity_key: str
whitelist_routes: List[Tuple[str]]
api_name: str
ignored_routes: List[Tuple[str]]
entity_models: List[_ORMType]
expire_days: int

def init_config(self, app_config: Dict[str, Any], **kwargs) -> None:
"""
Expand All @@ -71,6 +78,7 @@ def init_config(self, app_config: Dict[str, Any], **kwargs) -> None:
app_config.get("JWT_ROUTER_API_NAME"),
app_config.get("IGNORED_ROUTES") or [],
entity_models or app_config.get("ENTITY_MODELS") or [],
app_config.get("JWT_EXPIRE_DAYS")
)
if not _config.secret_key:
raise SecretKeyError
Expand All @@ -81,3 +89,4 @@ def init_config(self, app_config: Dict[str, Any], **kwargs) -> None:
self.api_name = _config.api_name
self.ignored_routes = _config.ignored_routes
self.entity_models = _config.entity_models
self.expire_days = _config.expire_days
40 changes: 34 additions & 6 deletions flask_jwt_router/_jwt_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from flask_jwt_router import JwtRoutes

app = Flask(__name__)
# You are required to always set a unique SECRET_KEY for your app
app.config["SECRET_KEY"] = "your_app_secret_key"

JwtRoutes(app)

Expand Down Expand Up @@ -77,6 +79,24 @@ def create_app(config):
...
jwt_routes.init_app(app, entity_models=[UserModel, TeacherModel, ...etc])

Setting the Token Expire Duration
=================================

There are two ways to set the expire duration of the JWT.

from your app config::

# Set the token expire duration to 7 days
app.config["JWT_EXPIRE_DAYS"] = 7

using the :class:`~flask_jwt_router.set_exp` method::

# Set the token expire duration to 14 days
jwt_routes = JwtRoutes()
# jwt_routes.init_app( ...etc
jwt_routes.set_exp(expire_days=14)

By default the expire duration is set to 30 days

Authorization & Tokens
======================
Expand Down Expand Up @@ -163,6 +183,8 @@ def login():
# pylint:disable=invalid-name
logger = logging.getLogger()

EXPIRE_DEFAULT = 30


class JwtRoutes:
"""
Expand All @@ -180,8 +202,9 @@ class JwtRoutes:
#: A list of entity models
entity_models: List[_ORMType]

#: Token expiry value. eg. 30 = 30 days from creation date.
exp: int = 30
#: Low level expire member. See :class:`~flask_jwt_router._config` & set with JWT_EXPIRE_DAYS
#: or use :class:`~flask_jwt_router.set_exp`.
exp: int

#: The class that is used to create Config objects. See :class:`~flask_jwt_router._config`
#: for more information.
Expand Down Expand Up @@ -224,6 +247,10 @@ def init_app(self, app=None, **kwargs):
self.entity = Entity(self.config)
self.routing = Routing(self.app, self.config, self.entity)
self.app.before_request(self.routing.before_middleware)
if self.config.expire_days:
self.exp = self.config.expire_days
else:
self.exp = EXPIRE_DEFAULT

# pylint:disable=no-self-use
def get_app_config(self, app):
Expand All @@ -246,15 +273,16 @@ def get_entity_id(self, **kwargs):
return None

# pylint:disable=no-self-use
def get_exp(self, **kwargs):
def set_exp(self, **kwargs) -> None:
"""
:param kwargs: Dict[str, int]
:return: number
- expire_days: The expire time for the JWT in days
:return: None
"""
try:
return kwargs['exp']
self.exp = kwargs['expire_days']
except KeyError as _:
return 30
self.exp = EXPIRE_DEFAULT

def create_token(self, **kwargs) -> str:
"""
Expand Down
4 changes: 0 additions & 4 deletions source/flask_jwt_router.rst

This file was deleted.

1 change: 0 additions & 1 deletion source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ Welcome to Flask JWT Router
authentication
entity
config
flask_jwt_router
routing


Expand Down
4 changes: 3 additions & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class TestConfig:
"SECRET_KEY": "a sectrect key",
"JWT_ROUTER_API_NAME": "api/v1",
"ENTITY_KEY": "user_id",
"JWT_EXPIRE_DAYS": 6,
}

def test_init_config(self, MockEntityModel):
Expand All @@ -29,8 +30,9 @@ def test_init_config(self, MockEntityModel):
assert config.entity_models == [MockEntityModel]
assert config.entity_key == "user_id"
assert config.api_name == "api/v1"
assert config.expire_days == 6

config_two = {**self.config, "ENTITY_MODELS": [MockEntityModel]}
config.init_config(config_two)

assert config.entity_models == [MockEntityModel]
assert config.entity_models == [MockEntityModel]
73 changes: 0 additions & 73 deletions tests/test_jwt_router.py

This file was deleted.

Loading