Skip to content

Commit

Permalink
Properly check for dict values in JWTs (#28)
Browse files Browse the repository at this point in the history
This solves and issue where if name or role are empty a KeyError is
raised
  • Loading branch information
omercnet authored Nov 6, 2022
1 parent eea5c9b commit 21acdac
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 79 deletions.
4 changes: 2 additions & 2 deletions django_descope/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class LoginForm(forms.Form):
)

def clean_email(self) -> str:
email = self.cleaned_data["email"].lower()
email = self.cleaned_data.get("email").lower()

try:
user = User.objects.get(email=email)
Expand All @@ -36,7 +36,7 @@ class SignupForm(forms.Form):
)

def clean_email(self) -> str:
email = self.cleaned_data["email"].lower()
email = self.cleaned_data.get("email").lower()

try:
user = User.objects.get(email=email)
Expand Down
37 changes: 24 additions & 13 deletions django_descope/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from typing import Dict

from descope import (
REFRESH_SESSION_TOKEN_NAME,
Expand Down Expand Up @@ -45,7 +46,7 @@ def post(self, request: HttpRequest, *args, **kwargs):
context["login_form"] = form
return self.render_to_response(context)

email = form.cleaned_data["email"]
email = form.cleaned_data.get("email")
try:
descope_client.magiclink.sign_in(
DeliveryMethod.EMAIL,
Expand All @@ -71,24 +72,34 @@ class LoginVerify(TemplateView):

def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
token = request.GET["t"]
token = request.GET.get("t")
try:
jwt_response = descope_client.magiclink.verify(token)
except AuthException as e:
context["login_error"] = e.error_message
return self.render_to_response(context)

logger.info("Login successful", jwt_response)
request.session["descopeUser"] = u = jwt_response["user"]
request.session["descopeSession"] = s = jwt_response[SESSION_TOKEN_NAME]
request.session["descopeRefresh"] = jwt_response[REFRESH_SESSION_TOKEN_NAME]

user, created = User.objects.get_or_create(
username=u["userId"],
email=u["email"],
is_staff=("is_staff" in s["roles"]),
first_name=u["name"].split()[0],
last_name=" ".join(u["name"].split()[0:]),

u: Dict
s: Dict
request.session["descopeUser"] = u = jwt_response.get("user")
request.session["descopeSession"] = s = jwt_response.get(SESSION_TOKEN_NAME)
request.session["descopeRefresh"] = jwt_response.get(REFRESH_SESSION_TOKEN_NAME)

username = u.get("userId")
email = u.get("email")
roles = s.get("roles", [])
name = u.get("name", "").split()
first_name = " ".join(name[:1])
last_name = " ".join(name[1:])
user, _ = User.objects.get_or_create(
username=username,
email=email,
is_staff=("is_staff" in roles),
is_superuser=("is_superuser" in roles),
first_name=first_name,
last_name=last_name,
)

login(request, user)
Expand All @@ -115,7 +126,7 @@ def post(self, request, *args, **kwargs):
context["signup_form"] = form
return self.render_to_response(context)

email = form.cleaned_data["email"]
email = form.cleaned_data.get("email")
try:
descope_client.magiclink.sign_up_or_in(
DeliveryMethod.EMAIL,
Expand Down
49 changes: 32 additions & 17 deletions example/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions example/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ license = "MIT"
python = ">=3.7,<4.0"
django = ">=3.2,<5"
django-descope = {path = "..", develop = true}
python-dotenv = "0.21.0"

[tool.poetry.dev-dependencies]
black = "22.6.0"
Expand Down
9 changes: 8 additions & 1 deletion example/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

import os
from pathlib import Path

from dotenv import load_dotenv

load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

Expand All @@ -28,7 +33,9 @@
ALLOWED_HOSTS = ["*"]


DESCOPE_PROJECT_ID = "P2GMsgxPSSQrq3Ig7M0ExAwoRGbP" # <-- Set this to your project ID
DESCOPE_PROJECT_ID = os.environ.get(
"DESCOPE_PROJECT_ID"
) # <-- Set this to your project ID


# Application definition
Expand Down
26 changes: 13 additions & 13 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 21acdac

Please sign in to comment.