Skip to content

test: Fix failing tests for django and flask #227

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

Merged
merged 3 commits into from
Sep 19, 2022
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
7 changes: 6 additions & 1 deletion tests/auth-react/django3x/mysite/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
thirdparty,
thirdpartyemailpassword,
thirdpartypasswordless,
userroles,
)
from supertokens_python.recipe.emailpassword import EmailPasswordRecipe
from supertokens_python.recipe.emailpassword.interfaces import (
Expand Down Expand Up @@ -81,6 +82,7 @@
from supertokens_python.recipe.thirdpartypasswordless.interfaces import (
APIInterface as ThirdpartyPasswordlessAPIInterface,
)
from supertokens_python.recipe.userroles import UserRolesRecipe
from supertokens_python.types import GeneralErrorResponse
from typing_extensions import Literal

Expand Down Expand Up @@ -240,13 +242,15 @@ def custom_init(
None, Literal["USER_INPUT_CODE", "MAGIC_LINK", "USER_INPUT_CODE_AND_MAGIC_LINK"]
] = None,
):
UserRolesRecipe.reset()
PasswordlessRecipe.reset()
ThirdPartyPasswordlessRecipe.reset()
JWTRecipe.reset()
EmailVerificationRecipe.reset()
SessionRecipe.reset()
ThirdPartyRecipe.reset()
EmailPasswordRecipe.reset()
EmailVerificationRecipe.reset()
ThirdPartyEmailPasswordRecipe.reset()
Supertokens.reset()

Expand Down Expand Up @@ -849,10 +853,11 @@ async def authorisation_url_get(
)

recipe_list = [
userroles.init(),
session.init(override=session.InputOverrideConfig(apis=override_session_apis)),
emailverification.init(
mode="OPTIONAL",
create_and_send_custom_email=ev_create_and_send_custom_email, # TODO: Is it correct to create a seperate func for this?
create_and_send_custom_email=ev_create_and_send_custom_email,
override=EVInputOverrideConfig(apis=override_email_verification_apis),
),
emailpassword.init(
Expand Down
17 changes: 17 additions & 0 deletions tests/auth-react/django3x/polls/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os

from django.urls import path

from . import views
Expand All @@ -11,3 +13,18 @@
path("test/featureFlags", views.test_feature_flags, name="featureFlags"),
path("beforeeach", views.before_each, name="beforeeach"),
]

mode = os.environ.get("APP_MODE", "asgi")

if mode == "asgi":
urlpatterns += [
path("unverifyEmail", views.unverify_email_api, name="unverifyEmail"), # type: ignore
path("setRole", views.set_role_api, name="setRole"), # type: ignore
path("checkRole", views.check_role_api, name="checkRole"), # type: ignore
]
else:
urlpatterns += [
path("unverifyEmail", views.sync_unverify_email_api, name="unverifyEmail"),
path("setRole", views.sync_set_role_api, name="setRole"),
path("checkRole", views.sync_check_role_api, name="checkRole"),
]
91 changes: 90 additions & 1 deletion tests/auth-react/django3x/polls/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,52 @@
# under the License.
import json
import os
from typing import List, Dict, Any

from django.conf import settings
from django.http import HttpRequest, HttpResponse, JsonResponse
from mysite.store import get_codes, get_url_with_token
from mysite.utils import custom_init

from supertokens_python.recipe.emailverification import EmailVerificationClaim
from supertokens_python.recipe.session import SessionContainer
from supertokens_python.recipe.session.interfaces import SessionClaimValidator
from supertokens_python.recipe.userroles import UserRoleClaim, PermissionClaim

mode = os.environ.get("APP_MODE", "asgi")


async def override_global_claim_validators(
gv: List[SessionClaimValidator],
_session: SessionContainer,
user_context: Dict[str, Any],
):
validators = gv.copy()
req = user_context["_default"]["request"]
body = await req.json()

if body.get("role"):
info = body["role"]
validator = getattr(UserRoleClaim.validators, info["validator"])
validators.append(validator(*info["args"]))

if body.get("permission"):
info = body["permission"]
validator = getattr(PermissionClaim.validators, info["validator"])
validators.append(validator(*info["args"]))

return validators


if mode == "asgi":
from supertokens_python.recipe.session.framework.django.asyncio import (
verify_session,
)
from supertokens_python.recipe.userroles.asyncio import (
create_new_role_or_add_permissions,
add_role_to_user,
)
from supertokens_python.recipe.emailverification.asyncio import unverify_email

@verify_session()
async def session_info(request: HttpRequest): # type: ignore
Expand All @@ -39,8 +72,36 @@ async def session_info(request: HttpRequest): # type: ignore
}
)

@verify_session()
async def set_role_api(request: HttpRequest):
session_: SessionContainer = request.supertokens # type: ignore
body = json.loads(request.body)
await create_new_role_or_add_permissions(body["role"], body["permissions"])
await add_role_to_user(session_.get_user_id(), body["role"])
await session_.fetch_and_set_claim(UserRoleClaim)
await session_.fetch_and_set_claim(PermissionClaim)
return JsonResponse({"status": "OK"})

@verify_session()
async def unverify_email_api(request: HttpRequest):
session_: SessionContainer = request.supertokens # type: ignore
await unverify_email(session_.get_user_id())
await session_.fetch_and_set_claim(EmailVerificationClaim)
return JsonResponse({"status": "OK"})

@verify_session(override_global_claim_validators=override_global_claim_validators)
async def check_role_api(): # type: ignore
return JsonResponse({"status": "OK"})

else:
from supertokens_python.recipe.session.framework.django.syncio import verify_session
from supertokens_python.recipe.userroles.syncio import (
create_new_role_or_add_permissions as sync_create_new_role_or_add_permissions,
add_role_to_user as sync_add_role_to_user,
)
from supertokens_python.recipe.emailverification.syncio import (
unverify_email as sync_unverify_email,
)

@verify_session()
def session_info(request: HttpRequest):
Expand All @@ -54,6 +115,27 @@ def session_info(request: HttpRequest):
}
)

@verify_session()
def sync_set_role_api(request: HttpRequest):
session_: SessionContainer = request.supertokens # type: ignore
body = json.loads(request.body)
sync_create_new_role_or_add_permissions(body["role"], body["permissions"])
sync_add_role_to_user(session_.get_user_id(), body["role"])
session_.sync_fetch_and_set_claim(UserRoleClaim)
session_.sync_fetch_and_set_claim(PermissionClaim)
return JsonResponse({"status": "OK"})

@verify_session()
def sync_unverify_email_api(request: HttpRequest):
session_: SessionContainer = request.supertokens # type: ignore
sync_unverify_email(session_.get_user_id())
session_.sync_fetch_and_set_claim(EmailVerificationClaim)
return JsonResponse({"status": "OK"})

@verify_session(override_global_claim_validators=override_global_claim_validators)
def sync_check_role_api():
return JsonResponse({"status": "OK"})


def ping(request: HttpRequest):
return HttpResponse("success")
Expand Down Expand Up @@ -87,5 +169,12 @@ def before_each(request: HttpRequest):

def test_feature_flags(request: HttpRequest):
return JsonResponse(
{"available": ["passwordless", "thirdpartypasswordless", "generalerror"]}
{
"available": [
"passwordless",
"thirdpartypasswordless",
"generalerror",
"userroles",
]
}
)
74 changes: 71 additions & 3 deletions tests/auth-react/flask-server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from dotenv import load_dotenv
from flask import Flask, g, jsonify, make_response, request
from flask_cors import CORS

from supertokens_python import (
InputAppInfo,
Supertokens,
Expand All @@ -34,6 +35,7 @@
thirdparty,
thirdpartyemailpassword,
thirdpartypasswordless,
userroles,
)
from supertokens_python.recipe.emailpassword import EmailPasswordRecipe
from supertokens_python.recipe.emailpassword.interfaces import (
Expand All @@ -47,10 +49,14 @@
InputFormField,
User,
)
from supertokens_python.recipe.emailverification import EmailVerificationRecipe
from supertokens_python.recipe.emailverification import (
EmailVerificationRecipe,
EmailVerificationClaim,
)
from supertokens_python.recipe.emailverification import (
InputOverrideConfig as EVInputOverrideConfig,
)
from supertokens_python.recipe.emailverification.asyncio import unverify_email
from supertokens_python.recipe.emailverification.interfaces import (
APIInterface as EmailVerificationAPIInterface,
)
Expand All @@ -75,9 +81,10 @@
from supertokens_python.recipe.session.framework.flask import verify_session
from supertokens_python.recipe.session.interfaces import (
APIInterface as SessionAPIInterface,
SessionContainer,
SessionClaimValidator,
)
from supertokens_python.recipe.session.interfaces import APIOptions as SAPIOptions
from supertokens_python.recipe.session.interfaces import SessionContainer
from supertokens_python.recipe.thirdparty import ThirdPartyRecipe
from supertokens_python.recipe.thirdparty.interfaces import (
APIInterface as ThirdpartyAPIInterface,
Expand Down Expand Up @@ -105,6 +112,15 @@
from supertokens_python.recipe.thirdpartypasswordless.interfaces import (
APIInterface as ThirdpartyPasswordlessAPIInterface,
)
from supertokens_python.recipe.userroles import (
UserRoleClaim,
PermissionClaim,
UserRolesRecipe,
)
from supertokens_python.recipe.userroles.asyncio import (
create_new_role_or_add_permissions,
add_role_to_user,
)
from supertokens_python.types import GeneralErrorResponse
from typing_extensions import Literal

Expand Down Expand Up @@ -264,13 +280,15 @@ def custom_init(
None, Literal["USER_INPUT_CODE", "MAGIC_LINK", "USER_INPUT_CODE_AND_MAGIC_LINK"]
] = None,
):
UserRolesRecipe.reset()
PasswordlessRecipe.reset()
ThirdPartyPasswordlessRecipe.reset()
JWTRecipe.reset()
EmailVerificationRecipe.reset()
SessionRecipe.reset()
ThirdPartyRecipe.reset()
EmailPasswordRecipe.reset()
EmailVerificationRecipe.reset()
ThirdPartyEmailPasswordRecipe.reset()
Supertokens.reset()

Expand Down Expand Up @@ -893,6 +911,7 @@ async def authorisation_url_get(
)

recipe_list = [
userroles.init(),
session.init(override=session.InputOverrideConfig(apis=override_session_apis)),
emailverification.init(
mode="OPTIONAL",
Expand Down Expand Up @@ -1014,10 +1033,59 @@ def test_get_device():

@app.get("/test/featureFlags") # type: ignore
def test_feature_flags():
available = ["passwordless", "thirdpartypasswordless", "generalerror"]
available = ["passwordless", "thirdpartypasswordless", "generalerror", "userroles"]
return jsonify({"available": available})


@app.get("/unverifyEmail") # type: ignore
@verify_session()
async def unverify_email_api():
session_: SessionContainer = g.supertokens # type: ignore
await unverify_email(session_.get_user_id())
await session_.fetch_and_set_claim(EmailVerificationClaim)
return jsonify({"status": "OK"})


@app.route("/setRole", methods=["POST"]) # type: ignore
@verify_session()
async def verify_email_api():
session_: SessionContainer = g.supertokens # type: ignore
body: Dict[str, Any] = request.get_json() # type: ignore
await create_new_role_or_add_permissions(body["role"], body["permissions"])
await add_role_to_user(session_.get_user_id(), body["role"])
await session_.fetch_and_set_claim(UserRoleClaim)
await session_.fetch_and_set_claim(PermissionClaim)
return jsonify({"status": "OK"})


async def override_global_claim_validators(
gv: List[SessionClaimValidator],
_session: SessionContainer,
user_context: Dict[str, Any],
):
validators = gv.copy()
req = user_context["_default"]["request"]
body = await req.json()

if body.get("role"):
info = body["role"]
validator = getattr(UserRoleClaim.validators, info["validator"])
validators.append(validator(*info["args"]))

if body.get("permission"):
info = body["permission"]
validator = getattr(PermissionClaim.validators, info["validator"])
validators.append(validator(*info["args"]))

return validators


@app.route("/checkRole", methods=["POST"]) # type: ignore
@verify_session(override_global_claim_validators=override_global_claim_validators)
async def check_role_api():
return jsonify({"status": "OK"})


@app.route("/", defaults={"path": ""}) # type: ignore
@app.route("/<path:path>") # type: ignore
def index(_: str):
Expand Down