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

Adding auth0 ❌ not working rn #9

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
venv/
myenv/
.env/

python-version/
pyproject.toml/
uv.lock/
# Python
__pycache__/
*.py[cod]
Expand Down
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.13
59 changes: 59 additions & 0 deletions middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import json
from jose import jwt
from urllib.request import urlopen
from django.conf import settings
from django.http import JsonResponse

def get_token_auth_header(request):
auth = request.META.get("HTTP_AUTHORIZATION", None)
if not auth:
raise Exception("Authorization header is expected")

parts = auth.split()

if parts[0].lower() != "bearer":
raise Exception("Authorization header must start with Bearer")
elif len(parts) == 1:
raise Exception("Token not found")
elif len(parts) > 2:
raise Exception("Authorization header must be Bearer token")

token = parts[1]
return token

def requires_auth(f):
def decorated(request, *args, **kwargs):
token = get_token_auth_header(request)
jsonurl = urlopen("https://"+settings.AUTH0_DOMAIN+"/.well-known/jwks.json")
jwks = json.loads(jsonurl.read())
unverified_header = jwt.get_unverified_header(token)
rsa_key = {}
for key in jwks["keys"]:
if key["kid"] == unverified_header["kid"]:
rsa_key = {
"kty": key["kty"],
"kid": key["kid"],
"use": key["use"],
"n": key["n"],
"e": key["e"]
}
if rsa_key:
try:
payload = jwt.decode(
token,
rsa_key,
algorithms=["RS256"],
audience=settings.AUTH0_CLIENT_ID,
issuer="https://"+settings.AUTH0_DOMAIN+"/"
)
except jwt.ExpiredSignatureError:
return JsonResponse({'message': 'token is expired'}, status=401)
except jwt.JWTClaimsError:
return JsonResponse({'message': 'incorrect claims, please check the audience and issuer'}, status=401)
except Exception:
return JsonResponse({'message': 'Unable to parse authentication token.'}, status=401)

request.user = payload
return f(request, *args, **kwargs)
return JsonResponse({'message': 'Unable to find appropriate key'}, status=401)
return decorated
Empty file.
3 changes: 3 additions & 0 deletions pup_spot/auth0_login/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions pup_spot/auth0_login/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class Auth0LoginConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "auth0_login"
Empty file.
3 changes: 3 additions & 0 deletions pup_spot/auth0_login/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions pup_spot/auth0_login/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions pup_spot/auth0_login/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
45 changes: 37 additions & 8 deletions pup_spot/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

import os
from django.core.exceptions import ImproperlyConfigured




from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
Expand Down Expand Up @@ -39,19 +45,42 @@
"django.contrib.staticfiles",
"rest_framework",
"locations",
"user_profiles"
"user_profiles",
# "rest_framwork_simplejwt",
"corsheaders",
"auth0_login"
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"corsheaders.middleware.CorsMiddleware",
]


REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
}


AUTH0_DOMAIN = "dev-8yxn7ind66gqamzr.us.auth0.com"
API_IDENTIFIER = "https://pupspot_api.com"
AUTH0_CLIENT_SECRET = "5PrtD3hPWSG_BL5l_GMVkzJWJ04hQx2Y_FQUF89DehRr2sutgHDtTgoOsmF5HIoM"
AUTH0_CLIENT_ID = "XAZYgozsrACx9pABKz376jteImbYL1an"
AUTH0_CALLBACK_URL = "http://localhost:8000/callback"

SIMPLE_JWT = {
'ALGORITHM': 'RS256'
}


ROOT_URLCONF = 'urls'

TEMPLATES = [
Expand Down
2 changes: 2 additions & 0 deletions pup_spot/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
"""
from django.contrib import admin
from django.urls import path, include
from .views import my_protected_view

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api_urls')),
path('protected/', my_protected_view),
]

10 changes: 5 additions & 5 deletions pup_spot/user_profiles/models/user_profile.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from django.db import models
from .base_profile import BaseProfile
from locations.models import LocationRating, LocationCrowdMeter, LocationDogCountReport
from django.contrib.auth.hashers import make_password, check_password
# from django.contrib.auth.hashers import make_password, check_password

class UserProfile(BaseProfile):
email = models.EmailField(unique=True)
password = models.CharField(max_length=255) # Make sure to hash passwords before saving
# password = models.CharField(max_length=255) # Make sure to hash passwords before saving
location = models.CharField(max_length=255)
bio = models.TextField(blank=True, null=True)
username = models.CharField(max_length=255, unique=True)
Expand All @@ -14,9 +14,9 @@ def __str__(self):
return self.username


def check_password(self, raw_password):
# Check password by comparing it with the hashed password
return check_password(raw_password, self.password)
# def check_password(self, raw_password):
# # Check password by comparing it with the hashed password
# return check_password(raw_password, self.password)

class Meta:
app_label = 'user_profiles'
Expand Down
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[project]
name = "pupspot-django"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = [
"django-cors-headers>=4.6.0",
"python-jose>=3.3.0",
]
9 changes: 8 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,11 @@ pylint-django>=2.5.5

# API
djangorestframework>=3.14.0
pydantic>=2.6.1
pydantic>=2.6.1

# Auth0
auth0-python>=3.0.0
djangorestframework-simplejwt>=5.0.0
python-jose>=3.3.0
python-dotenv>=0.19.0
cyrptography>=36.0.0
127 changes: 127 additions & 0 deletions uv.lock

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