id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,500
|
test_google_site_verification.py
|
rafalp_Misago/misago/conf/admin/tests/test_google_site_verification.py
|
import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from ...models import Setting
admin_link = reverse("misago:admin:settings:analytics:index")
@pytest.fixture
def setting(db):
return Setting.objects.get(setting="google_site_verification")
@pytest.fixture
def setting_with_value(setting):
setting.dry_value = "asdfghjkl1234567"
setting.save()
return setting
def test_site_verification_cant_be_edited_directly(admin_client, setting):
admin_client.post(admin_link, {"google_site_verification": "test"})
setting.refresh_from_db()
assert not setting.value
def test_site_verification_is_set_from_uploaded_file(admin_client, setting):
verification = b"google-site-verification: googleasdfghjkl1234567.html"
verification_file = SimpleUploadedFile("test.html", verification, "text/html")
admin_client.post(admin_link, {"google_site_verification_file": verification_file})
setting.refresh_from_db()
assert setting.value == "asdfghjkl1234567"
def test_non_html_uploaded_file_is_rejected(admin_client, setting):
verification_file = SimpleUploadedFile("test.html", b"test", "text/plain")
admin_client.post(admin_link, {"google_site_verification_file": verification_file})
setting.refresh_from_db()
assert not setting.value
def test_empty_uploaded_file_is_rejected(admin_client, setting_with_value):
verification_file = SimpleUploadedFile("test.html", b"", "text/html")
admin_client.post(admin_link, {"google_site_verification_file": verification_file})
setting_with_value.refresh_from_db()
assert setting_with_value.value
def test_incorrect_uploaded_file_is_rejected(admin_client, setting_with_value):
verification = b"google-site-verification: google.html"
verification_file = SimpleUploadedFile("test.html", verification, "text/html")
admin_client.post(admin_link, {"google_site_verification_file": verification_file})
setting_with_value.refresh_from_db()
assert setting_with_value.value
| 2,055
|
Python
|
.py
| 39
| 48.589744
| 87
| 0.771429
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,501
|
test_blank_avatar_validation.py
|
rafalp_Misago/misago/conf/admin/tests/test_blank_avatar_validation.py
|
from io import BytesIO
import pytest
from PIL import Image
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from ... import settings
from ...models import Setting
admin_link = reverse("misago:admin:settings:users:index")
def create_image(width, height):
image = Image.new("RGBA", (width, height))
stream = BytesIO()
image.save(stream, "PNG")
stream.seek(0)
return SimpleUploadedFile("image.png", stream.read(), "image/jpeg")
def submit_image(admin_client, image=""):
data = {
"account_activation": "user",
"username_length_min": 10,
"username_length_max": 10,
"anonymous_username": "Deleted",
"avatar_upload_limit": 2000,
"default_avatar": "gravatar",
"default_gravatar_fallback": "dynamic",
"signature_length_max": 100,
"blank_avatar": image,
"subscribe_start": "no",
"subscribe_reply": "no",
"users_per_page": 12,
"users_per_page_orphans": 4,
"top_posters_ranking_length": 10,
"top_posters_ranking_size": 10,
"allow_data_downloads": "no",
"data_downloads_expiration": 48,
"allow_delete_own_account": "no",
"new_inactive_accounts_delete": 0,
"ip_storage_time": 0,
}
return admin_client.post(admin_link, data)
@pytest.fixture
def setting(db):
return Setting.objects.get(setting="blank_avatar")
@pytest.fixture
def setting_with_value(admin_client, setting):
min_size = max(settings.MISAGO_AVATARS_SIZES)
image_file = create_image(min_size, min_size)
submit_image(admin_client, image_file)
setting.refresh_from_db()
return setting
def test_uploaded_image_is_rejected_if_its_not_square(admin_client, setting):
image_file = create_image(100, 200)
submit_image(admin_client, image_file)
setting.refresh_from_db()
assert not setting.value
def test_uploaded_image_is_rejected_if_its_smaller_than_max_avatar_size(
admin_client, setting
):
min_size = max(settings.MISAGO_AVATARS_SIZES)
image_file = create_image(min_size - 1, min_size - 1)
submit_image(admin_client, image_file)
setting.refresh_from_db()
assert not setting.value
def test_valid_blank_avatar_can_be_uploaded(admin_client, setting):
min_size = max(settings.MISAGO_AVATARS_SIZES)
image_file = create_image(min_size, min_size)
submit_image(admin_client, image_file)
setting.refresh_from_db()
assert setting.value
def test_submitting_form_without_new_image_doesnt_unset_existing_image(
admin_client, setting_with_value
):
submit_image(admin_client)
setting_with_value.refresh_from_db()
assert setting_with_value.value
| 2,733
|
Python
|
.py
| 73
| 32.09589
| 77
| 0.696015
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,502
|
test_change_settings_views.py
|
rafalp_Misago/misago/conf/admin/tests/test_change_settings_views.py
|
import pytest
from django import forms
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ... import SETTINGS_CACHE
from ..forms import SettingsForm
from ..views import SettingsView
@pytest.fixture(autouse=True)
def messages_mock(mocker):
return mocker.patch("misago.conf.admin.views.messages")
class Form(SettingsForm):
settings = ["forum_name"]
forum_name = forms.CharField(max_length=255)
class View(SettingsView):
form_class = Form
def render(self, request, context):
return True
def test_view_loads_form_settings_from_db(setting):
view = View()
assert view.get_settings(["forum_name"]) == {setting.setting: setting}
def test_view_raises_value_error_if_requested_setting_is_not_found(setting):
view = View()
with pytest.raises(ValueError):
assert view.get_settings(["forum_name", "nonexisting_setting"])
def test_initial_form_data_is_build_from_settings_dict(setting):
view = View()
settings_dict = {setting.setting: setting}
assert view.get_initial_form_data(settings_dict) == {setting.setting: setting.value}
def test_view_handles_get_request(rf, setting):
view = View.as_view()
view(rf.get("/"))
def test_view_handles_post_request(rf, setting):
view = View.as_view()
view(rf.post("/", {setting.setting: "New Value"}))
def test_view_changes_setting_on_correct_post_request(rf, setting):
view = View.as_view()
view(rf.post("/", {setting.setting: "New Value"}))
setting.refresh_from_db()
assert setting.value == "New Value"
def test_view_handles_invalid_post_request(rf, setting):
view = View.as_view()
view(rf.post("/", {"invalid_setting": ""}))
setting.refresh_from_db()
assert setting.value == "Misago"
def test_view_invalidates_settings_cache_on_correct_post_request(rf, setting):
with assert_invalidates_cache(SETTINGS_CACHE):
view = View.as_view()
view(rf.post("/", {setting.setting: "New Value"}))
def test_analytics_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:analytics:index"))
assert response.status_code == 200
def test_captcha_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:captcha:index"))
assert response.status_code == 200
def test_general_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:general:index"))
assert response.status_code == 200
def test_notifications_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:notifications:index"))
assert response.status_code == 200
def test_oauth2_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:oauth2:index"))
assert response.status_code == 200
def test_threads_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:threads:index"))
assert response.status_code == 200
def test_users_settings_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:users:index"))
assert response.status_code == 200
| 3,241
|
Python
|
.py
| 69
| 42.652174
| 88
| 0.737145
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,503
|
test_change_oauth2_settings.py
|
rafalp_Misago/misago/conf/admin/tests/test_change_oauth2_settings.py
|
from django.urls import reverse
from ...models import Setting
from ....test import assert_contains, assert_has_error_message
def test_oauth2_can_be_enabled(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "1",
"oauth2_provider": "Lorem",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "0",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "avatar",
},
)
assert response.status_code == 302
settings = {row.setting: row.value for row in Setting.objects.all()}
assert settings["enable_oauth2_client"] is True
assert settings["oauth2_provider"] == "Lorem"
assert settings["oauth2_client_id"] == "id"
assert settings["oauth2_client_secret"] == "secret"
assert settings["oauth2_enable_pkce"] is False
assert settings["oauth2_pkce_code_challenge_method"] == "S256"
assert settings["oauth2_scopes"] == "some scope"
assert settings["oauth2_login_url"] == "https://example.com/login/"
assert settings["oauth2_token_url"] == "https://example.com/token/"
assert settings["oauth2_token_extra_headers"] == ""
assert settings["oauth2_json_token_path"] == "access_token"
assert settings["oauth2_user_url"] == "https://example.com/user/"
assert settings["oauth2_user_method"] == "GET"
assert settings["oauth2_user_token_location"] == "HEADER"
assert settings["oauth2_user_token_name"] == "access_token"
assert settings["oauth2_user_extra_headers"] == ""
assert settings["oauth2_send_welcome_email"] is False
assert settings["oauth2_json_id_path"] == "id"
assert settings["oauth2_json_name_path"] == "name"
assert settings["oauth2_json_email_path"] == "email"
assert settings["oauth2_json_avatar_path"] == "avatar"
def test_oauth2_can_be_enabled_without_avatar(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "1",
"oauth2_provider": "Lorem",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "0",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert response.status_code == 302
settings = {row.setting: row.value for row in Setting.objects.all()}
assert settings["enable_oauth2_client"] is True
assert settings["oauth2_provider"] == "Lorem"
assert settings["oauth2_client_id"] == "id"
assert settings["oauth2_client_secret"] == "secret"
assert settings["oauth2_enable_pkce"] is False
assert settings["oauth2_pkce_code_challenge_method"] == "S256"
assert settings["oauth2_scopes"] == "some scope"
assert settings["oauth2_login_url"] == "https://example.com/login/"
assert settings["oauth2_token_url"] == "https://example.com/token/"
assert settings["oauth2_token_extra_headers"] == ""
assert settings["oauth2_json_token_path"] == "access_token"
assert settings["oauth2_user_url"] == "https://example.com/user/"
assert settings["oauth2_user_method"] == "GET"
assert settings["oauth2_user_token_location"] == "HEADER"
assert settings["oauth2_user_token_name"] == "access_token"
assert settings["oauth2_user_extra_headers"] == ""
assert settings["oauth2_send_welcome_email"] is False
assert settings["oauth2_json_id_path"] == "id"
assert settings["oauth2_json_name_path"] == "name"
assert settings["oauth2_json_email_path"] == "email"
assert settings["oauth2_json_avatar_path"] == ""
def test_oauth2_cant_be_enabled_with_some_value_missing(admin_client):
data = {
"enable_oauth2_client": "1",
"oauth2_provider": "Lorem",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "0",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
}
skip_settings = (
"enable_oauth2_client",
"oauth2_enable_pkce",
"oauth2_pkce_code_challenge_method",
"oauth2_json_avatar_path",
"oauth2_token_extra_headers",
"oauth2_user_method",
"oauth2_user_token_location",
"oauth2_user_extra_headers",
"oauth2_send_welcome_email",
)
for setting in data:
if setting in skip_settings:
continue
new_data = data.copy()
new_data[setting] = ""
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
new_data,
)
assert response.status_code == 302
assert_has_error_message(
response,
"You need to complete the configuration before you will be able to enable OAuth 2 on your site.",
)
settings = {row.setting: row.value for row in Setting.objects.all()}
assert settings["enable_oauth2_client"] is False
if setting != "oauth2_client_id":
assert settings["oauth2_client_id"] == "id"
if setting != "oauth2_client_secret":
assert settings["oauth2_client_secret"] == "secret"
if setting != "oauth2_scopes":
assert settings["oauth2_scopes"] == "some scope"
if setting != "oauth2_login_url":
assert settings["oauth2_login_url"] == "https://example.com/login/"
if setting != "oauth2_token_url":
assert settings["oauth2_token_url"] == "https://example.com/token/"
if setting != "oauth2_json_token_path":
assert settings["oauth2_json_token_path"] == "access_token"
if setting != "oauth2_user_url":
assert settings["oauth2_user_url"] == "https://example.com/user/"
if setting != "oauth2_user_token_name":
assert settings["oauth2_user_token_name"] == "access_token"
if setting != "oauth2_json_id_path":
assert settings["oauth2_json_id_path"] == "id"
if setting != "oauth2_json_name_path":
assert settings["oauth2_json_name_path"] == "name"
if setting != "oauth2_json_email_path":
assert settings["oauth2_json_email_path"] == "email"
def test_oauth2_scopes_are_normalized(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "0",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert response.status_code == 302
setting = Setting.objects.get(setting="oauth2_scopes")
assert setting.value == "some scope"
def test_oauth2_extra_token_headers_are_normalized(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "0",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": ("Lorem: ipsum\n Dolor: Met-elit"),
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert response.status_code == 302
setting = Setting.objects.get(setting="oauth2_token_extra_headers")
assert setting.value == "Lorem: ipsum\nDolor: Met-elit"
def test_oauth2_extra_token_headers_are_validated(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": (
"Lorem: ipsum\n Dolor-amet\n Dolor: Met-elit"
),
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert_contains(response, "is not a valid header")
def test_oauth2_extra_user_headers_are_normalized(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "0",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": ("Lorem: ipsum\n Dolor: Met-amet"),
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert response.status_code == 302
setting = Setting.objects.get(setting="oauth2_user_extra_headers")
assert setting.value == "Lorem: ipsum\nDolor: Met-amet"
def test_oauth2_extra_user_headers_are_validated(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": ("Lorem: ipsum\n Dolor-met"),
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert_contains(response, "is not a valid header")
def test_oauth2_extra_headers_are_validated_to_have_colons(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": ("Lorem: ipsum\n Dolor-met"),
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert_contains(response, "is not a valid header. It's missing a colon")
def test_oauth2_extra_headers_are_validated_to_have_names(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": ("Lorem: ipsum\n :Dolor-met"),
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert_contains(
response,
"is not a valid header. It's missing a header name before the colon",
)
def test_oauth2_extra_headers_are_validated_to_have_values(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": ("Lorem: ipsum\n Dolor-met:"),
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert_contains(
response,
"is not a valid header. It's missing a header value after the colon",
)
def test_oauth2_extra_headers_are_validated_to_be_unique(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "0",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_scopes": "some some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": ("Accept:b\nLorem: ipsum\n Accept: a"),
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "",
},
)
assert_contains(response, ""Accept" header is entered more than once.")
def test_oauth2_can_be_enabled_with_pkce(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:oauth2:index"),
{
"enable_oauth2_client": "1",
"oauth2_provider": "Lorem",
"oauth2_client_id": "id",
"oauth2_client_secret": "secret",
"oauth2_enable_pkce": "1",
"oauth2_pkce_code_challenge_method": "S256",
"oauth2_scopes": "some scope",
"oauth2_login_url": "https://example.com/login/",
"oauth2_token_url": "https://example.com/token/",
"oauth2_token_extra_headers": "",
"oauth2_json_token_path": "access_token",
"oauth2_user_url": "https://example.com/user/",
"oauth2_user_method": "GET",
"oauth2_user_token_location": "HEADER",
"oauth2_user_token_name": "access_token",
"oauth2_user_extra_headers": "",
"oauth2_send_welcome_email": "",
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "name",
"oauth2_json_email_path": "email",
"oauth2_json_avatar_path": "avatar",
},
)
assert response.status_code == 302
settings = {row.setting: row.value for row in Setting.objects.all()}
assert settings["enable_oauth2_client"] is True
assert settings["oauth2_provider"] == "Lorem"
assert settings["oauth2_client_id"] == "id"
assert settings["oauth2_client_secret"] == "secret"
assert settings["oauth2_enable_pkce"] is True
assert settings["oauth2_pkce_code_challenge_method"] == "S256"
assert settings["oauth2_scopes"] == "some scope"
assert settings["oauth2_login_url"] == "https://example.com/login/"
assert settings["oauth2_token_url"] == "https://example.com/token/"
assert settings["oauth2_token_extra_headers"] == ""
assert settings["oauth2_json_token_path"] == "access_token"
assert settings["oauth2_user_url"] == "https://example.com/user/"
assert settings["oauth2_user_method"] == "GET"
assert settings["oauth2_user_token_location"] == "HEADER"
assert settings["oauth2_user_token_name"] == "access_token"
assert settings["oauth2_user_extra_headers"] == ""
assert settings["oauth2_send_welcome_email"] is False
assert settings["oauth2_json_id_path"] == "id"
assert settings["oauth2_json_name_path"] == "name"
assert settings["oauth2_json_email_path"] == "email"
assert settings["oauth2_json_avatar_path"] == "avatar"
| 22,013
|
Python
|
.py
| 470
| 36.829787
| 109
| 0.582876
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,504
|
models.py
|
rafalp_Misago/misago/oauth2/models.py
|
from django.db import models
from django.utils import timezone
from ..conf import settings
class Subject(models.Model):
sub = models.CharField(max_length=36, primary_key=True) # UUID4 str length
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_on = models.DateTimeField(default=timezone.now)
last_used_on = models.DateTimeField(default=timezone.now)
| 406
|
Python
|
.py
| 8
| 47.375
| 80
| 0.78481
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,505
|
client.py
|
rafalp_Misago/misago/oauth2/client.py
|
from base64 import urlsafe_b64encode
from hashlib import sha256
from secrets import token_urlsafe
from typing import Any
from urllib.parse import urlencode
import requests
from django.urls import reverse
from django.utils.crypto import get_random_string
from requests.exceptions import RequestException
from . import exceptions
SESSION_STATE = "oauth2_state"
STATE_LENGTH = 40
REQUESTS_TIMEOUT = 30
SESSION_CODE_VERIFIER = "oauth2_code_verifier"
def create_login_url(request):
state = get_random_string(STATE_LENGTH)
request.session[SESSION_STATE] = state
querystring = {
"response_type": "code",
"client_id": request.settings.oauth2_client_id,
"redirect_uri": get_redirect_uri(request),
"scope": request.settings.oauth2_scopes,
"state": state,
}
if request.settings.oauth2_enable_pkce:
code_verifier = token_urlsafe()
request.session[SESSION_CODE_VERIFIER] = code_verifier
querystring["code_challenge"] = get_code_challenge(
code_verifier, request.settings.oauth2_pkce_code_challenge_method
)
querystring["code_challenge_method"] = (
request.settings.oauth2_pkce_code_challenge_method
)
return "%s?%s" % (request.settings.oauth2_login_url, urlencode(querystring))
def get_code_grant(request):
session_state = request.session.pop(SESSION_STATE, None)
if request.GET.get("error") == "access_denied":
raise exceptions.OAuth2AccessDeniedError()
if not session_state:
raise exceptions.OAuth2StateNotSetError()
provider_state = request.GET.get("state")
if not provider_state:
raise exceptions.OAuth2StateNotProvidedError()
if provider_state != session_state:
raise exceptions.OAuth2StateMismatchError()
code_grant = request.GET.get("code")
if not code_grant:
raise exceptions.OAuth2CodeNotProvidedError()
return code_grant
def get_access_token(request, code_grant):
token_url = request.settings.oauth2_token_url
data = {
"grant_type": "authorization_code",
"client_id": request.settings.oauth2_client_id,
"client_secret": request.settings.oauth2_client_secret,
"redirect_uri": get_redirect_uri(request),
"code": code_grant,
}
if request.settings.oauth2_enable_pkce:
data["code_verifier"] = request.session.pop(SESSION_CODE_VERIFIER, None)
headers = get_headers_dict(request.settings.oauth2_token_extra_headers)
try:
r = requests.post(
token_url,
data=data,
headers=headers,
timeout=REQUESTS_TIMEOUT,
)
except RequestException:
raise exceptions.OAuth2AccessTokenRequestError()
if r.status_code != 200:
raise exceptions.OAuth2AccessTokenResponseError()
try:
response_json = r.json()
if not isinstance(response_json, dict):
raise TypeError()
except (ValueError, TypeError):
raise exceptions.OAuth2AccessTokenJSONError()
access_token = get_value_from_json(
request.settings.oauth2_json_token_path,
response_json,
)
if not access_token:
raise exceptions.OAuth2AccessTokenNotProvidedError()
return access_token
JSON_MAPPING = {
"id": "oauth2_json_id_path",
"name": "oauth2_json_name_path",
"email": "oauth2_json_email_path",
"avatar": "oauth2_json_avatar_path",
}
def get_user_data(request, access_token):
headers = get_headers_dict(request.settings.oauth2_user_extra_headers)
user_url = request.settings.oauth2_user_url
if request.settings.oauth2_user_token_location == "QUERY":
user_url += "&" if "?" in user_url else "?"
user_url += urlencode({request.settings.oauth2_user_token_name: access_token})
elif request.settings.oauth2_user_token_location == "HEADER_BEARER":
headers[request.settings.oauth2_user_token_name] = f"Bearer {access_token}"
else:
headers[request.settings.oauth2_user_token_name] = access_token
try:
if request.settings.oauth2_user_method == "GET":
r = requests.get(user_url, headers=headers, timeout=REQUESTS_TIMEOUT)
else:
r = requests.post(user_url, headers=headers, timeout=REQUESTS_TIMEOUT)
except RequestException:
raise exceptions.OAuth2UserDataRequestError()
if r.status_code != 200:
raise exceptions.OAuth2UserDataResponseError()
try:
response_json = r.json()
if not isinstance(response_json, dict):
raise TypeError()
except (ValueError, TypeError):
raise exceptions.OAuth2UserDataJSONError()
user_data = {
key: get_value_from_json(getattr(request.settings, setting), response_json)
for key, setting in JSON_MAPPING.items()
}
return user_data, response_json
def get_redirect_uri(request):
return request.build_absolute_uri(reverse("misago:oauth2-complete"))
def get_headers_dict(headers_str):
headers = {}
if not headers_str:
return headers
for header in headers_str.splitlines():
header = header.strip()
if ":" not in header:
continue
header_name, header_value = [part.strip() for part in header.split(":", 1)]
if header_name and header_value:
headers[header_name] = header_value
return headers
def get_value_from_json(path, json):
if not path:
return None
if "." not in path:
return clear_json_value(json.get(path))
data = json
for path_part in path.split("."):
if not isinstance(data, dict):
return None
data = data.get(path_part)
if data is None:
return None
return clear_json_value(data)
def clear_json_value(value: Any) -> str | None:
if isinstance(value, str):
return value.strip() or None
if isinstance(value, int) and value is not True and value is not False:
return str(value)
return None
def get_code_challenge(code_verifier: str, code_challenge_method: str) -> str:
if not code_verifier:
raise exceptions.OAuth2CodeVerifierNotProvidedError()
if code_challenge_method == "plain":
return code_verifier
elif code_challenge_method == "S256":
return (
urlsafe_b64encode(sha256(code_verifier.encode("ascii")).digest())
.decode("ascii")
.rstrip("=")
)
raise exceptions.OAuth2NotSupportedHashMethodError()
| 6,530
|
Python
|
.py
| 166
| 32.319277
| 86
| 0.679822
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,506
|
user.py
|
rafalp_Misago/misago/oauth2/user.py
|
from django.contrib.auth import get_user_model
from django.db import IntegrityError, transaction
from django.utils import timezone
from django.utils.translation import pgettext_lazy
from ..users.setupnewuser import setup_new_user
from .exceptions import OAuth2UserDataValidationError, OAuth2UserIdNotProvidedError
from .models import Subject
from .validation import validate_user_data
User = get_user_model()
def get_user_from_data(request, user_data, user_data_raw):
if not user_data["id"]:
raise OAuth2UserIdNotProvidedError()
user = get_user_by_subject(user_data["id"])
if not user and user_data["email"]:
user = get_user_by_email(user_data["id"], user_data["email"])
created = not bool(user)
cleaned_data = validate_user_data(request, user, user_data, user_data_raw)
try:
with transaction.atomic():
if not user:
user = create_new_user(request, cleaned_data)
else:
update_existing_user(user, cleaned_data)
except IntegrityError as error:
raise_validation_error_from_integrity_error(error)
return user, created
def get_user_by_subject(user_id):
try:
subject = Subject.objects.select_related("user", "user__ban_cache").get(
sub=user_id
)
subject.last_used_on = timezone.now()
subject.save(update_fields=["last_used_on"])
return subject.user
except Subject.DoesNotExist:
return None
def get_user_by_email(user_id, user_email):
try:
user = User.objects.get_by_email(user_email)
Subject.objects.create(sub=user_id, user=user)
except User.DoesNotExist:
return None
def create_new_user(request, user_data):
activation_kwargs = {}
if request.settings.account_activation == "admin":
activation_kwargs = {"requires_activation": User.ACTIVATION_ADMIN}
user = User.objects.create_user(
user_data["name"],
user_data["email"],
joined_from_ip=request.user_ip,
**activation_kwargs,
)
setup_new_user(request.settings, user, avatar_url=user_data["avatar"])
Subject.objects.create(sub=user_data["id"], user=user)
return user
def update_existing_user(user, user_data):
save_changes = False
if user.username != user_data["name"]:
user.set_username(user_data["name"])
save_changes = True
if user.email != user_data["email"]:
user.set_email(user_data["email"])
save_changes = True
if save_changes:
user.save()
def raise_validation_error_from_integrity_error(error):
error_str = str(error)
if "misago_users_user_email_hash_key" in error_str:
raise OAuth2UserDataValidationError(
error_list=[
pgettext_lazy(
"oauth2 error",
"Your e-mail address returned by the provider is not available for use on this site.",
)
]
)
if "misago_users_user_slug_key" in error_str:
raise OAuth2UserDataValidationError(
error_list=[
pgettext_lazy(
"oauth2 error",
"Your username returned by the provider is not available for use on this site.",
)
]
)
| 3,316
|
Python
|
.py
| 85
| 30.870588
| 106
| 0.64794
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,507
|
urls.py
|
rafalp_Misago/misago/oauth2/urls.py
|
from django.urls import path
from .views import oauth2_login, oauth2_complete
urlpatterns = [
path("oauth2/login/", oauth2_login, name="oauth2-login"),
path("oauth2/complete/", oauth2_complete, name="oauth2-complete"),
]
| 231
|
Python
|
.py
| 6
| 35.833333
| 70
| 0.744395
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,508
|
apps.py
|
rafalp_Misago/misago/oauth2/apps.py
|
from django.apps import AppConfig
class MisagoOAuthConfig(AppConfig):
name = "misago.oauth2"
label = "misago_oauth2"
verbose_name = "Misago OAuth2"
| 162
|
Python
|
.py
| 5
| 28.6
| 35
| 0.748387
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,509
|
validation.py
|
rafalp_Misago/misago/oauth2/validation.py
|
from dataclasses import dataclass
from django.contrib.auth import get_user_model
from django.forms import ValidationError
from django.utils.crypto import get_random_string
from unidecode import unidecode
from ..users.validators import (
dj_validate_email,
validate_username_content,
validate_username_length,
)
from .exceptions import OAuth2UserDataValidationError
from .hooks import filter_user_data_hook, validate_user_data_hook
User = get_user_model()
class UsernameSettings:
username_length_max: int = 200
username_length_min: int = 1
def validate_user_data(request, user, user_data, response_json):
try:
return validate_user_data_hook(
validate_user_data_action,
request,
user,
user_data,
response_json,
)
except ValidationError as exc:
raise OAuth2UserDataValidationError(error_list=[str(exc.message)])
def validate_user_data_action(request, user, user_data, response_json):
filtered_data = filter_user_data(request, user, user_data)
validate_username_content(filtered_data["name"])
validate_username_length(UsernameSettings, filtered_data["name"])
dj_validate_email(filtered_data["email"])
return filtered_data
def filter_user_data(request, user, user_data):
return filter_user_data_hook(filter_user_data_action, request, user, user_data)
def filter_user_data_action(request, user, user_data):
return {
"id": user_data["id"],
"name": filter_name(user, user_data["name"] or ""),
"email": user_data["email"] or "",
"avatar": user_data["avatar"],
}
def filter_user_data_with_filters(request, user, user_data, filters):
for filter_user_data in filters:
user_data = filter_user_data(request, user, user_data.copy()) or user_data
return user_data
def filter_name(user, name):
if user and user.username == name:
return name
clean_name = "".join(
[c for c in unidecode(name.replace(" ", "_")) if c.isalnum() or c == "_"]
)
if user and user.username == clean_name:
return clean_name # No change in name
if not clean_name.replace("_", ""):
clean_name = "User_%s" % get_random_string(4)
clean_name_root = clean_name
while True:
try:
db_user = User.objects.get_by_username(clean_name)
except User.DoesNotExist:
return clean_name
if not user or user.pk != db_user.pk:
clean_name = f"{clean_name_root}_{get_random_string(4)}"
else:
return clean_name
| 2,598
|
Python
|
.py
| 66
| 33
| 83
| 0.674502
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,510
|
exceptions.py
|
rafalp_Misago/misago/oauth2/exceptions.py
|
from django.utils.translation import pgettext_lazy
class OAuth2Error(Exception):
pass
class OAuth2ProviderError(OAuth2Error):
pass
class OAuth2AccessDeniedError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error", "The OAuth2 process was canceled by the provider."
)
class OAuth2StateError(OAuth2Error):
recoverable = True
class OAuth2StateNotSetError(OAuth2StateError):
message = pgettext_lazy("oauth2 error", "The OAuth2 session is missing state.")
class OAuth2StateNotProvidedError(OAuth2StateError):
message = pgettext_lazy(
"oauth2 error", "The OAuth2 state was not sent by the provider."
)
class OAuth2StateMismatchError(OAuth2StateError):
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 state sent by the provider did not match one in the session.",
)
class OAuth2CodeError(OAuth2Error):
recoverable = True
class OAuth2CodeNotProvidedError(OAuth2CodeError):
message = pgettext_lazy(
"oauth2 error", "The OAuth2 authorization code was not sent by the provider."
)
class OAuth2ProviderError(OAuth2Error):
recoverable = True
class OAuth2AccessTokenRequestError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"Failed to connect to the OAuth2 provider to retrieve an access token.",
)
class OAuth2AccessTokenResponseError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 provider responded with error for an access token request.",
)
class OAuth2AccessTokenJSONError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 provider did not respond with a valid JSON for an access token request.",
)
class OAuth2AccessTokenNotProvidedError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"JSON sent by the OAuth2 provider did not contain an access token.",
)
class OAuth2UserDataRequestError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"Failed to connect to the OAuth2 provider to retrieve user profile.",
)
class OAuth2UserDataResponseError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 provider responded with error for user profile request.",
)
class OAuth2UserDataJSONError(OAuth2ProviderError):
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 provider did not respond with a valid JSON for user profile request.",
)
class OAuth2UserIdNotProvidedError(OAuth2Error):
message = pgettext_lazy(
"oauth2 error", "JSON sent by the OAuth2 provider did not contain a user ID."
)
class OAuth2UserAccountDeactivatedError(OAuth2Error):
recoverable = False
message = pgettext_lazy(
"oauth2 error",
"User account associated with the profile from the OAuth2 provider was deactivated by the site administrator.",
)
class OAuth2UserDataValidationError(OAuth2ProviderError):
recoverable = False
error_list: list[str]
message = pgettext_lazy(
"oauth2 error",
"User profile retrieved from the OAuth2 provider did not validate.",
)
def __init__(self, error_list: list[str]):
self.error_list = error_list
class OAuth2CodeVerifierNotProvidedError(OAuth2Error):
recoverable = False
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 authorization flow is missing code verifier.",
)
class OAuth2NotSupportedHashMethodError(OAuth2Error):
recoverable = False
message = pgettext_lazy(
"oauth2 error",
"The OAuth2 code challenge hash method is not supported.",
)
| 3,739
|
Python
|
.py
| 96
| 33.229167
| 119
| 0.734019
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,511
|
views.py
|
rafalp_Misago/misago/oauth2/views.py
|
from functools import wraps
from logging import getLogger
from django.contrib.auth import get_user_model, login
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.decorators.cache import never_cache
from ..core.exceptions import Banned
from ..users.bans import get_user_ban
from ..users.decorators import deny_banned_ips
from ..users.registration import send_welcome_email
from .client import (
create_login_url,
get_access_token,
get_code_grant,
get_user_data,
)
from .exceptions import (
OAuth2Error,
OAuth2UserAccountDeactivatedError,
OAuth2UserDataValidationError,
)
from .user import get_user_from_data
logger = getLogger("misago.oauth2")
User = get_user_model()
def oauth2_view(f):
f = deny_banned_ips(f)
@wraps(f)
@never_cache
def wrapped_oauth2_view(request):
if not request.settings.enable_oauth2_client:
raise Http404()
return f(request)
return wrapped_oauth2_view
@oauth2_view
def oauth2_login(request):
redirect_to = create_login_url(request)
return redirect(redirect_to)
@oauth2_view
def oauth2_complete(request):
try:
code_grant = get_code_grant(request)
token = get_access_token(request, code_grant)
user_data, response_json = get_user_data(request, token)
user, created = get_user_from_data(request, user_data, response_json)
if not user.is_active:
raise OAuth2UserAccountDeactivatedError()
if not user.is_misago_admin:
if user_ban := get_user_ban(user, request.cache_versions):
raise Banned(user_ban)
except OAuth2UserDataValidationError as error:
logger.exception(
"OAuth2 Profile Error",
extra={
f"error[{error_index}]": str(error_msg)
for error_index, error_msg in enumerate(error.error_list)
},
)
return render(
request,
"misago/errorpages/oauth2_profile.html",
{
"error": error,
"error_list": error.error_list,
},
status=400,
)
except OAuth2Error as error:
logger.exception("OAuth2 Error")
return render(
request,
"misago/errorpages/oauth2.html",
{"error": error},
status=400,
)
if created and request.settings.oauth2_send_welcome_email:
send_welcome_email(request, user)
if not user.requires_activation:
login(request, user)
return redirect(reverse("misago:index"))
| 2,660
|
Python
|
.py
| 80
| 26.075
| 77
| 0.661983
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,512
|
0002_copy_sso_subjects.py
|
rafalp_Misago/misago/oauth2/migrations/0002_copy_sso_subjects.py
|
# Generated by Django 3.2.15 on 2023-01-04 12:36
from django.db import migrations
from django.utils import timezone
CHUNK_SIZE = 50
def create_settings(apps, _):
Subject = apps.get_model("misago_oauth2", "Subject")
User = apps.get_model("misago_users", "User")
tz_now = timezone.now()
sso_users = User.objects.filter(sso_id__isnull=False)
batch = []
for user in sso_users.iterator(chunk_size=CHUNK_SIZE):
batch.append(
Subject(
sub=str(user.sso_id),
user=user,
created_on=tz_now,
last_used_on=tz_now,
)
)
if len(batch) >= CHUNK_SIZE:
Subject.objects.bulk_create(batch)
batch = []
if batch:
Subject.objects.bulk_create(batch)
class Migration(migrations.Migration):
dependencies = [
("misago_oauth2", "0001_initial"),
("misago_users", "0022_deleteduser"),
]
operations = [migrations.RunPython(create_settings)]
| 1,021
|
Python
|
.py
| 30
| 25.966667
| 58
| 0.606742
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,513
|
0001_initial.py
|
rafalp_Misago/misago/oauth2/migrations/0001_initial.py
|
# Generated by Django 3.2.15 on 2023-01-04 12:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Subject",
fields=[
(
"sub",
models.CharField(max_length=36, primary_key=True, serialize=False),
),
("created_on", models.DateTimeField(default=django.utils.timezone.now)),
(
"last_used_on",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| 1,114
|
Python
|
.py
| 33
| 21.090909
| 88
| 0.516729
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,514
|
conftest.py
|
rafalp_Misago/misago/oauth2/tests/conftest.py
|
from unittest.mock import patch
import pytest
def noop_filter_user_data(request, user, user_data):
return user_data
@pytest.fixture
def disable_user_data_filters():
with patch("misago.oauth2.validation.filter_user_data", noop_filter_user_data):
yield
| 272
|
Python
|
.py
| 8
| 30.375
| 83
| 0.76834
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,515
|
test_default_user_name_filter.py
|
rafalp_Misago/misago/oauth2/tests/test_default_user_name_filter.py
|
from ..validation import filter_name
def test_filter_replaces_spaces_with_underscores(db):
assert filter_name(None, "John Doe") == "John_Doe"
def test_filter_strips_special_characters(db):
assert filter_name(None, "John Doe!") == "John_Doe"
def test_filter_strips_unicode_strings(db):
assert filter_name(None, "Łóżąć Bęś") == "Lozac_Bes"
def test_filter_generates_random_name_to_avoid_empty_result(db):
user_name = filter_name(None, "__!!!")
assert user_name
assert len(user_name) > 5
assert user_name.startswith("User_")
def test_filter_generates_unique_name_to_avoid_same_names(user):
user_name = filter_name(None, user.username)
assert user_name
assert user_name != user.username
assert user_name.startswith(user.username)
def test_filter_keeps_user_name_if_its_same_as_current_one(user):
user_name = filter_name(user, user.username)
assert user_name == user.username
def test_filter_keeps_cleaned_user_name_if_its_same_as_current_one(user):
user.set_username("Lozac_Bes")
user.save()
user_name = filter_name(user, "Łóżąć Bęś")
assert user_name == user.username
| 1,163
|
Python
|
.py
| 25
| 41.6
| 73
| 0.724729
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,516
|
test_getting_json_values.py
|
rafalp_Misago/misago/oauth2/tests/test_getting_json_values.py
|
from ..client import get_value_from_json
def test_json_str_value_is_returned():
assert get_value_from_json("val", {"val": "ok", "val2": "nope"}) == "ok"
def test_json_str_value_has_stripped_whitespace():
assert get_value_from_json("val", {"val": " ok ", "val2": "nope"}) == "ok"
def test_json_int_value_is_cast_to_str():
assert get_value_from_json("val", {"val": 21, "val2": "nope"}) == "21"
def test_none_is_returned_if_val_is_not_found():
assert get_value_from_json("val", {"val3": 21, "val2": "nope"}) is None
def test_none_is_returned_if_val_is_null():
assert get_value_from_json("val", {"val": None, "val2": "nope"}) is None
def test_json_value_is_returned_from_nested_object():
assert (
get_value_from_json(
"val.child.val",
{
"val2": "nope",
"val": {
"child": {
"val2": "nope",
"val": "ok",
},
},
},
)
== "ok"
)
def test_none_is_returned_from_nested_object_missing_value():
assert (
get_value_from_json(
"val.child.val3",
{
"val2": "nope",
"val": {
"child": {
"val2": "nope",
"val": "ok",
},
},
},
)
is None
)
def test_json_value_returned_from_nested_object_is_str():
assert (
get_value_from_json(
"val.child.val",
{
"val2": "nope",
"val": {
"child": {
"val2": "nope",
"val": 21,
},
},
},
)
== "21"
)
def test_none_is_returned_from_nested_object_missing_path_item():
assert (
get_value_from_json(
"val.missing.val",
{
"val2": "nope",
"val": {
"child": {
"val2": "nope",
"val": 21,
},
},
},
)
is None
)
def test_none_is_returned_from_nested_path_item_not_being_dict():
assert (
get_value_from_json(
"val.child.val",
{
"val2": "nope",
"val": {
"child": "nope",
},
},
)
is None
)
| 2,578
|
Python
|
.py
| 88
| 17.022727
| 80
| 0.394737
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,517
|
test_get_code_grant.py
|
rafalp_Misago/misago/oauth2/tests/test_get_code_grant.py
|
from unittest.mock import Mock
import pytest
from .. import exceptions
from ..client import SESSION_STATE, get_code_grant
def test_code_grant_is_returned_from_request():
state = "l0r3m1p5um"
code_grant = "valid-code"
request = Mock(
GET={
"state": state,
"code": code_grant,
},
session={SESSION_STATE: state},
)
assert get_code_grant(request) == code_grant
# State was removed from session
assert SESSION_STATE not in request.session
def test_exception_is_raised_if_provider_returned_error():
request = Mock(
GET={"error": "access_denied"},
session={},
)
with pytest.raises(exceptions.OAuth2AccessDeniedError):
get_code_grant(request)
# State was removed from session
assert SESSION_STATE not in request.session
def test_exception_is_raised_if_session_is_missing_state():
state = "l0r3m1p5um"
code_grant = "valid-code"
request = Mock(
GET={
"state": state,
"code": code_grant,
},
session={},
)
with pytest.raises(exceptions.OAuth2StateNotSetError):
get_code_grant(request)
def test_exception_is_raised_if_request_is_missing_state():
state = "l0r3m1p5um"
code_grant = "valid-code"
request = Mock(
GET={
"code": code_grant,
},
session={SESSION_STATE: state},
)
with pytest.raises(exceptions.OAuth2StateNotProvidedError):
get_code_grant(request)
# State was removed from session
assert SESSION_STATE not in request.session
def test_exception_is_raised_if_request_state_is_empty():
state = "l0r3m1p5um"
code_grant = "valid-code"
request = Mock(
GET={
"state": "",
"code": code_grant,
},
session={SESSION_STATE: state},
)
with pytest.raises(exceptions.OAuth2StateNotProvidedError):
get_code_grant(request)
# State was removed from session
assert SESSION_STATE not in request.session
def test_exception_is_raised_if_session_state_doesnt_match_with_request():
state = "l0r3m1p5um"
code_grant = "valid-code"
request = Mock(
GET={
"state": "invalid",
"code": code_grant,
},
session={SESSION_STATE: state},
)
with pytest.raises(exceptions.OAuth2StateMismatchError):
get_code_grant(request)
# State was removed from session
assert SESSION_STATE not in request.session
def test_exception_is_raised_if_request_is_missing_code_grant():
state = "l0r3m1p5um"
request = Mock(
GET={
"state": state,
},
session={SESSION_STATE: state},
)
with pytest.raises(exceptions.OAuth2CodeNotProvidedError):
get_code_grant(request)
# State was removed from session
assert SESSION_STATE not in request.session
def test_exception_is_raised_if_request_code_grant_is_empty():
state = "l0r3m1p5um"
request = Mock(
GET={
"code": "",
"state": state,
},
session={SESSION_STATE: state},
)
with pytest.raises(exceptions.OAuth2CodeNotProvidedError):
get_code_grant(request)
# State was removed from session
assert SESSION_STATE not in request.session
| 3,333
|
Python
|
.py
| 104
| 25.048077
| 74
| 0.644089
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,518
|
test_get_access_token.py
|
rafalp_Misago/misago/oauth2/tests/test_get_access_token.py
|
from unittest.mock import Mock, patch
import pytest
from requests.exceptions import Timeout
from ...conf.test import override_dynamic_settings
from .. import exceptions
from ..client import (
REQUESTS_TIMEOUT,
SESSION_CODE_VERIFIER,
get_access_token,
)
ACCESS_TOKEN = "acc3ss-t0k3n"
CODE_GRANT = "valid-code"
@pytest.fixture
def mock_request(dynamic_settings):
return Mock(
settings=dynamic_settings,
build_absolute_uri=lambda url: f"http://mysite.com{url or ''}",
)
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
)
def test_access_token_is_retrieved_using_post_request(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value={
"access_token": ACCESS_TOKEN,
},
),
),
)
with patch("requests.post", post_mock):
assert get_access_token(mock_request, CODE_GRANT) == ACCESS_TOKEN
post_mock.assert_called_once_with(
"https://example.com/oauth2/token",
data={
"grant_type": "authorization_code",
"client_id": "clientid123",
"client_secret": "secr3t",
"redirect_uri": "http://mysite.com/oauth2/complete/",
"code": CODE_GRANT,
},
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
oauth2_token_extra_headers="Accept: application/json\nApi-Ver:1234",
)
def test_access_token_is_retrieved_using_extra_headers(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value={
"access_token": ACCESS_TOKEN,
},
),
),
)
with patch("requests.post", post_mock):
assert get_access_token(mock_request, CODE_GRANT) == ACCESS_TOKEN
post_mock.assert_called_once_with(
"https://example.com/oauth2/token",
data={
"grant_type": "authorization_code",
"client_id": "clientid123",
"client_secret": "secr3t",
"redirect_uri": "http://mysite.com/oauth2/complete/",
"code": CODE_GRANT,
},
headers={
"Accept": "application/json",
"Api-Ver": "1234",
},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
oauth2_json_token_path="data.auth.token",
)
def test_access_token_is_extracted_from_json(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value={
"data": {
"auth": {
"token": ACCESS_TOKEN,
},
},
},
),
),
)
with patch("requests.post", post_mock):
assert get_access_token(mock_request, CODE_GRANT) == ACCESS_TOKEN
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
)
def test_exception_is_raised_if_access_token_request_times_out(mock_request):
post_mock = Mock(side_effect=Timeout())
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2AccessTokenRequestError):
get_access_token(mock_request, CODE_GRANT)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
)
def test_exception_is_raised_if_access_token_request_response_is_not_200(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=400,
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2AccessTokenResponseError):
get_access_token(mock_request, CODE_GRANT)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
)
def test_exception_is_raised_if_access_token_request_response_is_not_json(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
side_effect=ValueError(),
),
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2AccessTokenJSONError):
get_access_token(mock_request, CODE_GRANT)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
)
def test_exception_is_raised_if_access_token_request_response_json_is_not_object(
mock_request,
):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=["json", "list"],
),
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2AccessTokenJSONError):
get_access_token(mock_request, CODE_GRANT)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
)
def test_exception_is_raised_if_access_token_request_response_json_misses_token(
mock_request,
):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value={
"no_token": "nope",
},
),
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2AccessTokenNotProvidedError):
get_access_token(mock_request, CODE_GRANT)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_client_id="clientid123",
oauth2_client_secret="secr3t",
oauth2_token_url="https://example.com/oauth2/token",
oauth2_enable_pkce=True,
)
def test_access_token_is_retrieved_using_post_request_with_pkce_enabled(mock_request):
code_verifier = "KUnVU1"
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value={
"access_token": ACCESS_TOKEN,
},
),
),
)
mock_request.session = {SESSION_CODE_VERIFIER: code_verifier}
with patch("requests.post", post_mock):
assert get_access_token(mock_request, CODE_GRANT) == ACCESS_TOKEN
post_mock.assert_called_once_with(
"https://example.com/oauth2/token",
data={
"grant_type": "authorization_code",
"client_id": "clientid123",
"client_secret": "secr3t",
"redirect_uri": "http://mysite.com/oauth2/complete/",
"code": CODE_GRANT,
"code_verifier": code_verifier,
},
headers={},
timeout=REQUESTS_TIMEOUT,
)
# code verifier was removed from session
assert SESSION_CODE_VERIFIER not in mock_request.session
| 7,851
|
Python
|
.py
| 228
| 25.447368
| 88
| 0.597468
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,519
|
test_get_code_challenge.py
|
rafalp_Misago/misago/oauth2/tests/test_get_code_challenge.py
|
import pytest
from .. import exceptions
from ..client import get_code_challenge
def test_exception_is_raised_if_code_verifier_is_not_provided():
with pytest.raises(exceptions.OAuth2CodeVerifierNotProvidedError):
get_code_challenge(None, "S256")
with pytest.raises(exceptions.OAuth2CodeVerifierNotProvidedError):
get_code_challenge("", "S256")
def test_exception_is_raised_if_code_challenge_method_is_not_supported():
with pytest.raises(exceptions.OAuth2NotSupportedHashMethodError):
get_code_challenge("hYfgN", "ABC")
def test_code_challenge_is_returned_using_S256_hash_method():
code_verifier = "hYfgNABC"
code_challenge = "E5AZUNDQx0-aVDeEVgNFTEglcG1bWgOuygG_elkz_io"
assert get_code_challenge(code_verifier, "S256") == code_challenge
def test_code_challenge_is_returned_using_plain_hash_method():
code_verifier = "hYfgNABC"
assert get_code_challenge(code_verifier, "plain") == code_verifier
| 960
|
Python
|
.py
| 18
| 48.666667
| 73
| 0.767167
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,520
|
test_get_user_data.py
|
rafalp_Misago/misago/oauth2/tests/test_get_user_data.py
|
from unittest.mock import Mock, patch
import pytest
from requests.exceptions import Timeout
from ...conf.test import override_dynamic_settings
from .. import exceptions
from ..client import REQUESTS_TIMEOUT, get_user_data
ACCESS_TOKEN = "acc3ss-t0k3n"
@pytest.fixture
def mock_request(dynamic_settings):
return Mock(settings=dynamic_settings)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="GET",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_get_request_with_token_in_query_string(
mock_request,
):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/user?atoken={ACCESS_TOKEN}",
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="GET",
oauth2_user_token_name="Authentication",
oauth2_user_token_location="HEADER",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_get_request_with_token_in_header(mock_request):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/user",
headers={"Authentication": ACCESS_TOKEN},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="GET",
oauth2_user_token_name="Authentication",
oauth2_user_token_location="HEADER_BEARER",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_get_request_with_bearer_token_in_header(
mock_request,
):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/user",
headers={"Authentication": f"Bearer {ACCESS_TOKEN}"},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="POST",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_post_request_with_token_in_query_string(
mock_request,
):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.post", post_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
post_mock.assert_called_once_with(
f"https://example.com/oauth2/user?atoken={ACCESS_TOKEN}",
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="POST",
oauth2_user_token_name="Authentication",
oauth2_user_token_location="HEADER",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_post_request_with_token_in_header(mock_request):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.post", post_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
post_mock.assert_called_once_with(
f"https://example.com/oauth2/user",
headers={"Authentication": ACCESS_TOKEN},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="POST",
oauth2_user_token_name="Authentication",
oauth2_user_token_location="HEADER_BEARER",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_post_request_with_bearer_token_in_header(
mock_request,
):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.post", post_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
post_mock.assert_called_once_with(
f"https://example.com/oauth2/user",
headers={"Authentication": f"Bearer {ACCESS_TOKEN}"},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/user",
oauth2_user_method="POST",
oauth2_user_token_name="Authentication",
oauth2_user_token_location="HEADER_BEARER",
oauth2_user_extra_headers="Accept: application/json\nApi-Ver:1234",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_is_returned_using_post_request_with_extra_headers(
mock_request,
):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.post", post_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
post_mock.assert_called_once_with(
f"https://example.com/oauth2/user",
headers={
"Authentication": f"Bearer {ACCESS_TOKEN}",
"Accept": "application/json",
"Api-Ver": "1234",
},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data?type=user",
oauth2_user_method="GET",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
oauth2_json_id_path="id",
oauth2_json_name_path="name",
oauth2_json_email_path="email",
oauth2_json_avatar_path="avatar",
)
def test_user_data_request_with_token_in_url_respects_existing_querystring(
mock_request,
):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=user_data,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, user_data)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/data?type=user&atoken={ACCESS_TOKEN}",
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data?type=user",
oauth2_user_method="GET",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
oauth2_json_id_path="id",
oauth2_json_name_path="user.profile.name",
oauth2_json_email_path="user.profile.email",
oauth2_json_avatar_path="user.profile.avatar",
)
def test_user_data_json_values_are_mapped_to_result(mock_request):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
json_response = {
"id": user_data["id"],
"user": {
"profile": {
"name": user_data["name"],
"email": user_data["email"],
"avatar": user_data["avatar"],
}
},
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=json_response,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, json_response)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/data?type=user&atoken={ACCESS_TOKEN}",
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data?type=user",
oauth2_user_method="GET",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
oauth2_json_id_path="id",
oauth2_json_name_path="user.profile.name",
oauth2_json_email_path="user.profile.email",
oauth2_json_avatar_path="user.profile.avatar",
)
def test_user_data_json_values_are_none_when_not_found(mock_request):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": "https://example.com/avatar.png",
}
json_response = {
"profile_id": user_data["id"],
"user": {
"data": {
"name": user_data["name"],
"email": user_data["email"],
"avatar": user_data["avatar"],
}
},
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=json_response,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (
{
"id": None,
"name": None,
"email": None,
"avatar": None,
},
json_response,
)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/data?type=user&atoken={ACCESS_TOKEN}",
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data?type=user",
oauth2_user_method="GET",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
oauth2_json_id_path="id",
oauth2_json_name_path="user.profile.name",
oauth2_json_email_path="user.profile.email",
oauth2_json_avatar_path="",
)
def test_user_data_skips_avatar_if_path_is_not_set(mock_request):
user_data = {
"id": "7dds8a7dd89sa",
"name": "Aerith",
"email": "aerith@example.com",
"avatar": None,
}
json_response = {
"id": user_data["id"],
"user": {
"profile": {
"name": user_data["name"],
"email": user_data["email"],
"avatar": "https://example.com/avatar.png",
}
},
}
get_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=json_response,
),
),
)
with patch("requests.get", get_mock):
assert get_user_data(mock_request, ACCESS_TOKEN) == (user_data, json_response)
get_mock.assert_called_once_with(
f"https://example.com/oauth2/data?type=user&atoken={ACCESS_TOKEN}",
headers={},
timeout=REQUESTS_TIMEOUT,
)
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data",
oauth2_user_method="POST",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
)
def test_exception_is_raised_if_user_data_request_times_out(mock_request):
post_mock = Mock(side_effect=Timeout())
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2UserDataRequestError):
get_user_data(mock_request, ACCESS_TOKEN)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data",
oauth2_user_method="POST",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
)
def test_exception_is_raised_if_user_data_request_response_is_not_200(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=400,
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2UserDataResponseError):
get_user_data(mock_request, ACCESS_TOKEN)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data",
oauth2_user_method="POST",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
)
def test_exception_is_raised_if_user_data_request_response_is_not_json(mock_request):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
side_effect=ValueError(),
),
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2UserDataJSONError):
get_user_data(mock_request, ACCESS_TOKEN)
post_mock.assert_called_once()
@override_dynamic_settings(
oauth2_user_url="https://example.com/oauth2/data",
oauth2_user_method="POST",
oauth2_user_token_name="atoken",
oauth2_user_token_location="QUERY",
)
def test_exception_is_raised_if_user_data_request_response_json_is_not_object(
mock_request,
):
post_mock = Mock(
return_value=Mock(
status_code=200,
json=Mock(
return_value=["json", "list"],
),
),
)
with patch("requests.post", post_mock):
with pytest.raises(exceptions.OAuth2UserDataJSONError):
get_user_data(mock_request, ACCESS_TOKEN)
post_mock.assert_called_once()
| 16,106
|
Python
|
.py
| 485
| 25.381443
| 86
| 0.601596
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,521
|
test_user_update_with_data.py
|
rafalp_Misago/misago/oauth2/tests/test_user_update_with_data.py
|
from unittest.mock import Mock
import pytest
from django.contrib.auth import get_user_model
from ..exceptions import OAuth2UserDataValidationError
from ..models import Subject
from ..user import get_user_from_data
User = get_user_model()
def test_user_is_updated_with_valid_data(user, dynamic_settings):
Subject.objects.create(sub="1234", user=user)
updated_user, created = get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "UpdatedName",
"email": "updated@example.com",
"avatar": None,
},
{},
)
assert created is False
assert updated_user.id
assert updated_user.id == user.id
assert updated_user.username == "UpdatedName"
assert updated_user.username != user.username
assert updated_user.slug == "updatedname"
assert updated_user.slug != user.slug
assert updated_user.email == "updated@example.com"
assert updated_user.email != user.email
user_by_name = User.objects.get_by_username("UpdatedName")
assert user_by_name.id == user.id
user_by_email = User.objects.get_by_email("updated@example.com")
assert user_by_email.id == user.id
def test_user_is_not_updated_with_unchanged_valid_data(user, dynamic_settings):
Subject.objects.create(sub="1234", user=user)
updated_user, created = get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": user.username,
"email": user.email,
"avatar": None,
},
{},
)
assert created is False
assert updated_user.id
assert updated_user.id == user.id
assert updated_user.username == "User"
assert updated_user.username == user.username
assert updated_user.slug == "user"
assert updated_user.slug == user.slug
assert updated_user.email == "user@example.com"
assert updated_user.email == user.email
user_by_name = User.objects.get_by_username("User")
assert user_by_name.id == user.id
user_by_email = User.objects.get_by_email("user@example.com")
assert user_by_email.id == user.id
def test_user_name_conflict_during_update_with_valid_data_is_handled(
user, other_user, dynamic_settings, disable_user_data_filters
):
Subject.objects.create(sub="1234", user=user)
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": other_user.username,
"email": "test@example.com",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
"Your username returned by the provider is not available "
"for use on this site."
]
def test_user_email_conflict_during_update_with_valid_data_is_handled(
user, other_user, dynamic_settings
):
Subject.objects.create(sub="1234", user=user)
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "NewUser",
"email": other_user.email,
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
"Your e-mail address returned by the provider is not available "
"for use on this site."
]
| 3,579
|
Python
|
.py
| 95
| 29.947368
| 79
| 0.629587
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,522
|
test_user_data_filter.py
|
rafalp_Misago/misago/oauth2/tests/test_user_data_filter.py
|
from ..validation import filter_user_data
def test_new_user_data_is_filtered_using_default_filters(db, request):
filtered_data = filter_user_data(
request,
None,
{
"id": "242132",
"name": "New User",
"email": "oauth2@example.com",
"avatar": None,
},
)
assert filtered_data == {
"id": "242132",
"name": "New_User",
"email": "oauth2@example.com",
"avatar": None,
}
def test_existing_user_data_is_filtered_using_default_filters(user, request):
filtered_data = filter_user_data(
request,
user,
{
"id": "242132",
"name": user.username,
"email": user.email,
"avatar": None,
},
)
assert filtered_data == {
"id": "242132",
"name": user.username,
"email": user.email,
"avatar": None,
}
def test_empty_user_name_is_replaced_with_placeholder_one(db, request):
filtered_data = filter_user_data(
request,
None,
{
"id": "242132",
"name": None,
"email": "oauth2@example.com",
"avatar": None,
},
)
assert filtered_data["name"].strip()
def test_missing_user_name_is_replaced_with_placeholder_one(db, request):
filtered_data = filter_user_data(
request,
None,
{
"id": "242132",
"name": None,
"email": "oauth2@example.com",
"avatar": None,
},
)
assert filtered_data["name"].strip()
def test_missing_user_email_is_set_as_empty_str(db, request):
filtered_data = filter_user_data(
request,
None,
{
"id": "242132",
"name": "New User",
"email": None,
"avatar": None,
},
)
assert filtered_data == {
"id": "242132",
"name": "New_User",
"email": "",
"avatar": None,
}
def test_original_user_data_is_not_mutated_by_default_filters(user, request):
user_data = {
"id": "1234",
"name": "New User",
"email": "oauth2@example.com",
"avatar": None,
}
filtered_data = filter_user_data(request, user, user_data)
assert filtered_data == {
"id": "1234",
"name": "New_User",
"email": "oauth2@example.com",
"avatar": None,
}
assert user_data == {
"id": "1234",
"name": "New User",
"email": "oauth2@example.com",
"avatar": None,
}
| 2,600
|
Python
|
.py
| 96
| 18.677083
| 77
| 0.507847
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,523
|
test_oauth2_complete_view.py
|
rafalp_Misago/misago/oauth2/tests/test_oauth2_complete_view.py
|
import responses
from django.contrib.auth import get_user_model
from django.urls import reverse
from responses.matchers import header_matcher, urlencoded_params_matcher
from ...conf.test import override_dynamic_settings
from ...test import assert_contains
from ...users.bans import ban_ip, ban_user
from ..client import SESSION_STATE
from ..models import Subject
User = get_user_model()
def test_oauth2_complete_view_returns_404_if_oauth_is_disabled(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is False
response = client.get(reverse("misago:oauth2-complete"))
assert response.status_code == 404
def test_oauth2_complete_view_returns_error_404_if_user_ip_is_banned_and_oauth_is_disabled(
client, dynamic_settings
):
ban_ip("127.*", "Ya got banned!")
assert dynamic_settings.enable_oauth2_client is False
response = client.get(reverse("misago:oauth2-complete"))
assert response.status_code == 404
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_complete_view_returns_error_403_if_user_ip_is_banned(
client, dynamic_settings
):
ban_ip("127.*", "Ya got banned!")
assert dynamic_settings.enable_oauth2_client is True
response = client.get(reverse("misago:oauth2-complete"))
assert_contains(response, "Ya got banned", 403)
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_complete_view_returns_error_400_if_user_canceled_sign_in(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
response = client.get("%s?error=access_denied" % reverse("misago:oauth2-complete"))
assert_contains(response, "The OAuth2 process was canceled by the provider.", 400)
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_complete_view_returns_error_400_if_state_is_not_set(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
response = client.get(reverse("misago:oauth2-complete"))
assert_contains(response, "OAuth2 session is missing state.", 400)
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_complete_view_returns_error_400_if_state_is_invalid(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
session = client.session
session[SESSION_STATE] = "state123"
session.save()
response = client.get(
"%s?state=invalid&code=1234" % reverse("misago:oauth2-complete")
)
assert_contains(
response,
"OAuth2 state sent by the provider did not match one in the session.",
400,
)
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_complete_view_returns_error_400_if_code_is_missing(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
session = client.session
session[SESSION_STATE] = "state123"
session.save()
response = client.get("%s?state=state123&code=" % reverse("misago:oauth2-complete"))
assert_contains(
response,
"OAuth2 authorization code was not sent by the provider.",
400,
)
TEST_SETTINGS = {
"enable_oauth2_client": True,
"oauth2_client_id": "oauth2_client_id",
"oauth2_client_secret": "oauth2_client_secret",
"oauth2_login_url": "https://example.com/oauth2/login",
"oauth2_token_url": "https://example.com/oauth2/token",
"oauth2_json_token_path": "token.bearer",
"oauth2_user_url": "https://example.com/oauth2/user",
"oauth2_user_method": "POST",
"oauth2_user_token_name": "Authorization",
"oauth2_user_token_location": "HEADER_BEARER",
"oauth2_send_welcome_email": True,
"oauth2_json_id_path": "id",
"oauth2_json_name_path": "profile.name",
"oauth2_json_email_path": "profile.email",
}
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_creates_new_user(client, dynamic_settings, mailoutbox):
assert dynamic_settings.enable_oauth2_client is True
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert response.status_code == 302
# User and subject are created
subject = Subject.objects.get(sub="1234")
user = User.objects.get_by_email("john@example.com")
assert subject.user_id == user.id
assert user.username == "John_Doe"
assert user.slug == "john-doe"
assert user.email == "john@example.com"
assert user.requires_activation == User.ACTIVATION_NONE
# User is authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] == user.id
# User welcome e-mail is sent
assert len(mailoutbox) == 1
assert mailoutbox[0].subject == "Welcome on Misago forums!"
TEST_SETTINGS_EMAIL_DISABLED = TEST_SETTINGS.copy()
TEST_SETTINGS_EMAIL_DISABLED["oauth2_send_welcome_email"] = False
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS_EMAIL_DISABLED)
def test_oauth2_complete_view_doesnt_send_welcome_mail_if_option_is_disabled(
client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert response.status_code == 302
# User and subject are created
subject = Subject.objects.get(sub="1234")
user = User.objects.get_by_email("john@example.com")
assert subject.user_id == user.id
# User is authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] == user.id
# User welcome e-mail is not sent
assert len(mailoutbox) == 0
TEST_SETTINGS_EXTRA_TOKEN_HEADERS = TEST_SETTINGS.copy()
TEST_SETTINGS_EXTRA_TOKEN_HEADERS["oauth2_token_extra_headers"] = (
"""
Accept: application/json
API-Version: 2.1.3.7
""".strip()
)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS_EXTRA_TOKEN_HEADERS)
def test_oauth2_complete_view_includes_extra_headers_in_token_request(
client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
header_matcher(
{
"Accept": "application/json",
"API-Version": "2.1.3.7",
}
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert response.status_code == 302
# User and subject are created
subject = Subject.objects.get(sub="1234")
user = User.objects.get_by_email("john@example.com")
assert subject.user_id == user.id
# User is authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] == user.id
TEST_SETTINGS_EXTRA_USER_HEADERS = TEST_SETTINGS.copy()
TEST_SETTINGS_EXTRA_USER_HEADERS["oauth2_user_extra_headers"] = (
"""
X-Header: its-a-test
API-Version: 2.1.3.7
""".strip()
)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS_EXTRA_USER_HEADERS)
def test_oauth2_complete_view_includes_extra_headers_in_user_request(
client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher(
{
"Authorization": f"Bearer {access_token}",
"X-Header": "its-a-test",
"API-Version": "2.1.3.7",
}
),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert response.status_code == 302
# User and subject are created
subject = Subject.objects.get(sub="1234")
user = User.objects.get_by_email("john@example.com")
assert subject.user_id == user.id
# User is authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] == user.id
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_updates_existing_user(
user, client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
Subject.objects.create(sub="1234", user=user)
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert response.status_code == 302
# User is updated
user.refresh_from_db()
assert user.username == "John_Doe"
assert user.slug == "john-doe"
assert user.email == "john@example.com"
# User is authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] == user.id
# User welcome e-mail is not sent
assert len(mailoutbox) == 0
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_returns_error_400_if_code_grant_is_rejected(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
code_grant = "12345grant"
session_state = "12345state"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"error": "Permission denied",
},
status=403,
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(
response,
"The OAuth2 provider responded with error for an access token request.",
400,
)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_returns_error_400_if_access_token_is_rejected(
user, client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
Subject.objects.create(sub="1234", user=user)
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"error": "Permission denied",
},
status=403,
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(
response,
"The OAuth2 provider responded with error for user profile request.",
400,
)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_returns_error_400_if_user_email_was_missing(
user, client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
Subject.objects.create(sub="1234", user=user)
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(response, "Enter a valid e-mail address.", 400)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_returns_error_400_if_user_email_was_invalid(
user, client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
Subject.objects.create(sub="1234", user=user)
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "invalid",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(response, "Enter a valid e-mail address.", 400)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_returns_error_400_if_user_data_causes_integrity_error(
user, client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": user.email,
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(
response,
(
"Your e-mail address returned by the provider is not available "
"for use on this site."
),
400,
)
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_updates_deactivated_user_but_returns_error_400(
inactive_user, client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
Subject.objects.create(sub="1234", user=inactive_user)
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(
response,
(
"User account associated with the profile from the OAuth2 provider "
"was deactivated by the site administrator."
),
400,
)
# User is updated but still deactivated
inactive_user.refresh_from_db()
assert inactive_user.username == "John_Doe"
assert inactive_user.slug == "john-doe"
assert inactive_user.email == "john@example.com"
assert inactive_user.is_active is False
# User is not authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] is None
# User welcome e-mail is not sent
assert len(mailoutbox) == 0
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_creates_banned_user_but_returns_error_403(
user, client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
user.username = "John_Doe"
ban_user(user, "Banned for a test.")
user.refresh_from_db()
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(response, "Banned for a test.", 403)
# User is created
new_user = User.objects.get_by_email("john@example.com")
assert new_user
assert new_user.id != user.id
assert new_user.username == "John_Doe"
assert new_user.slug == "john-doe"
assert new_user.email == "john@example.com"
# User is not authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] is None
# User welcome e-mail is not sent
assert len(mailoutbox) == 0
@responses.activate
@override_dynamic_settings(**TEST_SETTINGS)
def test_oauth2_complete_view_updates_banned_user_but_returns_error_403(
user, client, dynamic_settings, mailoutbox
):
assert dynamic_settings.enable_oauth2_client is True
Subject.objects.create(sub="1234", user=user)
user.username = "John_Doe"
ban_user(user, "Banned for a test.")
user.refresh_from_db()
code_grant = "12345grant"
session_state = "12345state"
access_token = "12345token"
session = client.session
session[SESSION_STATE] = session_state
session.save()
responses.post(
"https://example.com/oauth2/token",
json={
"token": {
"bearer": access_token,
},
},
match=[
urlencoded_params_matcher(
{
"grant_type": "authorization_code",
"client_id": "oauth2_client_id",
"client_secret": "oauth2_client_secret",
"redirect_uri": "http://testserver/oauth2/complete/",
"code": code_grant,
},
),
],
)
responses.post(
"https://example.com/oauth2/user",
json={
"id": 1234,
"profile": {
"name": "John Doe",
"email": "john@example.com",
},
},
match=[
header_matcher({"Authorization": f"Bearer {access_token}"}),
],
)
response = client.get(
"%s?state=%s&code=%s"
% (
reverse("misago:oauth2-complete"),
session_state,
code_grant,
)
)
assert_contains(response, "Banned for a test.", 403)
# User is updated
user.refresh_from_db()
assert user.username == "John_Doe"
assert user.slug == "john-doe"
assert user.email == "john@example.com"
# User is not authenticated
auth_api = client.get(reverse("misago:api:auth")).json()
assert auth_api["id"] is None
# User welcome e-mail is not sent
assert len(mailoutbox) == 0
| 29,501
|
Python
|
.py
| 923
| 23.151679
| 91
| 0.570312
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,524
|
test_login_url_creation.py
|
rafalp_Misago/misago/oauth2/tests/test_login_url_creation.py
|
from unittest.mock import Mock, patch
from urllib.parse import parse_qsl, urlparse
from ...conf.test import override_dynamic_settings
from ..client import (
SESSION_CODE_VERIFIER,
SESSION_STATE,
create_login_url,
)
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="some scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_login_url_is_created(dynamic_settings):
request = Mock(
session={},
settings=dynamic_settings,
build_absolute_uri=lambda url: f"http://mysite.com{url or ''}",
)
login_url = create_login_url(request)
# State set in session?
assert request.session.get(SESSION_STATE)
# Redirect url is valid?
redirect_to = urlparse(login_url)
assert redirect_to.netloc == "example.com"
assert redirect_to.path == "/oauth2/login"
assert parse_qsl(redirect_to.query) == [
("response_type", "code"),
("client_id", "clientid123"),
("redirect_uri", "http://mysite.com/oauth2/complete/"),
("scope", "some scopes"),
("state", request.session[SESSION_STATE]),
]
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="some scopes",
oauth2_login_url="https://example.com/oauth2/login",
oauth2_enable_pkce=True,
)
def test_oauth2_login_url_is_created_with_pkce(dynamic_settings):
code_verifier = "SF01jh"
code_challenge = "eemb2YInusdSF01jhCXpzV_juX3_xdAQnVU1oCvFBA"
request = Mock(
session={},
settings=dynamic_settings,
build_absolute_uri=lambda url: f"http://mysite.com{url or ''}",
)
with patch(
"misago.oauth2.client.get_code_challenge", return_value=code_challenge
), patch("misago.oauth2.client.token_urlsafe", return_value=code_verifier):
login_url = create_login_url(request)
# State set in session?
assert request.session.get(SESSION_STATE)
assert request.session.get(SESSION_CODE_VERIFIER) == code_verifier
# Redirect url is valid?
redirect_to = urlparse(login_url)
assert redirect_to.netloc == "example.com"
assert redirect_to.path == "/oauth2/login"
assert parse_qsl(redirect_to.query) == [
("response_type", "code"),
("client_id", "clientid123"),
("redirect_uri", "http://mysite.com/oauth2/complete/"),
("scope", "some scopes"),
("state", request.session[SESSION_STATE]),
("code_challenge", code_challenge),
("code_challenge_method", "S256"),
]
| 2,602
|
Python
|
.py
| 69
| 32.014493
| 79
| 0.671559
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,525
|
test_user_creation_from_data.py
|
rafalp_Misago/misago/oauth2/tests/test_user_creation_from_data.py
|
from unittest.mock import Mock
import pytest
from django.contrib.auth import get_user_model
from ...conf.test import override_dynamic_settings
from ..exceptions import OAuth2UserDataValidationError
from ..models import Subject
from ..user import get_user_from_data
User = get_user_model()
def test_activated_user_is_created_from_valid_data(db, dynamic_settings):
user, created = get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "NewUser",
"email": "user@example.com",
"avatar": None,
},
{},
)
assert created
assert user.id
assert user.username == "NewUser"
assert user.slug == "newuser"
assert user.email == "user@example.com"
assert user.requires_activation == User.ACTIVATION_NONE
user_by_name = User.objects.get_by_username("NewUser")
assert user_by_name.id == user.id
user_by_email = User.objects.get_by_email("user@example.com")
assert user_by_email.id == user.id
def test_user_subject_is_created_from_valid_data(db, dynamic_settings):
user, created = get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "NewUser",
"email": "user@example.com",
"avatar": None,
},
{},
)
assert created
assert user
user_subject = Subject.objects.get(sub="1234")
assert user_subject.user_id == user.id
def test_user_is_created_with_avatar_from_valid_data(db, dynamic_settings):
user, created = get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "NewUser",
"email": "user@example.com",
"avatar": "https://dummyimage.com/600/500",
},
{},
)
assert created
assert user
assert user.avatars
assert user.avatar_set.exists()
@override_dynamic_settings(account_activation="admin")
def test_user_is_created_with_admin_activation_from_valid_data(db, dynamic_settings):
user, created = get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "NewUser",
"email": "user@example.com",
"avatar": None,
},
{},
)
assert created
assert user
assert user.requires_activation == User.ACTIVATION_ADMIN
def test_user_name_conflict_during_creation_from_valid_data_is_handled(
user, dynamic_settings, disable_user_data_filters
):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": user.username,
"email": "test@example.com",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
"Your username returned by the provider is not available for use on this site."
]
def test_user_email_conflict_during_creation_from_valid_data_is_handled(
user, dynamic_settings
):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
get_user_from_data(
Mock(settings=dynamic_settings, user_ip="83.0.0.1"),
{
"id": "1234",
"name": "NewUser",
"email": user.email,
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
"Your e-mail address returned by the provider is not available "
"for use on this site."
]
| 3,731
|
Python
|
.py
| 109
| 26.146789
| 87
| 0.599778
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,526
|
test_user_data_validation.py
|
rafalp_Misago/misago/oauth2/tests/test_user_data_validation.py
|
from unittest.mock import Mock
import pytest
from ..exceptions import OAuth2UserDataValidationError
from ..validation import validate_user_data
def test_new_user_valid_data_is_validated(db, dynamic_settings):
valid_data = validate_user_data(
Mock(settings=dynamic_settings),
None,
{
"id": "1234",
"name": "Test User",
"email": "user@example.com",
"avatar": None,
},
{},
)
assert valid_data == {
"id": "1234",
"name": "Test_User",
"email": "user@example.com",
"avatar": None,
}
def test_existing_user_valid_data_is_validated(user, dynamic_settings):
valid_data = validate_user_data(
Mock(settings=dynamic_settings),
user,
{
"id": "1234",
"name": user.username,
"email": user.email,
"avatar": None,
},
{},
)
assert valid_data == {
"id": "1234",
"name": user.username,
"email": user.email,
"avatar": None,
}
def test_error_was_raised_for_user_data_with_without_name(
db, dynamic_settings, disable_user_data_filters
):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
validate_user_data(
Mock(settings=dynamic_settings),
None,
{
"id": "1234",
"name": "",
"email": "user@example.com",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
(
"Username can only contain Latin alphabet letters, digits, "
"and an underscore sign."
)
]
def test_error_was_raised_for_user_data_with_invalid_name(
db, dynamic_settings, disable_user_data_filters
):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
validate_user_data(
Mock(settings=dynamic_settings),
None,
{
"id": "1234",
"name": "Invalid!",
"email": "user@example.com",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
(
"Username can only contain Latin alphabet letters, digits, "
"and an underscore sign."
)
]
def test_error_was_raised_for_user_data_with_too_long_name(db, dynamic_settings):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
validate_user_data(
Mock(settings=dynamic_settings),
None,
{
"id": "1234",
"name": "UserName" * 100,
"email": "user@example.com",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == [
"Username cannot be longer than 200 characters."
]
def test_error_was_raised_for_user_data_without_email(db, dynamic_settings):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
validate_user_data(
Mock(settings=dynamic_settings),
None,
{
"id": "1234",
"name": "Test User",
"email": "",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == ["Enter a valid e-mail address."]
def test_error_was_raised_for_user_data_with_invalid_email(db, dynamic_settings):
with pytest.raises(OAuth2UserDataValidationError) as excinfo:
validate_user_data(
Mock(settings=dynamic_settings),
None,
{
"id": "1234",
"name": "Test User",
"email": "userexample.com",
"avatar": None,
},
{},
)
assert excinfo.value.error_list == ["Enter a valid e-mail address."]
| 3,933
|
Python
|
.py
| 126
| 21.142857
| 81
| 0.527484
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,527
|
test_oauth2_login_view.py
|
rafalp_Misago/misago/oauth2/tests/test_oauth2_login_view.py
|
from unittest.mock import patch
from urllib.parse import urlparse
from django.urls import reverse
from ...conf.test import override_dynamic_settings
from ...test import assert_contains
from ...users.bans import ban_ip
def test_oauth2_login_view_returns_404_if_oauth_is_disabled(client, dynamic_settings):
assert dynamic_settings.enable_oauth2_client is False
response = client.get(reverse("misago:oauth2-login"))
assert response.status_code == 404
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_login_view_returns_redirect_302_if_oauth_is_enabled(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
response = client.get(reverse("misago:oauth2-login"))
assert response.status_code == 302
redirect_to = urlparse(response["Location"])
assert redirect_to.netloc == "example.com"
assert redirect_to.path == "/oauth2/login"
assert "clientid123" in redirect_to.query
assert "code_challenge" not in redirect_to.query
assert "code_challenge_method=S256" not in redirect_to.query
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
)
def test_oauth2_login_view_returns_error_403_if_user_ip_is_banned(
client, dynamic_settings
):
ban_ip("127.*", "Ya got banned!")
assert dynamic_settings.enable_oauth2_client is True
response = client.get(reverse("misago:oauth2-login"))
assert_contains(response, "Ya got banned", 403)
def test_oauth2_login_view_returns_error_404_if_user_ip_is_banned_and_oauth_is_disabled(
client, dynamic_settings
):
ban_ip("127.*", "Ya got banned!")
assert dynamic_settings.enable_oauth2_client is False
response = client.get(reverse("misago:oauth2-login"))
assert response.status_code == 404
@override_dynamic_settings(
enable_oauth2_client=True,
oauth2_client_id="clientid123",
oauth2_scopes="scopes",
oauth2_login_url="https://example.com/oauth2/login",
oauth2_enable_pkce=True,
)
def test_oauth2_login_view_returns_redirect_302_if_oauth_and_pkce_enabled(
client, dynamic_settings
):
assert dynamic_settings.enable_oauth2_client is True
with patch(
"misago.oauth2.client.get_code_challenge",
return_value="eemb2YInusdSF01jhCXpzV_juX3_xdAQnVU1oCvFBA",
):
response = client.get(reverse("misago:oauth2-login"))
assert response.status_code == 302
redirect_to = urlparse(response["Location"])
assert redirect_to.netloc == "example.com"
assert redirect_to.path == "/oauth2/login"
assert "clientid123" in redirect_to.query
assert (
"code_challenge=eemb2YInusdSF01jhCXpzV_juX3_xdAQnVU1oCvFBA" in redirect_to.query
)
assert "code_challenge_method=S256" in redirect_to.query
| 2,999
|
Python
|
.py
| 73
| 36.739726
| 88
| 0.741569
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,528
|
test_headers_dict_creation.py
|
rafalp_Misago/misago/oauth2/tests/test_headers_dict_creation.py
|
from ..client import get_headers_dict
def test_empty_headers_dict_is_returned_for_none():
headers = get_headers_dict(None)
assert headers == {}
def test_empty_headers_dict_is_returned_for_empty_str():
headers = get_headers_dict("")
assert headers == {}
def test_empty_headers_dict_is_returned_for_empty_multiline_str():
headers = get_headers_dict(" \n \n ")
assert headers == {}
def test_header_is_returned_from_str():
headers = get_headers_dict("Lorem: ipsum")
assert headers == {"Lorem": "ipsum"}
def test_headers_str_content_is_cleaned():
headers = get_headers_dict(" Lorem: ips:um\n\n")
assert headers == {"Lorem": "ips:um"}
def test_multiple_headers_are_returned_from_multiline_str():
headers = get_headers_dict("Lorem: ipsum\nDolor: met")
assert headers == {"Lorem": "ipsum", "Dolor": "met"}
| 865
|
Python
|
.py
| 19
| 41.368421
| 66
| 0.681055
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,529
|
filter_user_data.py
|
rafalp_Misago/misago/oauth2/hooks/filter_user_data.py
|
from typing import Optional, Protocol
from django.http import HttpRequest
from ...plugins.hooks import FilterHook
from ...users.models import User
class FilterUserDataHookAction(Protocol):
"""
A standard Misago function used for filtering the user data, or the next
filter function from another plugin.
# Arguments
## `request: HttpRequest`
The request object.
## `user: Optional[User]`
A `User` object associated with `user_data["id"]` or `user_data["email"]`,
or `None` if it's the user's first time signing in with OAuth and the user's
account hasn't been created yet.
## `user_data: dict`
A Python `dict` with user data extracted from the OAuth 2 server's response:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
# Return value
A Python `dict` containing user data:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
"""
def __call__(
self,
request: HttpRequest,
user: Optional[User],
user_data: dict,
) -> dict:
pass
class FilterUserDataHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: FilterUserDataHookAction`
A standard Misago function used for filtering the user data, or the next
filter function from another plugin.
See the [action](#action) section for details.
## `request: HttpRequest`
The request object.
## `user: Optional[User]`
A `User` object associated with `user_data["id"]` or `user_data["email"]`,
or `None` if it's the user's first time signing in with OAuth and the user's
account hasn't been created yet.
## `user_data: dict`
A Python `dict` with user data extracted from the OAuth 2 server's response:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
# Return value
A Python `dict` containing user data:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
"""
def __call__(
self,
action: FilterUserDataHookAction,
request: HttpRequest,
user: Optional[User],
user_data: dict,
) -> dict:
pass
class FilterUserDataHook(
FilterHook[FilterUserDataHookAction, FilterUserDataHookFilter]
):
"""
This hook wraps the standard function that Misago uses to filter a Python `dict`
containing the user data extracted from the OAuth 2 server's response.
User data filtering is part of the [user data validation by the OAuth 2
client](./validate-user-data-hook.md), which itself is part of a function that
creates a new user account or updates an existing one if user data has changed.
Standard user data filtering doesn't validate the data but instead tries to
improve it to increase its chances of passing the validation. It converts the
`name` into a valid Misago username (e.g., `�ukasz Kowalski` becomes
`Lukasz_Kowalski`). It also appends a random string at the end of the name if
it's already taken by another user (e.g., `RickSanchez` becomes
`RickSanchez_C137`). If the name is empty, a placeholder one is generated,
e.g., `User_d6a9`. Lastly, it replaces an `email` with an empty string if
it's `None`, to prevent a type error from being raised by e-mail validation
that happens in the next step.
Plugin filters can still raise Django's `ValidationError` on an invalid value
instead of attempting to fix it if this is a preferable resolution.
# Example
The code below implements a custom filter function that extends the standard
logic with additional user e-mail normalization for Gmail e-mails:
```python
from django.http import HttpRequest
from misago.oauth.hooks import filter_user_data_hook
from misago.users.models import User
@filter_user_data_hook.append_filter
def normalize_gmail_email(
action, request: HttpRequest, user: User | None, user_data: dict
) -> dict:
if (
user_data["email"]
and user_data["email"].lower().endswith("@gmail.com")
):
# Dots in Gmail emails are ignored but frequently used by spammers
new_user_email = user_data["email"][:-10].replace(".", "")
user_data["email"] = new_user_email + "@gmail.com"
# Call the next function in chain
return action(user_data, request, user, user_data)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: FilterUserDataHookAction,
request: HttpRequest,
user: Optional[User],
user_data: dict,
) -> dict:
return super().__call__(action, request, user, user_data)
filter_user_data_hook = FilterUserDataHook()
| 5,134
|
Python
|
.py
| 134
| 31.791045
| 84
| 0.664176
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,530
|
__init__.py
|
rafalp_Misago/misago/oauth2/hooks/__init__.py
|
from .filter_user_data import filter_user_data_hook
from .validate_user_data import validate_user_data_hook
__all__ = ["filter_user_data_hook", "validate_user_data_hook"]
| 173
|
Python
|
.py
| 3
| 56
| 62
| 0.767857
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,531
|
validate_user_data.py
|
rafalp_Misago/misago/oauth2/hooks/validate_user_data.py
|
from typing import Optional, Protocol
from django.http import HttpRequest
from ...plugins.hooks import FilterHook
from ...users.models import User
class ValidateUserDataHookAction(Protocol):
"""
A standard Misago function used for validating the user data, or the next
filter function from another plugin.
Should raise a Django's `ValidationError` if data is invalid.
# Arguments
## `request: HttpRequest`
The request object.
## `user: Optional[User]`
A `User` object associated with `user_data["id"]` or `user_data["email"]`,
or `None` if it's the user's first time signing in with OAuth and the user's
account hasn't been created yet.
## `user_data: dict`
A Python `dict` with user data extracted from the OAuth 2 server's response:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
This `dict` will be unfiltered unless it was filtered by an `action` call or `filter_user_data` was used by the plugin to filter it.
## `response_json: dict`
A Python `dict` with the unfiltered OAuth 2 server's user info JSON.
# Return value
A Python `dict` containing validated user data:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
"""
def __call__(
self,
request: HttpRequest,
user: Optional[User],
user_data: dict,
response_json: dict,
) -> dict:
pass
class ValidateUserDataHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
Should raise a Django's `ValidationError` if data is invalid.
# Arguments
## `action: ValidateUserDataHookAction`
A standard Misago function used for filtering the user data, or the next
filter function from another plugin.
See the [action](#action) section for details.
## `request: HttpRequest`
The request object.
## `user: Optional[User]`
A `User` object associated with `user_data["id"]` or `user_data["email"]`,
or `None` if it's the user's first time signing in with OAuth and the user's
account hasn't been created yet.
## `user_data: dict`
A Python `dict` with user data extracted from the OAuth 2 server's response:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
This `dict` will be unfiltered unless it was filtered by an `action` call or `filter_user_data` was used by the plugin to filter it.
## `response_json: dict`
A Python `dict` with the unfiltered OAuth 2 server's user info JSON.
# Return value
A Python `dict` containing validated user data:
```python
class UserData(TypedDict):
id: str
name: str | None
email: str | None
avatar: str | None
```
"""
def __call__(
self,
action: ValidateUserDataHookAction,
request: HttpRequest,
user: Optional[User],
user_data: dict,
response_json: dict,
) -> dict:
pass
class ValidateUserDataHook(
FilterHook[ValidateUserDataHookAction, ValidateUserDataHookFilter]
):
"""
This hook wraps the standard function that Misago uses to validate a Python
`dict` containing the user data extracted from the OAuth 2 server's response.
Should raise a Django's `ValidationError` if data is invalid.
# Example
The code below implements a custom validator function that extends the standard
logic with additional check for a permission to use the forum by the user:
```python
from django.forms import ValidationError
from django.http import HttpRequest
from misago.oauth.hooks import validate_user_data_hook
from misago.users.models import User
@validate_user_data_hook.append_filter
def normalize_gmail_email(
action,
request: HttpRequest,
user: User | None,
user_data: dict,
response_json: dict,
) -> dict:
# Prevent user from completing the OAuth 2 flow unless they are a member
# of the "forum" group
if (
not response_json.get("groups")
or not isinstance(response_json["groups"], list)
or not "forum" in response_json["groups"]
):
raise ValidationError("You don't have a permission to use the forums.")
# Call the next function in chain
return action(user_data, request, user, user_data, response_json)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: ValidateUserDataHookAction,
request: HttpRequest,
user: Optional[User],
user_data: dict,
response_json: dict,
) -> dict:
return super().__call__(action, request, user, user_data, response_json)
validate_user_data_hook = ValidateUserDataHook()
| 5,080
|
Python
|
.py
| 138
| 30.086957
| 136
| 0.659984
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,532
|
models.py
|
rafalp_Misago/misago/permissions/models.py
|
from dataclasses import dataclass
from typing import TYPE_CHECKING
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.db import models
from ..users.enums import DefaultGroupId
from .moderator import ModeratorPermissions
if TYPE_CHECKING:
from ..users.models import User
class CategoryGroupPermission(models.Model):
category = models.ForeignKey("misago_categories.Category", on_delete=models.CASCADE)
group = models.ForeignKey("misago_users.Group", on_delete=models.CASCADE)
permission = models.CharField(max_length=32)
class ModeratorManager(models.Manager):
def get_moderator_permissions(self, user: "User") -> ModeratorPermissions:
fin_is_global: bool = False
fin_categories: list[int] = []
fin_private_threads: bool = False
queryset = Moderator.objects.filter(
models.Q(group__in=user.groups_ids) | models.Q(user=user)
).values_list("is_global", "categories", "private_threads")
for is_global, categories, private_threads in queryset:
fin_is_global = fin_is_global or is_global
fin_categories += categories
fin_private_threads = fin_private_threads or private_threads
return ModeratorPermissions(
is_global=fin_is_global,
categories_ids=set(fin_categories),
private_threads=fin_private_threads,
)
class Moderator(models.Model):
group = models.ForeignKey("misago_users.Group", null=True, on_delete=models.CASCADE)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE
)
is_global = models.BooleanField(default=True)
categories = ArrayField(models.PositiveIntegerField(), default=list)
private_threads = models.BooleanField(default=False)
objects = ModeratorManager()
@property
def is_protected(self):
return self.group_id in (DefaultGroupId.ADMINS, DefaultGroupId.MODERATORS)
@property
def name(self):
if self.group_id:
return str(self.group)
return str(self.user)
| 2,120
|
Python
|
.py
| 47
| 38.340426
| 88
| 0.717201
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,533
|
moderator.py
|
rafalp_Misago/misago/permissions/moderator.py
|
from dataclasses import dataclass
@dataclass(frozen=True)
class ModeratorPermissions:
is_global: bool
categories_ids: set[int]
private_threads: bool
| 163
|
Python
|
.py
| 6
| 23.833333
| 33
| 0.793548
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,534
|
enums.py
|
rafalp_Misago/misago/permissions/enums.py
|
from enum import StrEnum
class CategoryPermission(StrEnum):
SEE = "see"
BROWSE = "browse"
START = "start"
REPLY = "reply"
ATTACHMENTS = "attachments"
class CategoryQueryContext(StrEnum):
CURRENT = "current"
CHILD = "child"
OTHER = "other"
class CategoryThreadsQuery(StrEnum):
ALL = "all"
ALL_PINNED = "all_pinned"
ALL_PINNED_GLOBALLY = "all_pinned_globally"
ALL_PINNED_IN_CATEGORY = "all_pinned_in_category"
ALL_NOT_PINNED = "all_not_pinned"
ALL_NOT_PINNED_GLOBALLY = "all_not_pinned_globally"
ANON = "anon"
ANON_PINNED = "anon_pinned"
ANON_PINNED_GLOBALLY = "anon_pinned_globally"
ANON_PINNED_IN_CATEGORY = "anon_pinned_in_category"
ANON_NOT_PINNED = "anon_not_pinned"
ANON_NOT_PINNED_GLOBALLY = "anon_not_pinned_globally"
USER = "user"
USER_PINNED = "user_pinned"
USER_PINNED_GLOBALLY = "user_pinned_globally"
USER_PINNED_IN_CATEGORY = "user_pinned_in_category"
USER_NOT_PINNED = "user_not_pinned"
USER_NOT_PINNED_GLOBALLY = "user_not_pinned_globally"
USER_STARTED_PINNED = "user_started_pinned"
USER_STARTED_PINNED_GLOBALLY = "user_started_pinned_globally"
USER_STARTED_PINNED_IN_CATEGORY = "user_started_pinned_in_category"
USER_STARTED_NOT_PINNED = "user_started_not_pinned"
| 1,309
|
Python
|
.py
| 34
| 33.705882
| 71
| 0.703791
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,535
|
proxy.py
|
rafalp_Misago/misago/permissions/proxy.py
|
from functools import cached_property
from typing import TYPE_CHECKING, Any, Union
from django.contrib.auth.models import AnonymousUser
from ..users.enums import DefaultGroupId
from .enums import CategoryPermission
from .models import Moderator
from .moderator import ModeratorPermissions
from .user import get_user_permissions
if TYPE_CHECKING:
from ..users.models import User
class UserPermissionsProxy:
user: Union["User", AnonymousUser]
cache_versions: dict
accessed_permissions: bool
_wrapped = False
def __init__(self, user: Union["User", AnonymousUser], cache_versions: dict):
self.user = user
self.cache_versions = cache_versions
self.accessed_permissions = False
def __getattr__(self, name: str) -> Any:
try:
return self.permissions[name]
except KeyError as exc:
valid_permissions = "', '".join(self.permissions)
raise AttributeError(
f"{exc} is not an 'UserPermissionsProxy' attribute or "
f"one of valid permissions: '{valid_permissions}'"
) from exc
@cached_property
def permissions(self) -> dict:
self.accessed_permissions = True
return get_user_permissions(self.user, self.cache_versions)
@cached_property
def moderator(self) -> ModeratorPermissions | None:
if self.user.is_anonymous:
return None
return Moderator.objects.get_moderator_permissions(self.user)
@property
def is_global_moderator(self) -> bool:
if self.user.is_anonymous:
return False
if (
DefaultGroupId.ADMINS in self.user.groups_ids
or DefaultGroupId.MODERATORS in self.user.groups_ids
):
return True
return self.moderator.is_global
@cached_property
def categories_moderator(self) -> set[int]:
if self.user.is_anonymous:
return set()
if self.is_global_moderator:
return set(self.permissions["categories"][CategoryPermission.BROWSE])
if not self.permissions["categories"][CategoryPermission.BROWSE]:
return set()
browsed_categories = set(
self.permissions["categories"][CategoryPermission.BROWSE]
)
return browsed_categories.intersection(self.moderator.categories_ids)
@property
def private_threads_moderator(self) -> bool:
if self.user.is_anonymous:
return False
if self.is_global_moderator:
return True
return self.moderator.private_threads
| 2,600
|
Python
|
.py
| 66
| 31.151515
| 81
| 0.671576
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,536
|
user.py
|
rafalp_Misago/misago/permissions/user.py
|
from typing import TYPE_CHECKING, Union
from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
from ..cache.enums import CacheName
from ..categories.enums import CategoryTree
from ..categories.models import Category
from ..users.enums import DefaultGroupId
from ..users.models import Group
from .enums import CategoryPermission
from .hooks import (
build_user_category_permissions_hook,
build_user_permissions_hook,
get_user_permissions_hook,
)
from .models import CategoryGroupPermission
from .operations import (
if_greater,
if_true,
if_zero_or_greater,
)
if TYPE_CHECKING:
from ..users.models import User
def get_user_permissions(
user: Union["User", AnonymousUser], cache_versions: dict
) -> dict:
return get_user_permissions_hook(_get_user_permissions_action, user, cache_versions)
def _get_user_permissions_action(
user: Union["User", AnonymousUser], cache_versions: dict
) -> dict:
cache_key = get_user_permissions_cache_key(user, cache_versions)
permissions = cache.get(cache_key)
if permissions is None:
permissions = build_user_permissions(user)
cache.set(cache_key, permissions)
return permissions
def get_user_permissions_cache_key(
user: Union["User", AnonymousUser], cache_versions: dict
) -> str:
if user.is_anonymous:
return f"anonymous:{cache_versions[CacheName.PERMISSIONS]}"
return f"{user.permissions_id}:{cache_versions[CacheName.PERMISSIONS]}"
def build_user_permissions(user: Union["User", AnonymousUser]) -> dict:
if user.is_anonymous:
groups_ids = [DefaultGroupId.GUESTS]
else:
groups_ids = user.groups_ids
groups: list[Group] = list(Group.objects.filter(id__in=groups_ids))
permissions = build_user_permissions_hook(_build_user_permissions_action, groups)
permissions["categories"] = build_user_category_permissions(groups, permissions)
return permissions
def _build_user_permissions_action(groups: list[Group]) -> dict:
permissions = {
"can_use_private_threads": False,
"can_start_private_threads": False,
"private_thread_users_limit": 1,
"can_change_username": False,
"username_changes_limit": 0,
"username_changes_expire": 0,
"username_changes_span": 0,
"can_see_user_profiles": False,
"categories": {},
}
for group in groups:
if_true(
permissions,
"can_use_private_threads",
group.can_use_private_threads,
)
if_true(
permissions,
"can_start_private_threads",
group.can_start_private_threads,
)
if_greater(
permissions,
"private_thread_users_limit",
group.private_thread_users_limit,
)
if_true(
permissions,
"can_change_username",
group.can_change_username,
)
if_zero_or_greater(
permissions,
"username_changes_limit",
group.username_changes_limit,
)
if_zero_or_greater(
permissions,
"username_changes_expire",
group.username_changes_expire,
)
if_zero_or_greater(
permissions,
"username_changes_span",
group.username_changes_span,
)
if_true(
permissions,
"can_see_user_profiles",
group.can_see_user_profiles,
)
return permissions
def build_user_category_permissions(groups: list[Group], permissions: dict) -> dict:
categories: dict[int, Category] = {
category.id: category
for category in Category.objects.filter(
tree_id=CategoryTree.THREADS,
level__gt=0,
)
}
category_permissions_queryset = CategoryGroupPermission.objects.filter(
group__in=groups,
category__in=categories.values(),
).values_list("category_id", "permission")
category_permissions: dict[int, list[str]] = {}
for category_id, permission in category_permissions_queryset:
if category_id not in category_permissions:
category_permissions[category_id] = []
if permission not in category_permissions[category_id]:
category_permissions[category_id].append(permission)
return build_user_category_permissions_hook(
_build_user_category_permissions_action,
groups,
categories,
category_permissions,
permissions,
)
def _build_user_category_permissions_action(
groups: list[Group],
categories: dict[int, Category],
category_permissions: dict[int, list[str]],
user_permissions: dict,
) -> dict:
permissions = {
CategoryPermission.SEE: [],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
for category_id, category in categories.items():
# Skip category if we can't see its parent
if not can_see_parent_category(category, categories, permissions):
continue
# Skip category if we can't see it
perms = category_permissions.get(category_id, [])
if CategoryPermission.SEE not in perms:
continue
permissions[CategoryPermission.SEE].append(category_id)
if CategoryPermission.BROWSE in perms:
permissions[CategoryPermission.BROWSE].append(category_id)
else:
continue # Skip rest of permissions if we can't read its contents
if CategoryPermission.START in perms:
permissions[CategoryPermission.START].append(category_id)
if CategoryPermission.REPLY in perms:
permissions[CategoryPermission.REPLY].append(category_id)
if CategoryPermission.ATTACHMENTS in perms:
permissions[CategoryPermission.ATTACHMENTS].append(category_id)
return permissions
def can_see_parent_category(
category: Category,
categories: dict[int, Category],
permissions: dict,
) -> bool:
if category.level <= 1:
return True
if category.parent_id in permissions[CategoryPermission.BROWSE]:
return True
if category.parent_id in permissions[CategoryPermission.SEE]:
return categories[category.parent_id].delay_browse_check
return False
| 6,440
|
Python
|
.py
| 174
| 29.413793
| 88
| 0.667845
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,537
|
privatethreads.py
|
rafalp_Misago/misago/permissions/privatethreads.py
|
from django.core.exceptions import PermissionDenied
from django.db.models import QuerySet
from django.http import Http404
from django.utils.translation import pgettext
from ..threads.models import Thread, ThreadParticipant
from .hooks import (
check_private_threads_permission_hook,
check_see_private_thread_permission_hook,
check_start_private_threads_permission_hook,
filter_private_thread_posts_queryset_hook,
filter_private_threads_queryset_hook,
)
from .proxy import UserPermissionsProxy
def check_private_threads_permission(permissions: UserPermissionsProxy):
check_private_threads_permission_hook(
_check_private_threads_permission_action, permissions
)
def _check_private_threads_permission_action(permissions: UserPermissionsProxy):
if permissions.user.is_anonymous:
raise PermissionDenied(
pgettext(
"private threads permission error",
"You must be signed in to use private threads.",
)
)
if not permissions.can_use_private_threads:
raise PermissionDenied(
pgettext(
"private threads permission error",
"You can't use private threads.",
)
)
def check_start_private_threads_permission(permissions: UserPermissionsProxy):
check_start_private_threads_permission_hook(
_check_start_private_threads_permission_action, permissions
)
def _check_start_private_threads_permission_action(permissions: UserPermissionsProxy):
if not permissions.can_start_private_threads:
raise PermissionDenied(
pgettext(
"private threads permission error",
"You can't start new private threads.",
)
)
def check_see_private_thread_permission(
permissions: UserPermissionsProxy, thread: Thread
):
check_see_private_thread_permission_hook(
_check_see_private_thread_permission_action, permissions, thread
)
def _check_see_private_thread_permission_action(
permissions: UserPermissionsProxy, thread: Thread
):
check_private_threads_permission(permissions)
if permissions.user.id not in thread.participants_ids:
raise Http404()
def filter_private_threads_queryset(permissions: UserPermissionsProxy, queryset):
return filter_private_threads_queryset_hook(
_filter_private_threads_queryset_action, permissions, queryset
)
def _filter_private_threads_queryset_action(
permissions: UserPermissionsProxy, queryset
):
if permissions.user.is_anonymous:
return queryset.none()
return queryset.filter(
id__in=ThreadParticipant.objects.filter(user=permissions.user).values(
"thread_id"
)
)
def filter_private_thread_posts_queryset(
permissions: UserPermissionsProxy,
thread: Thread,
queryset: QuerySet,
) -> QuerySet:
return filter_private_thread_posts_queryset_hook(
_filter_private_thread_posts_queryset_action, permissions, thread, queryset
)
def _filter_private_thread_posts_queryset_action(
permissions: UserPermissionsProxy,
thread: Thread,
queryset: QuerySet,
) -> QuerySet:
return queryset
| 3,222
|
Python
|
.py
| 84
| 31.928571
| 86
| 0.728003
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,538
|
apps.py
|
rafalp_Misago/misago/permissions/apps.py
|
from django.apps import AppConfig
class MisagoPermissionsConfig(AppConfig):
name = "misago.permissions"
label = "misago_permissions"
verbose_name = "Misago Permissions"
| 183
|
Python
|
.py
| 5
| 32.8
| 41
| 0.778409
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,539
|
accounts.py
|
rafalp_Misago/misago/permissions/accounts.py
|
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
def check_delete_own_account_permission(user):
if user.is_misago_admin:
raise PermissionDenied(
pgettext(
"account permission error",
"You can't delete your account because you are an administrator.",
)
)
if user.is_staff:
raise PermissionDenied(
pgettext(
"account permission error",
"You can't delete your account because you are a staff user.",
)
)
| 605
|
Python
|
.py
| 17
| 25.470588
| 82
| 0.610256
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,540
|
copy.py
|
rafalp_Misago/misago/permissions/copy.py
|
from django.http import HttpRequest
from ..categories.models import Category
from ..postgres.delete import delete_all
from ..users.models import Group
from .hooks import copy_category_permissions_hook, copy_group_permissions_hook
from .models import CategoryGroupPermission
__all__ = ["copy_category_permissions", "copy_group_permissions"]
def copy_category_permissions(
src: Category,
dst: Category,
request: HttpRequest | None = None,
):
copy_category_permissions_hook(_copy_category_permissions_action, src, dst, request)
def _copy_category_permissions_action(
src: Category,
dst: Category,
request: HttpRequest | None = None,
) -> None:
delete_all(CategoryGroupPermission, category_id=dst.id)
queryset = CategoryGroupPermission.objects.filter(category=src).values_list(
"group_id", "permission"
)
copied_permissions = []
for group_id, permission in queryset:
copied_permissions.append(
CategoryGroupPermission(
category=dst,
group_id=group_id,
permission=permission,
)
)
if copied_permissions:
CategoryGroupPermission.objects.bulk_create(copied_permissions)
COPY_GROUP_PERMISSIONS = (
"can_use_private_threads",
"can_start_private_threads",
"private_thread_users_limit",
"can_change_username",
"username_changes_limit",
"username_changes_expire",
"username_changes_span",
"can_see_user_profiles",
)
def copy_group_permissions(
src: Group,
dst: Group,
request: HttpRequest | None = None,
) -> None:
copy_group_permissions_hook(_copy_group_permissions_action, src, dst, request)
for group_permission in COPY_GROUP_PERMISSIONS:
setattr(dst, group_permission, getattr(src, group_permission))
dst.save()
def _copy_group_permissions_action(
src: Group,
dst: Group,
request: HttpRequest | None = None,
) -> None:
_copy_group_category_permissions(src, dst)
def _copy_group_category_permissions(src: Group, dst: Group) -> None:
delete_all(CategoryGroupPermission, group_id=dst.id)
queryset = CategoryGroupPermission.objects.filter(group=src).values_list(
"category_id", "permission"
)
copied_permissions = []
for category_id, permission in queryset:
copied_permissions.append(
CategoryGroupPermission(
group=dst,
category_id=category_id,
permission=permission,
)
)
if copied_permissions:
CategoryGroupPermission.objects.bulk_create(copied_permissions)
| 2,633
|
Python
|
.py
| 74
| 29.364865
| 88
| 0.693733
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,541
|
permissionsid.py
|
rafalp_Misago/misago/permissions/permissionsid.py
|
from hashlib import md5
def get_permissions_id(groups_ids: list[int]):
return md5((".".join(map(str, groups_ids))).encode()).hexdigest()[:12]
| 148
|
Python
|
.py
| 3
| 46.333333
| 74
| 0.699301
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,542
|
admin.py
|
rafalp_Misago/misago/permissions/admin.py
|
from django.utils.translation import pgettext
from ..admin.views.generic import PermissionsFormView
from .enums import CategoryPermission
from .hooks import get_admin_category_permissions_hook
def get_admin_category_permissions(form: PermissionsFormView) -> list[dict]:
perms = [
form.create_permission(
id=CategoryPermission.SEE,
name=pgettext("category permission", "See category"),
help_text=pgettext(
"category permission", "See category on categories lists."
),
color="#eff6ff",
),
form.create_permission(
id=CategoryPermission.BROWSE,
name=pgettext("category permission", "Browse contents"),
color="#f5f3ff",
),
form.create_permission(
id=CategoryPermission.START,
name=pgettext("category permission", "Start threads"),
color="#fef2f2",
),
form.create_permission(
id=CategoryPermission.REPLY,
name=pgettext("category permission", "Reply threads"),
color="#fefce8",
),
form.create_permission(
id=CategoryPermission.ATTACHMENTS,
name=pgettext("category permission", "Attachments"),
help_text=pgettext(
"category permission", "Upload and download attachments."
),
color="#ecfdf5",
),
]
perms += get_admin_category_permissions_hook(form)
return perms
| 1,514
|
Python
|
.py
| 40
| 27.825
| 76
| 0.613342
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,543
|
panels.py
|
rafalp_Misago/misago/permissions/panels.py
|
from debug_toolbar.panels import Panel
from django.utils.translation import pgettext_lazy
class MisagoUserPermissionsPanel(Panel):
"""Panel that displays current user's permission"""
title = pgettext_lazy("debug toolbar", "Misago User Permissions")
nav_title = pgettext_lazy("debug toolbar", "Misago Permissions")
template = "misago/permissions_panel.html"
@property
def nav_subtitle(self):
misago_user = self.get_stats().get("misago_user")
if misago_user and misago_user.is_authenticated:
return misago_user.username
return pgettext_lazy("debug toolbar", "Anonymous user")
def generate_stats(self, request, response):
try:
misago_user = request.user
except AttributeError:
misago_user = None
try:
misago_permissions = request.user_permissions
except AttributeError:
misago_permissions = None
self.record_stats(
{
"misago_user": misago_user,
"misago_permissions": misago_permissions,
}
)
| 1,112
|
Python
|
.py
| 28
| 30.714286
| 69
| 0.648699
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,544
|
operations.py
|
rafalp_Misago/misago/permissions/operations.py
|
from typing import Any
def if_true(permissions: dict[str, Any], permission: str, value: bool):
if value is True:
permissions[permission] = True
def if_false(permissions: dict[str, Any], permission: str, value: bool):
if value is False:
permissions[permission] = False
def if_zero_or_greater(permissions: dict[str, Any], permission: str, value: int):
if value == 0 or value > permissions[permission]:
permissions[permission] = value
def if_greater(permissions: dict[str, Any], permission: str, value: int):
if value > permissions[permission]:
permissions[permission] = value
def if_lesser(permissions: dict[str, Any], permission: str, value: int):
if value < permissions[permission]:
permissions[permission] = value
| 785
|
Python
|
.py
| 16
| 43.6875
| 81
| 0.710145
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,545
|
categories.py
|
rafalp_Misago/misago/permissions/categories.py
|
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.translation import pgettext
from ..categories.models import Category
from .enums import CategoryPermission
from .hooks import (
check_browse_category_permission_hook,
check_see_category_permission_hook,
)
from .proxy import UserPermissionsProxy
def check_see_category_permission(
permissions: UserPermissionsProxy,
category: Category,
):
check_see_category_permission_hook(
_check_see_category_permission_action, permissions, category
)
def _check_see_category_permission_action(
permissions: UserPermissionsProxy,
category: Category,
):
if category.id not in permissions.categories[CategoryPermission.SEE]:
raise Http404()
def check_browse_category_permission(
permissions: UserPermissionsProxy,
category: Category,
can_delay: bool = False,
):
check_browse_category_permission_hook(
_check_browse_category_permission_action,
permissions,
category,
can_delay,
)
def _check_browse_category_permission_action(
permissions: UserPermissionsProxy,
category: Category,
can_delay: bool = False,
):
check_see_category_permission(permissions, category)
if category.id not in permissions.categories[CategoryPermission.BROWSE] and not (
can_delay and category.delay_browse_check
):
raise PermissionDenied(
pgettext(
"category permission error",
"You can't browse the contents of this category.",
)
)
| 1,609
|
Python
|
.py
| 49
| 27.387755
| 85
| 0.731613
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,546
|
0002_default_category_permissions.py
|
rafalp_Misago/misago/permissions/migrations/0002_default_category_permissions.py
|
# Generated by Django 4.2.7 on 2023-12-21 22:37
from django.db import migrations
from ...users.enums import DefaultGroupId
from ..enums import CategoryPermission
CATEGORY_PERMISSIONS = (
CategoryPermission.SEE,
CategoryPermission.BROWSE,
CategoryPermission.START,
CategoryPermission.REPLY,
CategoryPermission.ATTACHMENTS,
)
GROUPS_PERMISSIONS = {
DefaultGroupId.ADMINS: CATEGORY_PERMISSIONS,
DefaultGroupId.MODERATORS: CATEGORY_PERMISSIONS,
DefaultGroupId.MEMBERS: CATEGORY_PERMISSIONS,
DefaultGroupId.GUESTS: CATEGORY_PERMISSIONS,
}
def create_default_category_permissions(apps, schema_editor):
Permission = apps.get_model("misago_permissions", "CategoryGroupPermission")
Category = apps.get_model("misago_categories", "Category")
try:
category = Category.objects.get(slug="first-category")
except Category.DoesNotExist:
return
bulk_create_data: list[Permission] = []
for group_id, group_permissions in GROUPS_PERMISSIONS.items():
for permission in group_permissions:
bulk_create_data.append(
Permission(
category_id=category.id,
group_id=group_id,
permission=permission,
)
)
Permission.objects.bulk_create(bulk_create_data)
class Migration(migrations.Migration):
dependencies = [
("misago_permissions", "0001_initial"),
]
operations = [
migrations.RunPython(
create_default_category_permissions,
migrations.RunPython.noop,
),
]
| 1,611
|
Python
|
.py
| 45
| 28.555556
| 80
| 0.690277
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,547
|
0001_initial.py
|
rafalp_Misago/misago/permissions/migrations/0001_initial.py
|
# Generated by Django 4.2.7 on 2023-12-21 21:41
from django.conf import settings
from django.db import migrations, models
import django.contrib.postgres.fields
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("misago_users", "0029_users_permissions_nonnull"),
("misago_categories", "0012_categories_trees_ids"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="CategoryGroupPermission",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("permission", models.CharField(max_length=32)),
(
"category",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="misago_categories.category",
),
),
(
"group",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="misago_users.group",
),
),
],
),
migrations.CreateModel(
name="Moderator",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("is_global", models.BooleanField(default=True)),
(
"categories",
django.contrib.postgres.fields.ArrayField(
base_field=models.PositiveIntegerField(),
default=list,
size=None,
),
),
("private_threads", models.BooleanField(default=False)),
(
"group",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="misago_users.group",
),
),
(
"user",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| 2,881
|
Python
|
.py
| 83
| 17.457831
| 72
| 0.408879
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,548
|
0003_default_moderators.py
|
rafalp_Misago/misago/permissions/migrations/0003_default_moderators.py
|
# Generated by Django 4.2.8 on 2024-01-02 12:10
from django.db import migrations
from ...users.enums import DefaultGroupId
DEFAULT_MODERATOR_GROUPS = (DefaultGroupId.ADMINS, DefaultGroupId.MODERATORS)
def create_default_moderators(apps, schema_editor):
Moderator = apps.get_model("misago_permissions", "Moderator")
for group_id in DEFAULT_MODERATOR_GROUPS:
Moderator.objects.create(
group_id=group_id,
is_global=True,
)
class Migration(migrations.Migration):
dependencies = [
("misago_permissions", "0002_default_category_permissions"),
]
operations = [
migrations.RunPython(
create_default_moderators,
migrations.RunPython.noop,
),
]
| 757
|
Python
|
.py
| 21
| 29.238095
| 77
| 0.688705
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,549
|
conftest.py
|
rafalp_Misago/misago/permissions/tests/conftest.py
|
import pytest
from ...categories.models import Category
from ...categories.proxy import CategoriesProxy
from ...threads.test import post_thread
from ...users.test import create_test_user
from ..enums import CategoryPermission
from ..models import CategoryGroupPermission, Moderator
from ..proxy import UserPermissionsProxy
from ..threads import CategoryThreadsQuerysetFilter, ThreadsQuerysetFilter
@pytest.fixture
def threads_filter_factory(cache_versions):
def filter_factory_function(user):
permissions = UserPermissionsProxy(user, cache_versions)
categories = CategoriesProxy(permissions, cache_versions)
return ThreadsQuerysetFilter(permissions, categories.categories_list)
return filter_factory_function
@pytest.fixture
def category_threads_filter_factory(cache_versions):
def filter_factory_function(user, category):
permissions = UserPermissionsProxy(user, cache_versions)
categories = CategoriesProxy(permissions, cache_versions)
categories_data = categories.get_category_descendants(category.id)
return CategoryThreadsQuerysetFilter(
permissions,
categories.categories_list,
current_category=categories_data[0],
child_categories=categories_data[1:],
include_children=category.list_children_threads,
)
return filter_factory_function
@pytest.fixture
def category(root_category):
category = Category(name="Parent", slug="parent")
category.insert_at(root_category, position="last-child", save=True)
return category
@pytest.fixture
def child_category(category):
child_category = Category(name="Child", slug="child")
child_category.insert_at(category, position="last-child", save=True)
return child_category
@pytest.fixture
def sibling_category(root_category):
sibling_category = Category(name="Sibling", slug="sibling")
sibling_category.insert_at(root_category, position="last-child", save=True)
return sibling_category
@pytest.fixture
def category_guests_see_permission(category, guests_group):
return CategoryGroupPermission.objects.create(
category=category,
group=guests_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def category_guests_browse_permission(category, guests_group):
return CategoryGroupPermission.objects.create(
category=category,
group=guests_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def category_members_see_permission(category, members_group):
return CategoryGroupPermission.objects.create(
category=category,
group=members_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def category_members_browse_permission(category, members_group):
return CategoryGroupPermission.objects.create(
category=category,
group=members_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def category_moderators_see_permission(category, moderators_group):
return CategoryGroupPermission.objects.create(
category=category,
group=moderators_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def category_moderators_browse_permission(category, moderators_group):
return CategoryGroupPermission.objects.create(
category=category,
group=moderators_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def category_custom_see_permission(category, custom_group):
return CategoryGroupPermission.objects.create(
category=category,
group=custom_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def category_custom_browse_permission(category, custom_group):
return CategoryGroupPermission.objects.create(
category=category,
group=custom_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def child_category_guests_see_permission(child_category, guests_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=guests_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def child_category_guests_browse_permission(child_category, guests_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=guests_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def child_category_members_see_permission(child_category, members_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=members_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def child_category_members_browse_permission(child_category, members_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=members_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def child_category_moderators_see_permission(child_category, moderators_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=moderators_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def child_category_moderators_browse_permission(child_category, moderators_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=moderators_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def child_category_custom_see_permission(child_category, custom_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=custom_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def child_category_custom_browse_permission(child_category, custom_group):
return CategoryGroupPermission.objects.create(
category=child_category,
group=custom_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def sibling_category_guests_see_permission(sibling_category, guests_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=guests_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def sibling_category_guests_browse_permission(sibling_category, guests_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=guests_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def sibling_category_members_see_permission(sibling_category, members_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=members_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def sibling_category_members_browse_permission(sibling_category, members_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=members_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def sibling_category_moderators_see_permission(sibling_category, moderators_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=moderators_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def sibling_category_moderators_browse_permission(sibling_category, moderators_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=moderators_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def sibling_category_custom_group_see_permission(sibling_category, custom_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=custom_group,
permission=CategoryPermission.SEE,
)
@pytest.fixture
def sibling_category_custom_group_browse_permission(sibling_category, custom_group):
return CategoryGroupPermission.objects.create(
category=sibling_category,
group=custom_group,
permission=CategoryPermission.BROWSE,
)
@pytest.fixture
def category_moderator(user, user_password, category, child_category):
user = create_test_user(
"CategoryModerator", "catmoderator@example.com", user_password
)
Moderator.objects.create(
user=user,
categories=[category.id, child_category.id],
)
return user
@pytest.fixture
def category_thread(category):
return post_thread(category, title="Category Thread")
@pytest.fixture
def category_pinned_thread(category):
return post_thread(category, title="Category Pinned Thread", is_pinned=True)
@pytest.fixture
def category_pinned_globally_thread(category):
return post_thread(category, title="Category Global Thread", is_global=True)
@pytest.fixture
def child_category_thread(child_category):
return post_thread(child_category, title="Child Thread")
@pytest.fixture
def child_category_pinned_thread(child_category):
return post_thread(child_category, title="Child Pinned Thread", is_pinned=True)
@pytest.fixture
def child_category_pinned_globally_thread(child_category):
return post_thread(child_category, title="Child Global Thread", is_global=True)
@pytest.fixture
def sibling_category_thread(sibling_category):
return post_thread(sibling_category, title="Sibling Thread")
@pytest.fixture
def sibling_category_pinned_thread(sibling_category):
return post_thread(sibling_category, title="Sibling Pinned Thread", is_pinned=True)
@pytest.fixture
def sibling_category_pinned_globally_thread(sibling_category):
return post_thread(sibling_category, title="Sibling Global Thread", is_global=True)
@pytest.fixture
def category_user_thread(category, user):
return post_thread(category, title="Category Thread", poster=user)
@pytest.fixture
def child_category_user_thread(child_category, user):
return post_thread(child_category, title="Child Thread", poster=user)
@pytest.fixture
def sibling_category_user_thread(sibling_category, user):
return post_thread(sibling_category, title="Sibling Thread", poster=user)
| 10,152
|
Python
|
.py
| 259
| 33.849421
| 87
| 0.765276
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,550
|
test_thread_posts_queryset_filter.py
|
rafalp_Misago/misago/permissions/tests/test_thread_posts_queryset_filter.py
|
from ..models import Moderator
from ..proxy import UserPermissionsProxy
from ..threads import filter_thread_posts_queryset
def test_filter_thread_posts_queryset_shows_reply_to_anonymous_user(
cache_versions, anonymous_user, thread, post, reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert reply in queryset
def test_filter_thread_posts_queryset_shows_reply_to_user(
cache_versions, user, thread, post, reply
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert reply in queryset
def test_filter_thread_posts_queryset_shows_users_reply_to_anonymous_user(
cache_versions, anonymous_user, thread, post, user_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_reply in queryset
def test_filter_thread_posts_queryset_shows_users_own_reply_to_user(
cache_versions, user, thread, post, user_reply
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_reply in queryset
def test_filter_thread_posts_queryset_shows_other_users_reply_to_user(
cache_versions, user, thread, post, other_user_reply
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert other_user_reply in queryset
def test_filter_thread_posts_queryset_shows_hidden_post_to_anonymous_user(
cache_versions, anonymous_user, thread, post, hidden_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert hidden_reply in queryset
def test_filter_thread_posts_queryset_shows_users_hidden_post_to_anonymous_user(
cache_versions, anonymous_user, thread, post, user_hidden_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_hidden_reply in queryset
def test_filter_thread_posts_queryset_shows_hidden_post_to_user(
cache_versions, anonymous_user, thread, post, hidden_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert hidden_reply in queryset
def test_filter_thread_posts_queryset_shows_users_own_hidden_post_to_user(
cache_versions, anonymous_user, thread, post, user_hidden_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_hidden_reply in queryset
def test_filter_thread_posts_queryset_shows_other_users_hidden_post_to_user(
cache_versions, anonymous_user, thread, post, other_user_hidden_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert other_user_hidden_reply in queryset
def test_filter_thread_posts_queryset_hides_unapproved_post_from_anonymous_user(
cache_versions, anonymous_user, thread, post, unapproved_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert unapproved_reply not in queryset
def test_filter_thread_posts_queryset_hides_users_unapproved_post_from_anonymous_user(
cache_versions, anonymous_user, thread, post, user_unapproved_reply
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_unapproved_reply not in queryset
def test_filter_thread_posts_queryset_hides_unapproved_post_from_user(
cache_versions, user, thread, post, unapproved_reply
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert unapproved_reply not in queryset
def test_filter_thread_posts_queryset_hides_other_users_unapproved_post_from_user(
cache_versions, user, thread, post, other_user_unapproved_reply
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert other_user_unapproved_reply not in queryset
def test_filter_thread_posts_queryset_shows_users_own_unapproved_post_to_user(
cache_versions, user, thread, post, user_unapproved_reply
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_unapproved_reply in queryset
def test_filter_thread_posts_queryset_shows_unapproved_post_to_global_moderator(
cache_versions, moderator, thread, post, unapproved_reply
):
permissions = UserPermissionsProxy(moderator, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert unapproved_reply in queryset
def test_filter_thread_posts_queryset_shows_users_own_unapproved_post_to_global_moderator(
cache_versions, moderator, thread, post, unapproved_reply
):
unapproved_reply.poster = moderator
unapproved_reply.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert unapproved_reply in queryset
def test_filter_thread_posts_queryset_shows_other_users_unapproved_post_to_global_moderator(
cache_versions, moderator, thread, post, other_user_unapproved_reply
):
permissions = UserPermissionsProxy(moderator, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert other_user_unapproved_reply in queryset
def test_filter_thread_posts_queryset_shows_unapproved_post_to_category_moderator(
cache_versions, user, thread, post, unapproved_reply
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[thread.category_id],
)
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert unapproved_reply in queryset
def test_filter_thread_posts_queryset_shows_users_own_unapproved_post_to_category_moderator(
cache_versions, user, thread, post, user_unapproved_reply
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[thread.category_id],
)
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert user_unapproved_reply in queryset
def test_filter_thread_posts_queryset_shows_other_users_unapproved_post_to_category_moderator(
cache_versions, user, thread, post, other_user_unapproved_reply
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[thread.category_id],
)
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_thread_posts_queryset(
permissions, thread, thread.post_set.order_by("id")
)
assert post in queryset
assert other_user_unapproved_reply in queryset
| 8,830
|
Python
|
.py
| 209
| 37.215311
| 94
| 0.749591
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,551
|
test_copy_group_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_copy_group_permissions.py
|
import pytest
from ..copy import copy_group_permissions
from ..models import CategoryGroupPermission
def test_copy_group_permissions_copies_group_permissions(members_group, custom_group):
assert not custom_group.can_see_user_profiles
copy_group_permissions(members_group, custom_group)
assert custom_group.can_see_user_profiles
custom_group.refresh_from_db()
assert custom_group.can_see_user_profiles
def test_copy_group_permissions_copies_category_permission(
members_group, custom_group, other_category
):
CategoryGroupPermission.objects.create(
group=members_group,
category=other_category,
permission="test",
)
copy_group_permissions(members_group, custom_group)
CategoryGroupPermission.objects.get(
group=custom_group,
category=other_category,
permission="test",
)
def test_copy_group_permissions_deletes_previous_category_permission(
members_group, custom_group, other_category
):
CategoryGroupPermission.objects.create(
group=custom_group,
category=other_category,
permission="deleted",
)
copy_group_permissions(members_group, custom_group)
with pytest.raises(CategoryGroupPermission.DoesNotExist):
CategoryGroupPermission.objects.get(
group=custom_group,
category=other_category,
permission="deleted",
)
| 1,414
|
Python
|
.py
| 38
| 30.894737
| 86
| 0.734949
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,552
|
test_permissions_id.py
|
rafalp_Misago/misago/permissions/tests/test_permissions_id.py
|
from ..permissionsid import get_permissions_id
def test_permissions_id_is_created_from_groups_ids():
assert get_permissions_id([1])
assert get_permissions_id([1, 6, 9])
def test_permissions_id_is_stable():
assert get_permissions_id([1]) == get_permissions_id([1])
assert get_permissions_id([1, 6, 9]) == get_permissions_id([1, 6, 9])
assert get_permissions_id([1]) != get_permissions_id([1, 6, 9])
| 422
|
Python
|
.py
| 8
| 48.75
| 73
| 0.690244
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,553
|
test_threads_queryset_filter.py
|
rafalp_Misago/misago/permissions/tests/test_threads_queryset_filter.py
|
from itertools import product
from ...categories.proxy import CategoriesProxy
from ...threads.enums import ThreadWeight
from ...threads.models import Thread
from ...threads.test import post_thread
from ..proxy import UserPermissionsProxy
from ..threads import filter_category_threads_queryset
def test_threads_queryset_includes_category_with_see_and_browse_permission(
threads_filter_factory,
category_thread,
category_members_see_permission,
category_members_browse_permission,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter(Thread.objects)
assert category_thread in queryset
def test_threads_queryset_includes_category_with_see_permission_and_delay_browse(
threads_filter_factory,
category,
category_thread,
category_members_see_permission,
user,
):
category.delay_browse_check = True
category.save()
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter(Thread.objects)
assert category_thread in queryset
def test_threads_queryset_excludes_category_without_any_permissions(
threads_filter_factory,
category_thread,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter(Thread.objects)
assert not queryset.exists()
def test_threads_queryset_excludes_category_with_only_see_permission(
threads_filter_factory,
category_thread,
category_members_see_permission,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter(Thread.objects)
assert not queryset.exists()
def test_threads_queryset_combines_multiple_categories_with_see_and_browse_permission(
threads_filter_factory,
category_thread,
child_category_thread,
category_members_see_permission,
category_members_browse_permission,
child_category_members_see_permission,
child_category_members_browse_permission,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter(Thread.objects)
assert category_thread in queryset
assert child_category_thread in queryset
def test_threads_queryset_filter(
threads_filter_factory,
category,
child_category,
moderator,
category_moderator,
anonymous_user,
user,
other_user,
category_guests_see_permission,
category_guests_browse_permission,
category_members_see_permission,
category_members_browse_permission,
category_moderators_see_permission,
category_moderators_browse_permission,
child_category_guests_see_permission,
child_category_guests_browse_permission,
child_category_members_see_permission,
child_category_members_browse_permission,
child_category_moderators_see_permission,
child_category_moderators_browse_permission,
):
MATRIX = (
(moderator, category_moderator, anonymous_user, user, other_user),
(category, child_category),
(False, True),
(anonymous_user, user, other_user),
(0, 1, 2),
(False, True),
(False, True),
)
for args in product(*MATRIX):
check_thread_visibility(threads_filter_factory, *args)
def check_thread_visibility(
threads_filter_factory,
user,
category,
started_only,
poster,
thread_weight,
thread_hidden,
thread_unapproved,
):
if category.show_started_only != started_only:
category.show_started_only = started_only
category.save()
thread = post_thread(
category,
poster=poster if poster.is_authenticated else "Anon",
is_global=thread_weight == 2,
is_pinned=thread_weight == 1,
is_hidden=thread_hidden,
is_unapproved=thread_unapproved,
)
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter(Thread.objects)
if thread in queryset:
assert_queryset_contains(user, category, thread)
else:
assert_queryset_not_contains(user, category, thread)
thread.delete()
def assert_queryset_contains(user, category, thread):
if thread.weight == ThreadWeight.PINNED_GLOBALLY:
raise AssertionError(f"queryset result contains a globally pinned thread")
if user.id and (user.slug == "moderator" or user.slug == "categorymoderator"):
return
if thread.is_hidden:
raise AssertionError(
"queryset result for a user without moderator permissions contains "
"a hidden thread"
)
if user.is_anonymous and thread.is_unapproved:
raise AssertionError(
"queryset result for an anonymous user contains an unapproved thread"
)
if (
user.is_anonymous
and category.show_started_only
and thread.weight != ThreadWeight.PINNED_IN_CATEGORY
):
raise AssertionError(
"queryset result for an anonymous user and category with "
"show_started_only=true contains a thread that's not pinned in category"
)
if user.is_authenticated and thread.is_unapproved and thread.starter_id != user.id:
raise AssertionError(
"queryset result for a user without moderator permissions contains "
"an unapproved thread started by a different user"
)
if (
user.is_authenticated
and category.show_started_only
and not thread.weight
and thread.starter_id != user.id
):
raise AssertionError(
"queryset result for a category with show_started_only=true "
"contains not pinned thread that's not started by the user"
)
def assert_queryset_not_contains(user, category, thread):
if thread.weight == ThreadWeight.PINNED_GLOBALLY:
return
if user.is_authenticated and (
user.slug == "moderator" or user.slug == "categorymoderator"
):
raise AssertionError("queryset result for a moderator is missing a thread")
if thread.is_hidden:
return
if user.is_anonymous and thread.is_unapproved:
return
if user.is_authenticated and thread.is_unapproved and thread.starter_id == user.id:
raise AssertionError(
"queryset result for a user without moderator permissions is missing "
"an unapproved thread started by them"
)
if (
user.is_authenticated
and category.show_started_only
and thread.starter_id == user.id
):
raise AssertionError(
"queryset result for a user is missing a thread started by them"
)
def test_threads_pinned_queryset_includes_category_with_see_and_browse_permission(
threads_filter_factory,
category_pinned_globally_thread,
category_members_see_permission,
category_members_browse_permission,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter_pinned(Thread.objects)
assert category_pinned_globally_thread in queryset
def test_threads_pinned_queryset_includes_category_with_see_permission_and_delay_browse(
threads_filter_factory,
category,
category_pinned_globally_thread,
category_members_see_permission,
user,
):
category.delay_browse_check = True
category.save()
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter_pinned(Thread.objects)
assert category_pinned_globally_thread in queryset
def test_threads_pinned_queryset_excludes_category_without_any_permissions(
threads_filter_factory,
category_pinned_globally_thread,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter_pinned(Thread.objects)
assert not queryset.exists()
def test_threads_pinned_queryset_excludes_category_with_only_see_permission(
threads_filter_factory,
category_pinned_globally_thread,
category_members_see_permission,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter_pinned(Thread.objects)
assert not queryset.exists()
def test_threads_pinned_queryset_combines_multiple_categories_with_see_and_browse_permission(
threads_filter_factory,
category_pinned_globally_thread,
child_category_pinned_globally_thread,
category_members_see_permission,
category_members_browse_permission,
child_category_members_see_permission,
child_category_members_browse_permission,
user,
):
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter_pinned(Thread.objects)
assert category_pinned_globally_thread in queryset
assert child_category_pinned_globally_thread in queryset
def test_threads_queryset_filter_pinned(
threads_filter_factory,
category,
child_category,
moderator,
category_moderator,
anonymous_user,
user,
other_user,
category_guests_see_permission,
category_guests_browse_permission,
category_members_see_permission,
category_members_browse_permission,
category_moderators_see_permission,
category_moderators_browse_permission,
child_category_guests_see_permission,
child_category_guests_browse_permission,
child_category_members_see_permission,
child_category_members_browse_permission,
child_category_moderators_see_permission,
child_category_moderators_browse_permission,
):
MATRIX = (
(moderator, category_moderator, anonymous_user, user, other_user),
(category, child_category),
(False, True),
(anonymous_user, user, other_user),
(0, 1, 2),
(False, True),
(False, True),
)
for args in product(*MATRIX):
check_pinned_thread_visibility(threads_filter_factory, *args)
def check_pinned_thread_visibility(
threads_filter_factory,
user,
category,
started_only,
poster,
thread_weight,
thread_hidden,
thread_unapproved,
):
if category.show_started_only != started_only:
category.show_started_only = started_only
category.save()
thread = post_thread(
category,
poster=poster if poster.is_authenticated else "Anon",
is_global=thread_weight == 2,
is_pinned=thread_weight == 1,
is_hidden=thread_hidden,
is_unapproved=thread_unapproved,
)
threads_filter = threads_filter_factory(user)
queryset = threads_filter.filter_pinned(Thread.objects)
if thread in queryset:
assert_pinned_queryset_contains(user, category, thread)
else:
assert_pinned_queryset_not_contains(user, category, thread)
thread.delete()
def assert_pinned_queryset_contains(user, category, thread):
if thread.weight != ThreadWeight.PINNED_GLOBALLY:
raise AssertionError(
"pinned queryset result contains a thread that's not pinned globally"
)
if user.id and (user.slug == "moderator" or user.slug == "categorymoderator"):
return
if thread.is_hidden:
raise AssertionError(
"pinned queryset result for a user without moderator permissions "
"contains a hidden thread"
)
if user.is_anonymous and thread.is_unapproved:
raise AssertionError(
"pinned queryset result for an anonymous user contains an unapproved thread"
)
if user.is_authenticated and thread.is_unapproved and thread.starter_id != user.id:
raise AssertionError(
"queryset result for a user without moderator permissions contains "
"an unapproved thread started by a different user"
)
def assert_pinned_queryset_not_contains(user, category, thread):
if thread.weight != ThreadWeight.PINNED_GLOBALLY:
return
if user.is_authenticated and (
user.slug == "moderator" or user.slug == "categorymoderator"
):
raise AssertionError("queryset result for a moderator is missing a thread")
if thread.is_hidden:
return
if user.is_anonymous and thread.is_unapproved:
return
if user.is_authenticated and thread.is_unapproved and thread.starter_id == user.id:
raise AssertionError(
"pinned queryset result for a user without moderator permissions "
"is missing an unapproved thread started by them"
)
if (
user.is_authenticated
and category.show_started_only
and thread.starter_id == user.id
):
raise AssertionError(
"pinned queryset result for a user is missing a thread started by them"
)
def test_filter_category_threads_queryset(
cache_versions,
category,
moderator,
category_moderator,
anonymous_user,
user,
other_user,
category_guests_see_permission,
category_guests_browse_permission,
category_members_see_permission,
category_members_browse_permission,
category_moderators_see_permission,
category_moderators_browse_permission,
):
MATRIX = (
(moderator, category_moderator, anonymous_user, user, other_user),
(False, True),
(anonymous_user, user, other_user),
(0, 1, 2),
(False, True),
(False, True),
)
for args in product(*MATRIX):
check_category_thread_visibility(cache_versions, category, *args)
def check_category_thread_visibility(
cache_versions,
category,
user,
started_only,
poster,
thread_weight,
thread_hidden,
thread_unapproved,
):
permissions = UserPermissionsProxy(user, cache_versions)
categories = CategoriesProxy(permissions, cache_versions)
if category.show_started_only != started_only:
category.show_started_only = started_only
category.save()
thread = post_thread(
category,
poster=poster if poster.is_authenticated else "Anon",
is_global=thread_weight == 2,
is_pinned=thread_weight == 1,
is_hidden=thread_hidden,
is_unapproved=thread_unapproved,
)
queryset = filter_category_threads_queryset(
permissions, categories.categories[category.id], category.thread_set
)
if thread in queryset:
assert_category_threads_queryset_contains(user, category, thread)
else:
assert_category_threads_queryset_not_contains(user, category, thread)
thread.delete()
def assert_category_threads_queryset_contains(user, category, thread):
if user.is_authenticated and (
user.slug == "moderator" or user.slug == "categorymoderator"
):
return
if thread.is_hidden:
raise AssertionError(
"category threads queryset result for a user without moderator permissions "
"contains a hidden thread"
)
if user.is_anonymous and thread.is_unapproved:
raise AssertionError(
"category threads queryset result for an anonymous user contains "
"an unapproved thread"
)
if user.is_authenticated and thread.is_unapproved and thread.starter_id != user.id:
raise AssertionError(
"category threads queryset result for a user without moderator permissions "
"contains an unapproved thread started by a different user"
)
def assert_category_threads_queryset_not_contains(user, category, thread):
if user.is_authenticated and (
user.slug == "moderator" or user.slug == "categorymoderator"
):
raise AssertionError(
"category threads queryset result for a moderator is missing a thread"
)
if thread.is_hidden:
return
if user.is_anonymous and thread.is_unapproved:
return
if user.is_authenticated and thread.is_unapproved and thread.starter_id == user.id:
raise AssertionError(
"category threads queryset result for a user without moderator "
"permissions is missing an unapproved thread started by them"
)
if (
user.is_authenticated
and category.show_started_only
and thread.starter_id == user.id
):
raise AssertionError(
"category threads queryset result for a user is missing a thread started by them"
)
| 16,191
|
Python
|
.py
| 442
| 30.138009
| 93
| 0.703595
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,554
|
test_categories_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_categories_permissions.py
|
import pytest
from django.core.exceptions import PermissionDenied
from django.http import Http404
from ...categories.models import Category
from ...testutils import grant_category_group_permissions
from ..categories import (
PermissionDenied,
check_browse_category_permission,
check_see_category_permission,
)
from ..enums import CategoryPermission
from ..proxy import UserPermissionsProxy
def test_check_see_category_permission_passes_if_user_has_permission(
user, root_category, cache_versions
):
category = Category(name="Category", slug="category")
category.insert_at(root_category, position="last-child", save=True)
grant_category_group_permissions(category, user.group, CategoryPermission.SEE)
permissions = UserPermissionsProxy(user, cache_versions)
check_see_category_permission(permissions, category)
def test_check_see_category_permission_fails_if_user_has_no_permission(
user, root_category, cache_versions
):
category = Category(name="Category", slug="category")
category.insert_at(root_category, position="last-child", save=True)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_category_permission(permissions, category)
def test_check_see_category_permission_passes_if_user_can_browse_parent_category(
user, root_category, cache_versions
):
parent_category = Category(name="Category", slug="category")
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
parent_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
grant_category_group_permissions(child_category, user.group, CategoryPermission.SEE)
permissions = UserPermissionsProxy(user, cache_versions)
check_see_category_permission(permissions, child_category)
def test_check_see_category_permission_passes_if_user_can_browse_parent_category_with_delay(
user, root_category, cache_versions
):
parent_category = Category(
name="Category", slug="category", delay_browse_check=True
)
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
parent_category, user.group, CategoryPermission.SEE
)
grant_category_group_permissions(child_category, user.group, CategoryPermission.SEE)
permissions = UserPermissionsProxy(user, cache_versions)
check_see_category_permission(permissions, child_category)
def test_check_see_category_permission_fails_if_user_cant_browse_parent_category(
user, root_category, cache_versions
):
parent_category = Category(
name="Category", slug="category", delay_browse_check=True
)
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(child_category, user.group, CategoryPermission.SEE)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_category_permission(permissions, child_category)
def test_check_browse_category_permission_passes_if_user_has_see_and_browse_permissions(
user, root_category, cache_versions
):
category = Category(name="Category", slug="category")
category.insert_at(root_category, position="last-child", save=True)
grant_category_group_permissions(
category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
permissions = UserPermissionsProxy(user, cache_versions)
check_browse_category_permission(permissions, category)
def test_check_browse_category_permission_fails_if_user_has_no_permissions(
user, root_category, cache_versions
):
category = Category(name="Category", slug="category")
category.insert_at(root_category, position="last-child", save=True)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_browse_category_permission(permissions, category)
def test_check_browse_category_permission_fails_if_user_has_no_browse_permission(
user, root_category, cache_versions
):
category = Category(name="Category", slug="category")
category.insert_at(root_category, position="last-child", save=True)
grant_category_group_permissions(category, user.group, CategoryPermission.SEE)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_browse_category_permission(permissions, category)
def test_check_browse_category_permission_fails_if_user_has_only_browse_permission(
user, root_category, cache_versions
):
category = Category(name="Category", slug="category")
category.insert_at(root_category, position="last-child", save=True)
grant_category_group_permissions(category, user.group, CategoryPermission.BROWSE)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_browse_category_permission(permissions, category)
def test_check_browse_category_permission_passes_if_user_can_browse_parent_category(
user, root_category, cache_versions
):
parent_category = Category(name="Category", slug="category")
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
parent_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
grant_category_group_permissions(
child_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
permissions = UserPermissionsProxy(user, cache_versions)
check_see_category_permission(permissions, child_category)
def test_check_browse_category_permission_passes_if_user_can_browse_parent_category_with_delay(
user, root_category, cache_versions
):
parent_category = Category(
name="Category", slug="category", delay_browse_check=True
)
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
parent_category, user.group, CategoryPermission.SEE
)
grant_category_group_permissions(
child_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
permissions = UserPermissionsProxy(user, cache_versions)
check_see_category_permission(permissions, child_category)
def test_check_browse_category_permission_fails_if_user_cant_see_parent(
user, root_category, cache_versions
):
parent_category = Category(name="Category", slug="category")
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
child_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_category_permission(permissions, child_category)
def test_check_browse_category_permission_fails_if_user_cant_see_parent(
user, root_category, cache_versions
):
parent_category = Category(name="Category", slug="category")
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
child_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_category_permission(permissions, child_category)
def test_check_browse_category_permission_fails_if_user_cant_browse_parent(
user, root_category, cache_versions
):
parent_category = Category(name="Category", slug="category")
parent_category.insert_at(root_category, position="last-child", save=True)
child_category = Category(name="Child Category", slug="child-category")
child_category.insert_at(parent_category, position="last-child", save=True)
grant_category_group_permissions(
parent_category, user.group, CategoryPermission.SEE
)
grant_category_group_permissions(
child_category, user.group, CategoryPermission.SEE, CategoryPermission.BROWSE
)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_category_permission(permissions, child_category)
| 9,394
|
Python
|
.py
| 179
| 47.391061
| 95
| 0.765948
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,555
|
test_threads_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_threads_permissions.py
|
import pytest
from django.core.exceptions import PermissionDenied
from django.http import Http404
from ..enums import CategoryPermission
from ..models import CategoryGroupPermission, Moderator
from ..proxy import UserPermissionsProxy
from ..threads import (
check_post_in_closed_category_permission,
check_see_thread_permission,
check_start_thread_in_category_permission,
)
def test_check_post_in_closed_category_permission_passes_if_category_is_open(
user, cache_versions, default_category
):
permissions = UserPermissionsProxy(user, cache_versions)
check_post_in_closed_category_permission(permissions, default_category)
def test_check_post_in_closed_category_permission_passes_if_user_is_global_moderator(
moderator, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_post_in_closed_category_permission(permissions, default_category)
def test_check_post_in_closed_category_permission_passes_if_user_is_category_moderator(
user, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
permissions = UserPermissionsProxy(user, cache_versions)
check_post_in_closed_category_permission(permissions, default_category)
def test_check_post_in_closed_category_permission_fails_if_user_is_not_moderator(
user, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_post_in_closed_category_permission(permissions, default_category)
def test_check_post_in_closed_category_permission_fails_if_user_is_anonymous(
anonymous_user, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(PermissionDenied):
check_post_in_closed_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_passes_if_user_has_permission(
user, cache_versions, default_category
):
permissions = UserPermissionsProxy(user, cache_versions)
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_passes_if_anonymous_has_permission(
user, cache_versions, default_category
):
permissions = UserPermissionsProxy(user, cache_versions)
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_fails_if_user_has_no_permission(
user, cache_versions, default_category
):
CategoryGroupPermission.objects.filter(
group=user.group,
permission=CategoryPermission.START,
).delete()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_fails_if_anonymous_has_no_permission(
anonymous_user, guests_group, cache_versions, default_category
):
CategoryGroupPermission.objects.filter(
group=guests_group,
permission=CategoryPermission.START,
).delete()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(PermissionDenied):
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_passes_if_user_is_global_moderator(
moderator, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_passes_if_user_is_category_moderator(
user, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
permissions = UserPermissionsProxy(user, cache_versions)
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_fails_for_user_if_category_is_closed(
user, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_start_thread_in_category_permission(permissions, default_category)
def test_check_start_thread_in_category_permission_fails_for_anonymous_if_category_is_closed(
anonymous_user, cache_versions, default_category
):
default_category.is_closed = True
default_category.save()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(PermissionDenied):
check_start_thread_in_category_permission(permissions, default_category)
def test_check_see_thread_permission_passes_for_user_with_permission(
user, cache_versions, default_category, thread
):
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_anonymous_user_with_permission(
anonymous_user, cache_versions, default_category, thread
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_user_viewing_their_unapproved_thread(
user, cache_versions, default_category, thread
):
thread.starter = user
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_viewing_other_user_unapproved_thread(
user, other_user, cache_versions, default_category, thread
):
thread.starter = other_user
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_viewing_deleted_user_unapproved_thread(
user, cache_versions, default_category, thread
):
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_category_moderator_viewing_their_unapproved_thread(
user, cache_versions, default_category, thread
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
thread.starter = user
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_category_moderator_viewing_other_user_unapproved_thread(
user, other_user, cache_versions, default_category, thread
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
thread.starter = other_user
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_category_moderator_viewing_deleted_user_unapproved_thread(
user, cache_versions, default_category, thread
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_global_moderator_viewing_their_unapproved_thread(
moderator, cache_versions, default_category, thread
):
thread.starter = moderator
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_global_moderator_viewing_other_user_unapproved_thread(
moderator, other_user, cache_versions, default_category, thread
):
thread.starter = other_user
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_global_moderator_viewing_deleted_user_unapproved_thread(
moderator, cache_versions, default_category, thread
):
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_viewing_user_unapproved_thread(
anonymous_user, user, cache_versions, default_category, thread
):
thread.starter = user
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_viewing_deleted_user_unapproved_thread(
anonymous_user, cache_versions, default_category, thread
):
thread.is_unapproved = True
thread.save()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_viewing_their_hidden_thread(
user, cache_versions, default_category, thread
):
thread.starter = user
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_viewing_other_user_hidden_thread(
user, other_user, cache_versions, default_category, thread
):
thread.starter = other_user
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_viewing_deleted_user_hidden_thread(
user, cache_versions, default_category, thread
):
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_category_moderator_viewing_their_hidden_thread(
user, cache_versions, default_category, thread
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
thread.starter = user
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_category_moderator_viewing_other_user_hidden_thread(
user, other_user, cache_versions, default_category, thread
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
thread.starter = other_user
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_category_moderator_viewing_deleted_user_hidden_thread(
user, cache_versions, default_category, thread
):
Moderator.objects.create(
user=user,
is_global=False,
categories=[default_category.id],
)
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(user, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_global_moderator_viewing_their_hidden_thread(
moderator, cache_versions, default_category, thread
):
thread.starter = moderator
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_global_moderator_viewing_other_user_hidden_thread(
moderator, other_user, cache_versions, default_category, thread
):
thread.starter = other_user
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_passes_for_global_moderator_viewing_deleted_user_hidden_thread(
moderator, cache_versions, default_category, thread
):
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(moderator, cache_versions)
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_viewing_user_hidden_thread(
anonymous_user, other_user, cache_versions, default_category, thread
):
thread.starter = other_user
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_viewing_deleted_user_hidden_thread(
anonymous_user, cache_versions, default_category, thread
):
thread.is_hidden = True
thread.save()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_without_see_permission(
user, cache_versions, default_category, thread
):
CategoryGroupPermission.objects.filter(
group=user.group,
permission=CategoryPermission.SEE,
).delete()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_without_see_permission(
anonymous_user, guests_group, cache_versions, default_category, thread
):
CategoryGroupPermission.objects.filter(
group=guests_group,
permission=CategoryPermission.SEE,
).delete()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_without_browse_permission(
user, cache_versions, default_category, thread
):
CategoryGroupPermission.objects.filter(
group=user.group,
permission=CategoryPermission.BROWSE,
).delete()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_without_browse_permission(
anonymous_user, guests_group, cache_versions, default_category, thread
):
CategoryGroupPermission.objects.filter(
group=guests_group,
permission=CategoryPermission.BROWSE,
).delete()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(Http404):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_user_without_browse_permission_in_delayed_check_category(
user, cache_versions, default_category, thread
):
default_category.delay_browse_check = True
default_category.save()
CategoryGroupPermission.objects.filter(
group=user.group,
permission=CategoryPermission.BROWSE,
).delete()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_see_thread_permission(permissions, default_category, thread)
def test_check_see_thread_permission_fails_for_anonymous_user_without_browse_permission_in_delayed_check_category(
anonymous_user, guests_group, cache_versions, default_category, thread
):
default_category.delay_browse_check = True
default_category.save()
CategoryGroupPermission.objects.filter(
group=guests_group,
permission=CategoryPermission.BROWSE,
).delete()
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(PermissionDenied):
check_see_thread_permission(permissions, default_category, thread)
| 17,912
|
Python
|
.py
| 397
| 40.052897
| 114
| 0.768796
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,556
|
test_category_threads_queryset_filter.py
|
rafalp_Misago/misago/permissions/tests/test_category_threads_queryset_filter.py
|
from itertools import product
from ...threads.models import Thread
from ...threads.enums import ThreadWeight
from ...threads.test import post_thread
def test_category_threads_queryset_includes_category_with_see_and_browse_permission(
category_threads_filter_factory,
category,
category_thread,
category_members_see_permission,
category_members_browse_permission,
user,
):
threads_filter = category_threads_filter_factory(user, category)
queryset = threads_filter.filter(Thread.objects)
assert category_thread in queryset
def test_category_threads_queryset_includes_category_with_see_permission_and_delay_browse(
category_threads_filter_factory,
category,
category_thread,
category_members_see_permission,
user,
):
category.delay_browse_check = True
category.save()
threads_filter = category_threads_filter_factory(user, category)
queryset = threads_filter.filter(Thread.objects)
assert category_thread in queryset
def test_category_threads_queryset_filter(
category_threads_filter_factory,
category,
child_category,
sibling_category,
moderator,
category_moderator,
anonymous_user,
user,
other_user,
category_guests_see_permission,
category_guests_browse_permission,
category_members_see_permission,
category_members_browse_permission,
category_moderators_see_permission,
category_moderators_browse_permission,
child_category_guests_see_permission,
child_category_guests_browse_permission,
child_category_members_see_permission,
child_category_members_browse_permission,
child_category_moderators_see_permission,
child_category_moderators_browse_permission,
sibling_category_guests_see_permission,
sibling_category_guests_browse_permission,
sibling_category_members_see_permission,
sibling_category_members_browse_permission,
sibling_category_moderators_see_permission,
sibling_category_moderators_browse_permission,
):
MATRIX = (
(moderator, category_moderator, anonymous_user, user, other_user),
(category, child_category),
(category, child_category, sibling_category),
(False, True),
(False, True),
(anonymous_user, user, other_user),
(0, 1, 2),
(False, True),
(False, True),
)
for args in product(*MATRIX):
check_category_thread_visibility(category_threads_filter_factory, *args)
def check_category_thread_visibility(
category_threads_filter_factory,
user,
category,
thread_category,
list_children_threads,
started_only,
poster,
thread_weight,
thread_hidden,
thread_unapproved,
):
if category.list_children_threads != list_children_threads:
category.list_children_threads = list_children_threads
category.save()
if thread_category.show_started_only != started_only:
thread_category.show_started_only = started_only
thread_category.save()
thread = post_thread(
thread_category,
poster=poster if poster.is_authenticated else "Anon",
is_global=thread_weight == 2,
is_pinned=thread_weight == 1,
is_hidden=thread_hidden,
is_unapproved=thread_unapproved,
)
threads_filter = category_threads_filter_factory(user, category)
queryset = threads_filter.filter(Thread.objects)
if thread in queryset:
assert_queryset_contains(user, category, thread_category, thread)
else:
assert_queryset_not_contains(user, category, thread_category, thread)
thread.delete()
def assert_queryset_contains(user, category, thread_category, thread):
if thread_category.slug == "sibling":
raise AssertionError(
"queryset result contains a thread from the sibling category"
)
if category.slug == "child" and thread_category.slug == "parent":
raise AssertionError(
"queryset result contains a thread from the sibling category"
)
if (
not category.list_children_threads
and category.slug == "parent"
and thread_category.slug == "child"
):
raise AssertionError(
"queryset result for the category with list_children_threads=False "
"contains a thread from the child category "
)
if thread.weight == ThreadWeight.PINNED_GLOBALLY:
raise AssertionError("queryset result contains a globally pinned thread")
if user.id and (user.slug == "moderator" or user.slug == "categorymoderator"):
return
if thread.is_hidden:
raise AssertionError(
"queryset result for a user without moderator permissions contains "
"a hidden thread"
)
if user.is_anonymous and thread.is_unapproved:
raise AssertionError(
"queryset result for an anonymous user contains an unapproved thread"
)
if (
user.is_anonymous
and thread_category.show_started_only
and thread.weight != ThreadWeight.PINNED_IN_CATEGORY
):
raise AssertionError(
"queryset result for an anonymous user and category with "
"show_started_only=true contains a thread that's not pinned in category"
)
if thread.weight == ThreadWeight.PINNED_IN_CATEGORY and category == thread_category:
raise AssertionError(
"queryset result for an anonymous user and category with "
"show_started_only=true contains a thread that's not pinned in category"
)
if user.is_authenticated and thread.is_unapproved and thread.starter_id != user.id:
raise AssertionError(
"queryset result for a user without moderator permissions contains "
"an unapproved thread started by a different user"
)
if (
user.is_authenticated
and thread_category.show_started_only
and thread.weight != ThreadWeight.PINNED_IN_CATEGORY
and thread.starter_id != user.id
):
raise AssertionError(
"queryset result for a category with show_started_only=true "
"contains not pinned thread that's not started by the user"
)
def assert_queryset_not_contains(user, category, thread_category, thread):
if thread_category.slug == "sibling":
return
if category.slug == "child" and thread_category.slug == "parent":
return
if (
not category.list_children_threads
and category.slug == "parent"
and thread_category.slug == "child"
):
return
if thread.weight == ThreadWeight.PINNED_GLOBALLY:
return
if thread.weight == ThreadWeight.PINNED_IN_CATEGORY and category == thread_category:
return
if user.is_authenticated and (
user.slug == "moderator" or user.slug == "categorymoderator"
):
raise AssertionError("queryset result for a moderator is missing a thread")
if thread.is_hidden:
return
if user.is_anonymous and thread.is_unapproved:
return
if user.is_authenticated and thread.is_unapproved and thread.starter_id == user.id:
raise AssertionError(
"queryset result for a user without moderator permissions is missing "
"an unapproved thread started by them"
)
if (
user.is_authenticated
and thread_category.show_started_only
and thread.starter_id == user.id
):
raise AssertionError(
"queryset result for a user is missing a thread started by them"
)
def test_category_pinned_threads_queryset_includes_category_with_see_and_browse_permission(
category_threads_filter_factory,
category,
category_pinned_thread,
category_pinned_globally_thread,
category_members_see_permission,
category_members_browse_permission,
user,
):
threads_filter = category_threads_filter_factory(user, category)
queryset = threads_filter.filter_pinned(Thread.objects)
assert category_pinned_thread in queryset
assert category_pinned_globally_thread in queryset
def test_category_pinned_threads_queryset_includes_category_with_see_permission_and_delay_browse(
category_threads_filter_factory,
category,
category_pinned_thread,
category_pinned_globally_thread,
category_members_see_permission,
user,
):
category.delay_browse_check = True
category.save()
threads_filter = category_threads_filter_factory(user, category)
queryset = threads_filter.filter_pinned(Thread.objects)
assert category_pinned_thread in queryset
assert category_pinned_globally_thread in queryset
def test_category_pinned_threads_queryset_filter(
category_threads_filter_factory,
category,
child_category,
sibling_category,
moderator,
category_moderator,
anonymous_user,
user,
other_user,
category_guests_see_permission,
category_guests_browse_permission,
category_members_see_permission,
category_members_browse_permission,
category_moderators_see_permission,
category_moderators_browse_permission,
child_category_guests_see_permission,
child_category_guests_browse_permission,
child_category_members_see_permission,
child_category_members_browse_permission,
child_category_moderators_see_permission,
child_category_moderators_browse_permission,
sibling_category_guests_see_permission,
sibling_category_guests_browse_permission,
sibling_category_members_see_permission,
sibling_category_members_browse_permission,
sibling_category_moderators_see_permission,
sibling_category_moderators_browse_permission,
):
MATRIX = (
(moderator, category_moderator, anonymous_user, user, other_user),
(category, child_category),
(category, child_category, sibling_category),
(False, True),
(False, True),
(anonymous_user, user, other_user),
(0, 1, 2),
(False, True),
(False, True),
)
for args in product(*MATRIX):
check_category_pinned_thread_visibility(category_threads_filter_factory, *args)
def check_category_pinned_thread_visibility(
category_threads_filter_factory,
user,
category,
thread_category,
list_children_threads,
started_only,
poster,
thread_weight,
thread_hidden,
thread_unapproved,
):
if category.list_children_threads != list_children_threads:
category.list_children_threads = list_children_threads
category.save()
if thread_category.show_started_only != started_only:
thread_category.show_started_only = started_only
thread_category.save()
thread = post_thread(
thread_category,
poster=poster if poster.is_authenticated else "Anon",
is_global=thread_weight == 2,
is_pinned=thread_weight == 1,
is_hidden=thread_hidden,
is_unapproved=thread_unapproved,
)
threads_filter = category_threads_filter_factory(user, category)
queryset = threads_filter.filter_pinned(Thread.objects)
if thread in queryset:
assert_pinned_queryset_contains(user, category, thread_category, thread)
else:
assert_pinned_queryset_not_contains(user, category, thread_category, thread)
thread.delete()
def assert_pinned_queryset_contains(user, category, thread_category, thread):
if thread.weight == ThreadWeight.NOT_PINNED:
raise AssertionError(
"pinned queryset result contains a thread that is not pinned"
)
if category != thread_category and thread.weight != ThreadWeight.PINNED_GLOBALLY:
raise AssertionError(
"pinned queryset result contains a thread from other category "
"that is not globally pinned"
)
if user.id and (user.slug == "moderator" or user.slug == "categorymoderator"):
return
if thread.is_hidden:
raise AssertionError(
"pinned queryset result for a user without moderator permissions "
"contains a hidden thread"
)
if user.is_anonymous and thread.is_unapproved:
raise AssertionError(
"pinned queryset result for an anonymous user contains an unapproved thread"
)
if user.is_authenticated and thread.is_unapproved and thread.starter_id != user.id:
raise AssertionError(
"pinned queryset result for a user without moderator permissions contains "
"an unapproved thread started by a different user"
)
def assert_pinned_queryset_not_contains(user, category, thread_category, thread):
if thread.weight == ThreadWeight.NOT_PINNED:
return
if category != thread_category and thread.weight != ThreadWeight.PINNED_GLOBALLY:
return
if user.is_authenticated and (
user.slug == "moderator" or user.slug == "categorymoderator"
):
raise AssertionError(
"pinned queryset result for a moderator is missing a thread"
)
if thread.is_hidden:
return
if user.is_anonymous and thread.is_unapproved:
return
if user.is_authenticated and thread.is_unapproved and thread.starter_id == user.id:
raise AssertionError(
"pinned queryset result for a user without moderator permissions is "
"missing an unapproved thread started by them"
)
if (
user.is_authenticated
and thread_category.show_started_only
and thread.starter_id == user.id
):
raise AssertionError(
"pinned queryset result for a user is missing a thread started by them"
)
| 13,676
|
Python
|
.py
| 354
| 31.70339
| 97
| 0.698604
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,557
|
test_moderator_manager.py
|
rafalp_Misago/misago/permissions/tests/test_moderator_manager.py
|
from ..models import Moderator
def test_moderator_manager_get_moderator_permissions_returns_empty_data_for_user_if_none_exist(
user,
):
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert not data.categories_ids
def test_moderator_manager_get_moderator_permissions_returns_categories_ids_for_user(
sibling_category, child_category, user
):
Moderator.objects.create(
is_global=False,
user=user,
categories=[sibling_category.id, child_category.id],
)
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert data.categories_ids == set([sibling_category.id, child_category.id])
def test_moderator_manager_get_moderator_permissions_sums_categories_ids_for_user(
sibling_category, child_category, user
):
Moderator.objects.create(
is_global=False,
user=user,
categories=[sibling_category.id],
)
Moderator.objects.create(
is_global=False,
user=user,
categories=[sibling_category.id, child_category.id],
)
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert data.categories_ids == set([sibling_category.id, child_category.id])
def test_moderator_manager_get_moderator_permissions_returns_global_flag_for_user(user):
Moderator.objects.create(is_global=True, user=user)
data = Moderator.objects.get_moderator_permissions(user)
assert data.is_global
assert not data.categories_ids
def test_moderator_manager_get_moderator_permissions_returns_categories_ids_for_user_group(
sibling_category, child_category, user, members_group, custom_group
):
user.set_groups(members_group, [custom_group])
user.save()
Moderator.objects.create(
is_global=False,
group=custom_group,
categories=[sibling_category.id, child_category.id],
)
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert data.categories_ids == set([sibling_category.id, child_category.id])
def test_moderator_manager_get_moderator_permissions_sums_categories_ids_for_user_group(
sibling_category, child_category, user, members_group, custom_group
):
user.set_groups(members_group, [custom_group])
user.save()
Moderator.objects.create(
is_global=False,
group=custom_group,
categories=[sibling_category.id],
)
Moderator.objects.create(
is_global=False,
group=custom_group,
categories=[sibling_category.id, child_category.id],
)
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert data.categories_ids == set([sibling_category.id, child_category.id])
def test_moderator_manager_get_moderator_permissions_returns_global_flag_for_user_group(
user, members_group, custom_group
):
user.set_groups(members_group, [custom_group])
user.save()
Moderator.objects.create(is_global=True, group=custom_group)
data = Moderator.objects.get_moderator_permissions(user)
assert data.is_global
assert not data.categories_ids
def test_moderator_manager_get_moderator_permissions_returns_private_threads_flag_for_user(
user,
):
Moderator.objects.create(is_global=False, private_threads=True, user=user)
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert not data.categories_ids
assert data.private_threads
def test_moderator_manager_get_moderator_permissions_returns_global_flag_for_user_group(
user, members_group, custom_group
):
user.set_groups(members_group, [custom_group])
user.save()
Moderator.objects.create(is_global=False, private_threads=True, group=custom_group)
data = Moderator.objects.get_moderator_permissions(user)
assert not data.is_global
assert not data.categories_ids
assert data.private_threads
| 3,977
|
Python
|
.py
| 97
| 35.690722
| 95
| 0.742078
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,558
|
test_accounts_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_accounts_permissions.py
|
import pytest
from django.core.exceptions import PermissionDenied
from ..accounts import check_delete_own_account_permission
def test_regular_user_can_delete_their_own_account(user):
check_delete_own_account_permission(user)
def test_django_staff_cant_delete_their_own_account(staffuser):
with pytest.raises(PermissionDenied):
check_delete_own_account_permission(staffuser)
def test_misago_admin_cant_delete_their_own_account(admin):
with pytest.raises(PermissionDenied):
check_delete_own_account_permission(admin)
def test_misago_root_cant_delete_their_own_account(root_admin):
with pytest.raises(PermissionDenied):
check_delete_own_account_permission(root_admin)
| 714
|
Python
|
.py
| 14
| 46.5
| 63
| 0.797395
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,559
|
test_build_user_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_build_user_permissions.py
|
from ..enums import CategoryPermission
from ..user import build_user_permissions
def test_build_user_permissions_builds_user_permissions(user):
permissions = build_user_permissions(user)
assert permissions["can_see_user_profiles"]
def test_build_user_permissions_builds_user_permissions_from_multiple_groups(
user, members_group, custom_group
):
members_group.can_see_user_profiles = False
members_group.save()
custom_group.can_see_user_profiles = True
custom_group.save()
user.set_groups(members_group, [custom_group])
user.save()
permissions = build_user_permissions(user)
assert permissions["can_see_user_profiles"]
def test_build_user_permissions_builds_anonymous_user_permissions(db, anonymous_user):
permissions = build_user_permissions(anonymous_user)
assert permissions["can_see_user_profiles"]
def test_build_user_permissions_builds_user_category_permissions(
user, default_category
):
permissions = build_user_permissions(user)
assert permissions["categories"] == {
CategoryPermission.SEE: [default_category.id],
CategoryPermission.BROWSE: [default_category.id],
CategoryPermission.START: [default_category.id],
CategoryPermission.REPLY: [default_category.id],
CategoryPermission.ATTACHMENTS: [default_category.id],
}
def test_build_user_permissions_builds_anonymous_user_category_permissions(
anonymous_user, default_category
):
permissions = build_user_permissions(anonymous_user)
assert permissions["categories"] == {
CategoryPermission.SEE: [default_category.id],
CategoryPermission.BROWSE: [default_category.id],
CategoryPermission.START: [default_category.id],
CategoryPermission.REPLY: [default_category.id],
CategoryPermission.ATTACHMENTS: [default_category.id],
}
| 1,860
|
Python
|
.py
| 41
| 40.04878
| 86
| 0.751384
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,560
|
test_build_user_category_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_build_user_category_permissions.py
|
from ..enums import CategoryPermission
from ..models import CategoryGroupPermission
from ..user import build_user_category_permissions
def test_build_user_category_permissions_returns_no_permissions_for_user_without_perms(
custom_group, category
):
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_includes_group_see_permission(
custom_group,
category,
category_custom_see_permission,
):
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [category.id],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_includes_group_see_and_browse_permissions(
custom_group,
category,
category_custom_see_permission,
category_custom_browse_permission,
):
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [category.id],
CategoryPermission.BROWSE: [category.id],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_requires_see_permission_for_browse_permissions(
custom_group,
category,
category_custom_browse_permission,
):
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_uses_delay_browse_check_if_browse_is_missing(
custom_group,
category,
child_category,
category_custom_see_permission,
child_category_custom_see_permission,
):
category.delay_browse_check = True
category.save()
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [category.id, child_category.id],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_includes_all_permissions(
custom_group, category, child_category
):
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.SEE,
)
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.BROWSE,
)
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.START,
)
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.REPLY,
)
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.ATTACHMENTS,
)
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [category.id],
CategoryPermission.BROWSE: [category.id],
CategoryPermission.START: [category.id],
CategoryPermission.REPLY: [category.id],
CategoryPermission.ATTACHMENTS: [category.id],
}
def test_build_user_category_permissions_requires_browse_permissions_for_other_permissions(
custom_group, category, child_category
):
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.START,
)
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.REPLY,
)
CategoryGroupPermission.objects.create(
group=custom_group,
category=category,
permission=CategoryPermission.ATTACHMENTS,
)
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_requires_parent_category_browse(
custom_group,
category,
child_category,
child_category_custom_see_permission,
child_category_custom_browse_permission,
):
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [],
CategoryPermission.BROWSE: [],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_child_category_is_visible_under_visible_parent(
custom_group,
category,
child_category,
category_custom_see_permission,
category_custom_browse_permission,
child_category_custom_see_permission,
child_category_custom_browse_permission,
):
permissions = build_user_category_permissions([custom_group], {})
assert permissions == {
CategoryPermission.SEE: [category.id, child_category.id],
CategoryPermission.BROWSE: [category.id, child_category.id],
CategoryPermission.START: [],
CategoryPermission.REPLY: [],
CategoryPermission.ATTACHMENTS: [],
}
def test_build_user_category_permissions_combines_multiple_groups_permissions(
members_group,
custom_group,
default_category,
category,
child_category,
category_custom_see_permission,
category_custom_browse_permission,
child_category_custom_see_permission,
child_category_custom_browse_permission,
):
permissions = build_user_category_permissions([members_group, custom_group], {})
assert permissions == {
CategoryPermission.SEE: [
default_category.id,
category.id,
child_category.id,
],
CategoryPermission.BROWSE: [
default_category.id,
category.id,
child_category.id,
],
CategoryPermission.START: [default_category.id],
CategoryPermission.REPLY: [default_category.id],
CategoryPermission.ATTACHMENTS: [default_category.id],
}
| 6,812
|
Python
|
.py
| 192
| 29.005208
| 91
| 0.700925
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,561
|
test_operations.py
|
rafalp_Misago/misago/permissions/tests/test_operations.py
|
from ..operations import (
if_false,
if_greater,
if_lesser,
if_true,
if_zero_or_greater,
)
def test_if_true_keeps_permission_false_if_value_is_false():
permissions = {"permission": False}
if_true(permissions, "permission", False)
assert permissions == {"permission": False}
def test_if_true_changes_permission_to_true_if_value_is_true():
permissions = {"permission": False}
if_true(permissions, "permission", True)
assert permissions == {"permission": True}
def test_if_false_keeps_permission_true_if_value_is_true():
permissions = {"permission": True}
if_false(permissions, "permission", True)
assert permissions == {"permission": True}
def test_if_false_changes_permission_to_false_if_value_is_false():
permissions = {"permission": True}
if_false(permissions, "permission", False)
assert permissions == {"permission": False}
def test_if_greater_keeps_permission_low_if_value_is_lesser():
permissions = {"permission": 5}
if_greater(permissions, "permission", 4)
assert permissions == {"permission": 5}
def test_if_greater_changes_permission_if_value_is_greater():
permissions = {"permission": 5}
if_greater(permissions, "permission", 6)
assert permissions == {"permission": 6}
def test_if_lesser_keeps_permission_high_if_value_is_greater():
permissions = {"permission": 5}
if_lesser(permissions, "permission", 6)
assert permissions == {"permission": 5}
def test_if_lesser_changes_permission_if_value_is_lesser():
permissions = {"permission": 5}
if_lesser(permissions, "permission", 4)
assert permissions == {"permission": 4}
def test_if_zero_or_greater_keeps_permission_high_if_value_is_lesser():
permissions = {"permission": 5}
if_zero_or_greater(permissions, "permission", 4)
assert permissions == {"permission": 5}
def test_if_zero_or_greater_changes_permission_if_value_is_greater():
permissions = {"permission": 5}
if_zero_or_greater(permissions, "permission", 6)
assert permissions == {"permission": 6}
def test_if_zero_or_greater_changes_permission_if_value_is_zero():
permissions = {"permission": 5}
if_zero_or_greater(permissions, "permission", 0)
assert permissions == {"permission": 0}
| 2,272
|
Python
|
.py
| 51
| 40.137255
| 71
| 0.707594
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,562
|
test_get_user_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_get_user_permissions.py
|
from unittest.mock import patch
from ..user import get_user_permissions
@patch("misago.permissions.user.build_user_permissions")
@patch("misago.permissions.user.cache")
def test_get_user_permissions_builds_user_permissions_on_cache_miss(
cache_mock, build_user_permissions, cache_versions, user
):
build_user_permissions.return_value = {"build_permissions": True}
cache_mock.get.return_value = None
permissions = get_user_permissions(user, cache_versions)
assert permissions["build_permissions"]
cache_mock.get.assert_called_once()
cache_mock.set.assert_called_once()
build_user_permissions.assert_called_once()
@patch("misago.permissions.user.build_user_permissions")
@patch("misago.permissions.user.cache")
def test_get_user_permissions_uses_cached_permissions_on_cache_hit(
cache_mock, build_user_permissions, cache_versions, user
):
cache_mock.get.return_value = {"cached_permissions": True}
permissions = get_user_permissions(user, cache_versions)
assert permissions["cached_permissions"]
cache_mock.get.assert_called_once()
cache_mock.set.assert_not_called()
build_user_permissions.assert_not_called()
@patch("misago.permissions.user.build_user_permissions")
@patch("misago.permissions.user.cache")
def test_get_user_permissions_builds_anonymous_user_permissions_on_cache_miss(
cache_mock, build_user_permissions, cache_versions, db, anonymous_user
):
build_user_permissions.return_value = {"build_permissions": True}
cache_mock.get.return_value = None
permissions = get_user_permissions(anonymous_user, cache_versions)
assert permissions["build_permissions"]
cache_mock.get.assert_called_once()
cache_mock.set.assert_called_once()
build_user_permissions.assert_called_once()
@patch("misago.permissions.user.build_user_permissions")
@patch("misago.permissions.user.cache")
def test_get_user_permissions_uses_anonymous_cached_permissions_on_cache_hit(
cache_mock, build_user_permissions, cache_versions, db, anonymous_user
):
cache_mock.get.return_value = {"cached_permissions": True}
permissions = get_user_permissions(anonymous_user, cache_versions)
assert permissions["cached_permissions"]
cache_mock.get.assert_called_once()
cache_mock.set.assert_not_called()
build_user_permissions.assert_not_called()
| 2,349
|
Python
|
.py
| 48
| 45.083333
| 78
| 0.771016
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,563
|
test_private_threads_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_private_threads_permissions.py
|
import pytest
from django.core.exceptions import PermissionDenied
from django.http import Http404
from ...threads.models import ThreadParticipant
from ...threads.test import post_thread
from ..privatethreads import (
check_private_threads_permission,
check_see_private_thread_permission,
check_start_private_threads_permission,
filter_private_thread_posts_queryset,
filter_private_threads_queryset,
)
from ..proxy import UserPermissionsProxy
def test_check_private_threads_permission_passes_if_user_has_permission(
user, cache_versions
):
permissions = UserPermissionsProxy(user, cache_versions)
check_private_threads_permission(permissions)
def test_check_private_threads_permission_fails_if_user_has_no_permission(
user, members_group, cache_versions
):
members_group.can_use_private_threads = False
members_group.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_private_threads_permission(permissions)
def test_check_private_threads_permission_fails_if_user_is_anonymous(
anonymous_user, cache_versions
):
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
with pytest.raises(PermissionDenied):
check_private_threads_permission(permissions)
def test_check_start_private_threads_permission_passes_if_user_has_permission(
user, cache_versions
):
permissions = UserPermissionsProxy(user, cache_versions)
check_start_private_threads_permission(permissions)
def test_check_start_private_threads_permission_fails_if_user_has_no_permission(
user, members_group, cache_versions
):
members_group.can_start_private_threads = False
members_group.save()
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_start_private_threads_permission(permissions)
def test_check_see_private_thread_permission_passes_if_user_has_permission(
user, cache_versions, thread
):
thread.participants.add(user)
permissions = UserPermissionsProxy(user, cache_versions)
check_see_private_thread_permission(permissions, thread)
def test_check_see_private_thread_permission_fails_if_user_cant_use_private_threads(
user, cache_versions, thread
):
user.group.can_use_private_threads = False
user.group.save()
thread.participants.add(user)
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(PermissionDenied):
check_see_private_thread_permission(permissions, thread)
def test_check_see_private_thread_permission_fails_if_user_is_not_thread_participant(
user, cache_versions, thread
):
permissions = UserPermissionsProxy(user, cache_versions)
with pytest.raises(Http404):
check_see_private_thread_permission(permissions, thread)
def test_filter_private_threads_queryset_returns_nothing_for_anonymous_user(
private_threads_category, anonymous_user, cache_versions
):
post_thread(private_threads_category)
permissions = UserPermissionsProxy(anonymous_user, cache_versions)
queryset = filter_private_threads_queryset(
permissions, private_threads_category.thread_set
)
assert not queryset.exists()
def test_filter_private_threads_queryset_returns_thread_for_user_who_is_a_thread_participant(
private_threads_category, user, cache_versions
):
thread = post_thread(private_threads_category)
ThreadParticipant.objects.create(thread=thread, user=user)
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_private_threads_queryset(
permissions, private_threads_category.thread_set
)
assert thread in list(queryset)
def test_filter_private_threads_queryset_excludes_thread_user_is_not_participating_in(
private_threads_category, user, other_user, cache_versions
):
thread = post_thread(private_threads_category)
ThreadParticipant.objects.create(thread=thread, user=other_user)
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_private_threads_queryset(
permissions, private_threads_category.thread_set
)
assert not queryset.exists()
def test_filter_private_thread_posts_queryset_returns_all_posts(
user, cache_versions, thread
):
permissions = UserPermissionsProxy(user, cache_versions)
queryset = filter_private_thread_posts_queryset(
permissions, thread, thread.post_set
)
assert queryset.exists()
| 4,508
|
Python
|
.py
| 103
| 39.281553
| 93
| 0.78218
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,564
|
test_user_permissions_proxy.py
|
rafalp_Misago/misago/permissions/tests/test_user_permissions_proxy.py
|
from ..enums import CategoryPermission
from ..models import CategoryGroupPermission, Moderator
from ..proxy import UserPermissionsProxy
def test_user_permissions_proxy_makes_no_queries_unused(
django_assert_num_queries, user, cache_versions
):
with django_assert_num_queries(0):
proxy = UserPermissionsProxy(user, cache_versions)
assert not proxy.accessed_permissions
def test_user_permissions_proxy_returns_user_permissions(user, cache_versions):
proxy = UserPermissionsProxy(user, cache_versions)
permissions = proxy.permissions
assert permissions["categories"]
assert proxy.accessed_permissions
def test_user_permissions_proxy_getattr_returns_user_permission(user, cache_versions):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.categories
assert proxy.accessed_permissions
def test_user_permissions_proxy_returns_admins_member_global_moderator_permission(
django_assert_num_queries, user, admins_group, cache_versions
):
user.set_groups(admins_group)
user.save()
with django_assert_num_queries(0):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_moderators_member_global_moderator_permission(
django_assert_num_queries, user, moderators_group, cache_versions
):
user.set_groups(moderators_group)
user.save()
with django_assert_num_queries(0):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_secondary_admins_member_global_moderator_permission(
django_assert_num_queries, user, members_group, admins_group, cache_versions
):
user.set_groups(members_group, [admins_group])
user.save()
with django_assert_num_queries(0):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_secondary_moderators_member_global_moderator_permission(
django_assert_num_queries, user, members_group, moderators_group, cache_versions
):
user.set_groups(members_group, [moderators_group])
user.save()
with django_assert_num_queries(0):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_custom_moderators_member_global_moderator_permission(
django_assert_num_queries, user, custom_group, cache_versions
):
Moderator.objects.create(is_global=True, group=custom_group)
user.set_groups(custom_group)
user.save()
with django_assert_num_queries(1):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_custom_moderators_secondary_member_global_moderator_permission(
django_assert_num_queries, user, members_group, custom_group, cache_versions
):
Moderator.objects.create(is_global=True, group=custom_group)
user.set_groups(members_group, [custom_group])
user.save()
with django_assert_num_queries(1):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_true_for_member_global_moderator_permission(
django_assert_num_queries, user, cache_versions
):
Moderator.objects.create(is_global=True, user=user)
with django_assert_num_queries(1):
proxy = UserPermissionsProxy(user, cache_versions)
assert proxy.is_global_moderator
def test_user_permissions_proxy_returns_false_for_member_without_global_moderator_permission(
django_assert_num_queries, user, cache_versions
):
with django_assert_num_queries(1):
proxy = UserPermissionsProxy(user, cache_versions)
assert not proxy.is_global_moderator
def test_user_permissions_proxy_returns_false_for_member_without_global_moderator_permission(
django_assert_num_queries, user, cache_versions
):
with django_assert_num_queries(1):
proxy = UserPermissionsProxy(user, cache_versions)
assert not proxy.is_global_moderator
def test_user_permissions_proxy_returns_false_for_category_moderator(
django_assert_num_queries, user, cache_versions, other_category
):
Moderator.objects.create(is_global=False, user=user, categories=[other_category.id])
with django_assert_num_queries(1):
proxy = UserPermissionsProxy(user, cache_versions)
assert not proxy.is_global_moderator
def test_user_permissions_proxy_returns_list_of_moderated_categories_ids_for_local_moderator(
django_assert_num_queries, user, cache_versions, other_category
):
CategoryGroupPermission.objects.create(
category=other_category,
group=user.group,
permission=CategoryPermission.SEE,
)
CategoryGroupPermission.objects.create(
category=other_category,
group=user.group,
permission=CategoryPermission.BROWSE,
)
Moderator.objects.create(is_global=False, user=user, categories=[other_category.id])
proxy = UserPermissionsProxy(user, cache_versions)
proxy.permissions
with django_assert_num_queries(1):
assert proxy.categories_moderator == {other_category.id}
def test_user_permissions_proxy_excludes_not_browseable_categories_from_moderated_categories(
django_assert_num_queries, user, cache_versions, other_category
):
CategoryGroupPermission.objects.create(
category=other_category,
group=user.group,
permission=CategoryPermission.SEE,
)
Moderator.objects.create(is_global=False, user=user, categories=[other_category.id])
proxy = UserPermissionsProxy(user, cache_versions)
proxy.permissions
with django_assert_num_queries(1):
assert proxy.categories_moderator == set()
def test_user_permissions_proxy_returns_false_global_moderator_for_anonymous_user(
django_assert_num_queries, db, anonymous_user, cache_versions
):
proxy = UserPermissionsProxy(anonymous_user, cache_versions)
with django_assert_num_queries(0):
assert not proxy.is_global_moderator
def test_user_permissions_proxy_returns_no_moderated_categories_for_anonymous_user(
django_assert_num_queries, db, anonymous_user, cache_versions
):
proxy = UserPermissionsProxy(anonymous_user, cache_versions)
proxy.permissions
with django_assert_num_queries(0):
assert not proxy.categories_moderator
| 6,479
|
Python
|
.py
| 138
| 41.572464
| 103
| 0.764032
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,565
|
test_copy_category_permissions.py
|
rafalp_Misago/misago/permissions/tests/test_copy_category_permissions.py
|
import pytest
from ..copy import copy_category_permissions
from ..models import CategoryGroupPermission
def test_copy_category_permissions_copies_category_permission(
members_group, sibling_category, other_category
):
CategoryGroupPermission.objects.create(
group=members_group,
category=sibling_category,
permission="test",
)
copy_category_permissions(sibling_category, other_category)
CategoryGroupPermission.objects.get(
group=members_group,
category=other_category,
permission="test",
)
def test_copy_category_permissions_deletes_previous_category_permission(
members_group, sibling_category, other_category
):
CategoryGroupPermission.objects.create(
group=members_group,
category=other_category,
permission="deleted",
)
copy_category_permissions(sibling_category, other_category)
with pytest.raises(CategoryGroupPermission.DoesNotExist):
CategoryGroupPermission.objects.get(
group=members_group,
category=other_category,
permission="deleted",
)
| 1,127
|
Python
|
.py
| 32
| 28.6875
| 72
| 0.729282
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,566
|
checks.py
|
rafalp_Misago/misago/permissions/threads/checks.py
|
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.translation import pgettext
from ...categories.models import Category
from ...threads.models import Thread
from ..categories import check_see_category_permission
from ..enums import CategoryPermission
from ..hooks import (
check_post_in_closed_category_permission_hook,
check_see_thread_permission_hook,
check_start_thread_in_category_permission_hook,
)
from ..proxy import UserPermissionsProxy
def check_post_in_closed_category_permission(
permissions: UserPermissionsProxy, category: Category
):
check_post_in_closed_category_permission_hook(
_check_post_in_closed_category_permission_action,
permissions,
category,
)
def _check_post_in_closed_category_permission_action(
permissions: UserPermissionsProxy, category: Category
):
if category.is_closed and not (
permissions.is_global_moderator
or category.id in permissions.categories_moderator
):
raise PermissionDenied(
pgettext(
"threads permission error",
"This category is closed.",
)
)
def check_start_thread_in_category_permission(
permissions: UserPermissionsProxy, category: Category
):
check_start_thread_in_category_permission_hook(
_check_start_thread_in_category_permission_action,
permissions,
category,
)
def _check_start_thread_in_category_permission_action(
permissions: UserPermissionsProxy, category: Category
):
if category.id not in permissions.categories[CategoryPermission.START]:
raise PermissionDenied(
pgettext(
"threads permission error",
"You can't start new threads in this category.",
)
)
check_post_in_closed_category_permission(permissions, category)
def check_see_thread_permission(
permissions: UserPermissionsProxy, category: Category, thread: Thread
):
check_see_thread_permission_hook(
_check_see_thread_permission_action, permissions, category, thread
)
def _check_see_thread_permission_action(
permissions: UserPermissionsProxy, category: Category, thread: Thread
):
if not (
permissions.is_global_moderator
or category.id in permissions.categories_moderator
):
if thread.is_hidden:
raise Http404()
if thread.is_unapproved and (
thread.starter_id is None
or permissions.user.is_anonymous
or thread.starter_id != permissions.user.id
):
raise Http404()
if (
category.show_started_only
and not thread.weight
and (
thread.starter_id is None
or permissions.user.is_anonymous
or thread.starter_id != permissions.user.id
)
):
raise Http404()
check_see_category_permission(permissions, category)
if category.id not in permissions.categories[CategoryPermission.BROWSE]:
if category.delay_browse_check:
raise PermissionDenied(
pgettext(
"category permission error",
"You can't browse the contents of this category.",
)
)
raise Http404()
| 3,382
|
Python
|
.py
| 94
| 27.925532
| 76
| 0.671459
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,567
|
__init__.py
|
rafalp_Misago/misago/permissions/threads/__init__.py
|
from .checks import (
check_post_in_closed_category_permission,
check_see_thread_permission,
check_start_thread_in_category_permission,
)
from .querysets import (
CategoryThreadsQuerysetFilter,
ThreadsQuerysetFilter,
filter_category_threads_queryset,
filter_thread_posts_queryset,
)
__all__ = [
"CategoryThreadsQuerysetFilter",
"ThreadsQuerysetFilter",
"check_post_in_closed_category_permission",
"check_see_thread_permission",
"check_start_thread_in_category_permission",
"filter_category_threads_queryset",
"filter_thread_posts_queryset",
]
| 600
|
Python
|
.py
| 20
| 26.15
| 48
| 0.753022
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,568
|
querysets.py
|
rafalp_Misago/misago/permissions/threads/querysets.py
|
from typing import Iterable
from django.db.models import Q, QuerySet
from ...threads.enums import ThreadWeight
from ...threads.models import Thread
from ..enums import (
CategoryPermission,
CategoryQueryContext,
CategoryThreadsQuery,
)
from ..hooks import (
filter_thread_posts_queryset_hook,
get_category_threads_category_query_hook,
get_category_threads_pinned_category_query_hook,
get_threads_category_query_hook,
get_threads_pinned_category_query_hook,
get_category_threads_query_hook,
get_threads_query_orm_filter_hook,
)
from ..proxy import UserPermissionsProxy
class ThreadsQuerysetFilter:
permissions: UserPermissionsProxy
all_categories: list[dict]
def __init__(
self,
permissions: UserPermissionsProxy,
all_categories: list[dict],
) -> QuerySet:
self.permissions = permissions
self.all_categories = []
for category in all_categories:
if category["id"] in permissions.categories[CategoryPermission.BROWSE] or (
category["id"] in permissions.categories[CategoryPermission.SEE]
and category["delay_browse_check"]
):
self.all_categories.append(category)
def filter(self, queryset: QuerySet) -> QuerySet:
categories_queries = self.get_categories_threads_queries()
if not categories_queries:
return queryset.none()
filters: list[Q] = self.get_queryset_filters(categories_queries)
return queryset.filter(_or_q(filters))
def filter_pinned(self, queryset: QuerySet) -> QuerySet:
categories_queries = self.get_categories_pinned_threads_queries()
if not categories_queries:
return queryset.none()
filters: list[Q] = self.get_queryset_filters(categories_queries)
return queryset.filter(_or_q(filters))
def get_categories_threads_queries(self) -> dict[str, set[int]]:
queries: dict[str, set[int]] = {}
for category in self.all_categories:
if query := get_threads_category_query(self.permissions, category):
self.add_query_to_queries(queries, query, category)
return queries
def get_categories_pinned_threads_queries(self) -> dict[str, set[int]]:
queries: dict[str, set[int]] = {}
for category in self.all_categories:
if query := get_threads_pinned_category_query(self.permissions, category):
self.add_query_to_queries(queries, query, category)
return queries
def add_query_to_queries(
self, queries: dict[str, set[int]], query: str | list[str], category: dict
) -> None:
if isinstance(query, str):
if query not in queries:
queries[query] = set()
queries[query].add(category["id"])
else:
for q in query:
self.add_query_to_queries(queries, q, category)
def get_queryset_filters(self, access_levels: dict[str, set[int]]) -> list[Q]:
filters: list[Q] = []
for query, categories_ids in access_levels.items():
filter_ = get_threads_query_orm_filter(
query, categories_ids, self.permissions.user.id
)
filters.append(filter_)
return filters
class CategoryThreadsQuerysetFilter(ThreadsQuerysetFilter):
current_category: dict
child_categories: list[dict]
other_categories: list[dict]
include_children: bool
def __init__(
self,
permissions: UserPermissionsProxy,
categories: list[dict],
current_category: dict,
child_categories: list[dict],
include_children: bool,
) -> QuerySet:
super().__init__(permissions, categories)
self.current_category = current_category
self.child_categories = []
self.other_categories = []
children_ids = set(c["id"] for c in child_categories)
for category in self.all_categories:
if category["id"] == current_category["id"]:
continue
elif category["id"] in children_ids:
self.child_categories.append(category)
else:
self.other_categories.append(category)
self.include_children = include_children
def get_categories_threads_queries(self) -> dict[str, set[int]]:
queries: dict[str, set[int]] = {}
if query := get_category_threads_category_query(
self.permissions, self.current_category, CategoryQueryContext.CURRENT
):
self.add_query_to_queries(queries, query, self.current_category)
if self.include_children:
for category in self.child_categories:
if query := get_category_threads_category_query(
self.permissions, category, CategoryQueryContext.CHILD
):
self.add_query_to_queries(queries, query, category)
for category in self.other_categories:
if query := get_category_threads_category_query(
self.permissions, category, CategoryQueryContext.OTHER
):
self.add_query_to_queries(queries, query, category)
return queries
def get_categories_pinned_threads_queries(self) -> dict[str, set[int]]:
queries: dict[str, set[int]] = {}
if query := get_category_threads_pinned_category_query(
self.permissions, self.current_category, CategoryQueryContext.CURRENT
):
self.add_query_to_queries(queries, query, self.current_category)
for category in self.child_categories:
if query := get_category_threads_pinned_category_query(
self.permissions, category, CategoryQueryContext.CHILD
):
self.add_query_to_queries(queries, query, category)
for category in self.other_categories:
if query := get_category_threads_pinned_category_query(
self.permissions, category, CategoryQueryContext.OTHER
):
self.add_query_to_queries(queries, query, category)
return queries
def filter_category_threads_queryset(
permissions: UserPermissionsProxy, category: dict, queryset: QuerySet
):
if permissions.user.is_authenticated:
user_id = permissions.user.id
else:
user_id = None
query = get_category_threads_query(permissions, category)
if isinstance(query, list):
expression = _or_q(
[get_threads_query_orm_filter(q, [category["id"]], user_id) for q in query]
)
else:
expression = get_threads_query_orm_filter(query, [category["id"]], user_id)
return queryset.filter(expression)
def get_category_threads_query(
permissions: UserPermissionsProxy, category: dict
) -> str | list[str] | None:
return get_category_threads_query_hook(
_get_category_threads_query_action, permissions, category
)
def _get_category_threads_query_action(
permissions: UserPermissionsProxy, category: dict
) -> str | list[str] | None:
if (
permissions.is_global_moderator
or category["id"] in permissions.categories_moderator
):
return CategoryThreadsQuery.ALL
if category["show_started_only"]:
if permissions.user.is_authenticated:
return [
CategoryThreadsQuery.USER_PINNED,
CategoryThreadsQuery.USER_STARTED_NOT_PINNED,
]
return CategoryThreadsQuery.ANON_PINNED
if permissions.user.is_authenticated:
return CategoryThreadsQuery.USER
return CategoryThreadsQuery.ANON
def get_threads_category_query(
permissions: UserPermissionsProxy, category: dict
) -> str | list[str] | None:
return get_threads_category_query_hook(
_get_threads_category_query_action, permissions, category
)
def _get_threads_category_query_action(
permissions: UserPermissionsProxy, category: dict
) -> str | list[str] | None:
if (
permissions.is_global_moderator
or category["id"] in permissions.categories_moderator
):
return CategoryThreadsQuery.ALL_NOT_PINNED_GLOBALLY
if category["show_started_only"]:
if permissions.user.is_authenticated:
return [
CategoryThreadsQuery.USER_PINNED_IN_CATEGORY,
CategoryThreadsQuery.USER_STARTED_NOT_PINNED,
]
return CategoryThreadsQuery.ANON_PINNED_IN_CATEGORY
if permissions.user.is_authenticated:
return CategoryThreadsQuery.USER_NOT_PINNED_GLOBALLY
return CategoryThreadsQuery.ANON_NOT_PINNED_GLOBALLY
def get_threads_pinned_category_query(
permissions: UserPermissionsProxy, category: dict
) -> str | list[str] | None:
return get_threads_pinned_category_query_hook(
_get_threads_pinned_category_query_action, permissions, category
)
def _get_threads_pinned_category_query_action(
permissions: UserPermissionsProxy, category: dict
) -> str | list[str] | None:
if (
permissions.is_global_moderator
or category["id"] in permissions.categories_moderator
):
return CategoryThreadsQuery.ALL_PINNED_GLOBALLY
if permissions.user.is_authenticated:
return CategoryThreadsQuery.USER_PINNED_GLOBALLY
return CategoryThreadsQuery.ANON_PINNED_GLOBALLY
def get_category_threads_category_query(
permissions: UserPermissionsProxy, category: dict, context: str
) -> str | list[str] | None:
return get_category_threads_category_query_hook(
_get_category_threads_category_query_action,
permissions,
category,
context,
)
def _get_category_threads_category_query_action(
permissions: UserPermissionsProxy, category: dict, context: str
) -> str | list[str] | None:
if context == CategoryQueryContext.OTHER:
return None # We don't display non-category items on category pages
if (
permissions.is_global_moderator
or category["id"] in permissions.categories_moderator
):
if context == CategoryQueryContext.CURRENT:
return CategoryThreadsQuery.ALL_NOT_PINNED
return CategoryThreadsQuery.ALL_NOT_PINNED_GLOBALLY
if category["show_started_only"]:
if context == CategoryQueryContext.CURRENT:
if permissions.user.is_authenticated:
return CategoryThreadsQuery.USER_STARTED_NOT_PINNED
return None
if permissions.user.is_authenticated:
return [
CategoryThreadsQuery.USER_PINNED_IN_CATEGORY,
CategoryThreadsQuery.USER_STARTED_NOT_PINNED,
]
return CategoryThreadsQuery.ANON_PINNED_IN_CATEGORY
if context == CategoryQueryContext.CURRENT:
if permissions.user.is_authenticated:
return CategoryThreadsQuery.USER_NOT_PINNED
return CategoryThreadsQuery.ANON_NOT_PINNED
if permissions.user.is_authenticated:
return CategoryThreadsQuery.USER_NOT_PINNED_GLOBALLY
return CategoryThreadsQuery.ANON_NOT_PINNED_GLOBALLY
def get_category_threads_pinned_category_query(
permissions: UserPermissionsProxy, category: dict, context: str
) -> str | list[str] | None:
return get_category_threads_pinned_category_query_hook(
_get_category_threads_pinned_category_query_action,
permissions,
category,
context,
)
def _get_category_threads_pinned_category_query_action(
permissions: UserPermissionsProxy, category: dict, context: str
) -> str | list[str] | None:
if (
permissions.is_global_moderator
or category["id"] in permissions.categories_moderator
):
if context == CategoryQueryContext.CURRENT:
return CategoryThreadsQuery.ALL_PINNED
return CategoryThreadsQuery.ALL_PINNED_GLOBALLY
if permissions.user.is_authenticated:
if context == CategoryQueryContext.CURRENT:
return CategoryThreadsQuery.USER_PINNED
return CategoryThreadsQuery.USER_PINNED_GLOBALLY
if context == CategoryQueryContext.CURRENT:
return CategoryThreadsQuery.ANON_PINNED
return CategoryThreadsQuery.ANON_PINNED_GLOBALLY
def _or_q(q: Iterable[Q]):
fin = None
for cond in q:
if cond:
if fin is not None:
fin |= cond
else:
fin = cond
return fin
def get_threads_query_orm_filter(
query: CategoryThreadsQuery | str,
categories: set[int],
user_id: int | None,
) -> Q:
q = get_threads_query_orm_filter_hook(
_get_threads_query_orm_filter_action, query, categories, user_id
)
if q is None:
raise ValueError(f"Could not find a filter for the '{query}' query.")
return q
def _get_threads_query_orm_filter_action(
query: CategoryThreadsQuery | str,
categories: set[int],
user_id: int | None,
) -> Q | None:
if query == CategoryThreadsQuery.ALL:
return Q(category_id__in=categories)
if query == CategoryThreadsQuery.ALL_PINNED:
return Q(
category_id__in=categories,
weight__gt=ThreadWeight.NOT_PINNED,
)
if query == CategoryThreadsQuery.ALL_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_GLOBALLY,
)
if query == CategoryThreadsQuery.ALL_PINNED_IN_CATEGORY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_GLOBALLY,
)
if query == CategoryThreadsQuery.ALL_NOT_PINNED:
return Q(
category_id__in=categories,
weight=ThreadWeight.NOT_PINNED,
)
if query == CategoryThreadsQuery.ALL_NOT_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight__lt=ThreadWeight.PINNED_GLOBALLY,
)
if query == CategoryThreadsQuery.ANON:
return Q(
category_id__in=categories,
is_hidden=False,
is_unapproved=False,
)
if query == CategoryThreadsQuery.ANON_PINNED:
return Q(
category_id__in=categories,
weight__gt=ThreadWeight.NOT_PINNED,
is_hidden=False,
is_unapproved=False,
)
if query == CategoryThreadsQuery.ANON_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_GLOBALLY,
is_hidden=False,
is_unapproved=False,
)
if query == CategoryThreadsQuery.ANON_PINNED_IN_CATEGORY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_IN_CATEGORY,
is_hidden=False,
is_unapproved=False,
)
if query == CategoryThreadsQuery.ANON_NOT_PINNED:
return Q(
category_id__in=categories,
weight=ThreadWeight.NOT_PINNED,
is_hidden=False,
is_unapproved=False,
)
if query == CategoryThreadsQuery.ANON_NOT_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight__lt=ThreadWeight.PINNED_GLOBALLY,
is_hidden=False,
is_unapproved=False,
)
if query == CategoryThreadsQuery.USER:
return Q(
category_id__in=categories,
is_hidden=False,
) & Q(
Q(is_unapproved=False) | Q(starter_id=user_id),
)
if query == CategoryThreadsQuery.USER_PINNED:
return Q(
category_id__in=categories,
weight__gt=ThreadWeight.NOT_PINNED,
is_hidden=False,
) & Q(
Q(is_unapproved=False) | Q(starter_id=user_id),
)
if query == CategoryThreadsQuery.USER_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_GLOBALLY,
is_hidden=False,
) & Q(
Q(is_unapproved=False) | Q(starter_id=user_id),
)
if query == CategoryThreadsQuery.USER_PINNED_IN_CATEGORY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_IN_CATEGORY,
is_hidden=False,
) & Q(
Q(is_unapproved=False) | Q(starter_id=user_id),
)
if query == CategoryThreadsQuery.USER_NOT_PINNED:
return Q(
category_id__in=categories,
weight=ThreadWeight.NOT_PINNED,
is_hidden=False,
) & Q(
Q(is_unapproved=False) | Q(starter_id=user_id),
)
if query == CategoryThreadsQuery.USER_NOT_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight__lt=ThreadWeight.PINNED_GLOBALLY,
is_hidden=False,
) & Q(
Q(is_unapproved=False) | Q(starter_id=user_id),
)
if query == CategoryThreadsQuery.USER_STARTED_PINNED:
return Q(
category_id__in=categories,
weight__gt=ThreadWeight.NOT_PINNED,
is_hidden=False,
starter_id=user_id,
)
if query == CategoryThreadsQuery.USER_STARTED_PINNED_GLOBALLY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_GLOBALLY,
is_hidden=False,
starter_id=user_id,
)
if query == CategoryThreadsQuery.USER_STARTED_PINNED_IN_CATEGORY:
return Q(
category_id__in=categories,
weight=ThreadWeight.PINNED_IN_CATEGORY,
is_hidden=False,
starter_id=user_id,
)
if query == CategoryThreadsQuery.USER_STARTED_NOT_PINNED:
return Q(
category_id__in=categories,
weight=ThreadWeight.NOT_PINNED,
is_hidden=False,
starter_id=user_id,
)
return None
def filter_thread_posts_queryset(
permissions: UserPermissionsProxy,
thread: Thread,
queryset: QuerySet,
) -> QuerySet:
return filter_thread_posts_queryset_hook(
_filter_thread_posts_queryset_action, permissions, thread, queryset
)
def _filter_thread_posts_queryset_action(
permissions: UserPermissionsProxy,
thread: Thread,
queryset: QuerySet,
) -> QuerySet:
if (
permissions.is_global_moderator
or thread.category_id in permissions.categories_moderator
):
return queryset
if permissions.user.is_authenticated:
return queryset.filter(
Q(is_unapproved=False) | Q(poster_id=permissions.user.id)
)
return queryset.filter(is_unapproved=False)
| 18,636
|
Python
|
.py
| 475
| 30.305263
| 87
| 0.648506
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,569
|
get_threads_category_query.py
|
rafalp_Misago/misago/permissions/hooks/get_threads_category_query.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class GetThreadsCategoryQueryHookAction(Protocol):
"""
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
threads from the given category for displaying on the threads page.
Standard `WHERE` clauses implemented by Misago can be retrieved from the
`CategoryThreadsQuery` `StrEnum`:
```python
from misago.permissions.enums import CategoryThreadsQuery
```
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None: ...
class GetThreadsCategoryQueryHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetThreadsCategoryQueryHookAction`
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
pinned threads from the given category for displaying on the threads page.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
action: GetThreadsCategoryQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None: ...
class GetThreadsCategoryQueryHook(
FilterHook[
GetThreadsCategoryQueryHookAction,
GetThreadsCategoryQueryHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to get the name of
the predefined database `WHERE` clause (represented as a `Q` object instance)
to use to retrieve threads from the given category for displaying on the threads
page.
# Example
The code below implements a custom filter function that specifies a custom
`WHERE` clause supported by the `get_threads_query_orm_filter_hook`.
```python
from misago.permissions.hooks import get_threads_category_query_hook
from misago.permissions.proxy import UserPermissionsProxy
@get_threads_category_query_hook.append_filter
def get_threads_category_query(
action,
permissions: UserPermissionsProxy,
category: dict,
) -> str | list[str] | None:
if category.get("plugin_flag"):
return "plugin-where"
return action(permissions, category)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetThreadsCategoryQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None:
return super().__call__(action, permissions, category)
get_threads_category_query_hook = GetThreadsCategoryQueryHook()
| 3,822
|
Python
|
.py
| 92
| 35.565217
| 84
| 0.71208
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,570
|
check_browse_category_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_browse_category_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckBrowseCategoryPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has permission to
browse a category. It also checks if the user can see the category.
It raises Django's `Http404` if they can't see it or `PermissionDenied`
with an error message if they can't browse it.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
## `can_delay: Bool = False`
A `bool` that specifies if this check can be delayed. If the category can be
seen by the user but they have no permission to browse it, and both `can_delay`
and `category.delay_browse_check` are `True`, a `PermissionDenied` error
will not be raised.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: Category,
can_delay: bool = False,
) -> None: ...
class CheckBrowseCategoryPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckBrowseCategoryPermissionHookAction`
A standard Misago function used to check if the user has permission to
browse a category. It also checks if the user can see the category.
It raises Django's `Http404` if they can't see it or `PermissionDenied`
with an error message if they can't browse it.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
## `can_delay: Bool = False`
A `bool` that specifies if this check can be delayed. If the category can be
seen by the user but they have no permission to browse it, and both `can_delay`
and `category.delay_browse_check` are `True`, a `PermissionDenied` error
will not be raised.
"""
def __call__(
self,
action: CheckBrowseCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
can_delay: bool = False,
) -> None: ...
class CheckBrowseCategoryPermissionHook(
FilterHook[
CheckBrowseCategoryPermissionHookAction,
CheckBrowseCategoryPermissionHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to check if the user
has permission to browse a category. It also checks if the user can see the
category. It raises Django's `Http404` if they can't see it or `PermissionDenied`
with an error message if they can't browse it.
# Example
The code below implements a custom filter function that blocks a user from
browsing a specified category if there is a custom flag set on their account.
```python
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
from misago.categories.models import Category
from misago.permissions.hooks import check_browse_category_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
@check_browse_category_permission_hook.append_filter
def check_user_can_browse_category(
action,
permissions: UserPermissionsProxy,
category: Category,
) -> None:
# Run standard permission checks
action(permissions, category)
if category.id in permissions.user.plugin_data.get("banned_categories", []):
raise PermissionDenied(
pgettext(
"category permission error",
"Site admin has removed your access to this category."
)
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckBrowseCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
can_delay: bool = False,
) -> None:
return super().__call__(action, permissions, category, can_delay)
check_browse_category_permission_hook = CheckBrowseCategoryPermissionHook()
| 4,398
|
Python
|
.py
| 102
| 36.509804
| 85
| 0.704695
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,571
|
check_start_private_threads_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_start_private_threads_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckStartPrivateThreadsPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has a permission to
start new private threads. Raises Django's `PermissionDenied` with an error
message if they don't.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
) -> None: ...
class CheckStartPrivateThreadsPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckStartPrivateThreadsPermissionHookAction`
A standard Misago function used to check if the user has a permission to
start new private threads. Raises Django's `PermissionDenied` with an error
message if they don't.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
"""
def __call__(
self,
action: CheckStartPrivateThreadsPermissionHookAction,
permissions: "UserPermissionsProxy",
) -> None: ...
class CheckStartPrivateThreadsPermissionHook(
FilterHook[
CheckStartPrivateThreadsPermissionHookAction,
CheckStartPrivateThreadsPermissionHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to check if the user
has a permission to start bew private threads. Raises Django's
`PermissionDenied` with an error message if they don't.
# Example
The code below implements a custom filter function that blocks user from
starting new private threads if there's a custom flag set on their account.
```python
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
from misago.permissions.hooks import check_start_private_threads_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
@check_start_private_threads_permission_hook.append_filter
def check_user_is_banned_from_starting_private_threads(
action,
permissions: UserPermissionsProxy,
) -> None:
# Run standard permission checks
action(permissions)
if permissions.user.plugin_data.get("ban_start_private_threads"):
raise PermissionDenied(
pgettext(
"private threads permission error",
"Site admin has removed your option to start private threads."
)
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckStartPrivateThreadsPermissionHookAction,
permissions: "UserPermissionsProxy",
) -> None:
return super().__call__(action, permissions)
check_start_private_threads_permission_hook = CheckStartPrivateThreadsPermissionHook()
| 3,133
|
Python
|
.py
| 76
| 34.486842
| 86
| 0.716408
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,572
|
check_see_private_thread_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_see_private_thread_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
from ...threads.models import Thread
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckSeePrivateThreadPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has a permission to see
a private thread. Raises Django's `Http404` if they can't.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `thread: Thread`
A thread to check permissions for.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
thread: Thread,
) -> None: ...
class CheckSeePrivateThreadPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckSeePrivateThreadPermissionHookAction`
A standard Misago function used to check if the user has a permission to see
a private thread. Raises Django's `Http404` if they can't.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `thread: Thread`
A thread to check permissions for.
"""
def __call__(
self,
action: CheckSeePrivateThreadPermissionHookAction,
permissions: "UserPermissionsProxy",
thread: Thread,
) -> None: ...
class CheckSeePrivateThreadPermissionHook(
FilterHook[
CheckSeePrivateThreadPermissionHookAction,
CheckSeePrivateThreadPermissionHookFilter,
]
):
"""
This hook wraps the standard Misago function used to check if the user has
a permission to see a private thread. Raises Django's `Http404` if they can't.
# Example
The code below implements a custom filter function that blocks a user from seeing
a specified thread if there is a custom flag set on their account.
```python
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
from misago.permissions.hooks import check_see_private_thread_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
from misago.threads.models import Thread
@check_see_private_thread_permission_hook.append_filter
def check_user_can_see_thread(
action,
permissions: UserPermissionsProxy,
thread: Thread,
) -> None:
# Run standard permission checks
action(permissions, category)
if thread.id in permissions.user.plugin_data.get("banned_thread", []):
raise PermissionDenied(
pgettext(
"thread permission error",
"Site admin has removed your access to this thread."
)
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckSeePrivateThreadPermissionHookAction,
permissions: "UserPermissionsProxy",
thread: Thread,
) -> None:
return super().__call__(action, permissions, thread)
check_see_private_thread_permission_hook = CheckSeePrivateThreadPermissionHook()
| 3,301
|
Python
|
.py
| 84
| 32.583333
| 85
| 0.701413
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,573
|
get_category_threads_category_query.py
|
rafalp_Misago/misago/permissions/hooks/get_category_threads_category_query.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
from ..enums import CategoryQueryContext
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class GetCategoryThreadsCategoryQueryHookAction(Protocol):
"""
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
threads from the given category for displaying on the category threads page.
Standard `WHERE` clauses implemented by Misago can be retrieved from the
`CategoryThreadsQuery` `StrEnum`:
```python
from misago.permissions.enums import CategoryThreadsQuery
```
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
## `context: CategoryQueryContext`
A `CategoryQueryContext` `StrEnum` member describing the `category` position
in the categories tree.
Possible values:
- `CURRENT`: the category for which the threads list is retrieved.
- `CHILD`: a child (or other descendant) category of the current category.
- `OTHER`: a category located elsewhere in the categories tree.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None: ...
class GetCategoryThreadsCategoryQueryHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetCategoryThreadsCategoryQueryHookAction`
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
threads from the given category for displaying on the category threads page.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
## `context: CategoryQueryContext`
A `CategoryQueryContext` `StrEnum` member describing the `category` position
in the categories tree.
Possible values:
- `CURRENT`: the category for which the threads list is retrieved.
- `CHILD`: a child (or other descendant) category of the current category.
- `OTHER`: a category located elsewhere in the categories tree.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
action: GetCategoryThreadsCategoryQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None: ...
class GetCategoryThreadsCategoryQueryHook(
FilterHook[
GetCategoryThreadsCategoryQueryHookAction,
GetCategoryThreadsCategoryQueryHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to get the name of
the predefined database `WHERE` clause (represented as a `Q` object instance)
to use to retrieve threads from the given category for displaying on
the category threads page.
# Example
The code below implements a custom filter function that specifies a custom
`WHERE` clause supported by the `get_threads_query_orm_filter_hook`.
```python
from misago.permissions.enums import CategoryQueryContext
from misago.permissions.hooks import get_category_threads_category_query_hook
from misago.permissions.proxy import UserPermissionsProxy
@get_category_threads_category_query_hook.append_filter
def get_category_threads_category_query(
action,
permissions: UserPermissionsProxy,
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None:
if (
category.get("plugin_flag") and context == CategoryQueryContext.CURRENT
):
return "plugin-where"
return action(permissions, category, context)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetCategoryThreadsCategoryQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None:
return super().__call__(action, permissions, category, context)
get_category_threads_category_query_hook = GetCategoryThreadsCategoryQueryHook()
| 5,077
|
Python
|
.py
| 114
| 38.464912
| 83
| 0.723002
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,574
|
get_admin_category_permissions.py
|
rafalp_Misago/misago/permissions/hooks/get_admin_category_permissions.py
|
# get_stats.py
from typing import Protocol
from ...admin.views.generic import PermissionsFormView
from ...plugins.hooks import ActionHook
class GetAdminCategoryPermissionsHookAction(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `form: PermissionsFormView`
An instance of Admin Category Permissions Form view that implements a `create_permission`
factory function that plugin should use to create new permissions.
## Return value
A list of Python `dict`s with permissions to include in Admin Category Permissions Form.
"""
def __call__(self, form: PermissionsFormView) -> list[dict]: ...
class GetAdminCategoryPermissionsHook(
ActionHook[GetAdminCategoryPermissionsHookAction]
):
"""
This hook lets plugins add permissions to Admin Category Permissions forms.
# Example
The code below implements a custom action that adds `BUMP` and `BURY`
permissions to category permission forms:
```python
from misago.admin.views.generic import PermissionsFormView
from misago.permissions.hooks import get_admin_category_permissions_hook
@get_admin_category_permissions_hook.append_action
def add_plugin_category_permissions(form: PermissionsFormView) -> list[dict]:
return [
form.create_permission(
id="BUMP",
name="Bump threads",
help_text="Allows users to bump threads."
color="#ecfeff",
),
form.create_permission(
id="BURY",
name="Bury threads",
help_text="Allows users to bury threads."
color="#f5f3ff",
),
]
```
To create a `dict` with permission's data, you should use the `create_permission`
method from the `form` instance:
```python
def create_permission(
id: str, name: str, help_text: str | None = None, , color: str | None = None
) -> dict:
...
```
"""
__slots__ = ActionHook.__slots__ # important for memory usage!
def __call__(self, form: PermissionsFormView) -> list[dict]:
permissions: list[dict] = []
for plugin_permissions in super().__call__(form):
permissions += plugin_permissions
return permissions
get_admin_category_permissions_hook = GetAdminCategoryPermissionsHook()
| 2,426
|
Python
|
.py
| 59
| 33.508475
| 93
| 0.666098
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,575
|
check_see_thread_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_see_thread_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
from ...threads.models import Thread
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckSeeThreadPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has a permission to see
a thread. Raises Django's `Http404` if they can't see it or `PermissionDenied`
with an error message if they can't browse it.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
## `thread: Thread`
A thread to check permissions for.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: Category,
thread: Thread,
) -> None: ...
class CheckSeeThreadPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckSeeThreadPermissionHookAction`
A standard Misago function used to check if the user has a permission to see
a thread. Raises Django's `Http404` if they can't see it or `PermissionDenied`
with an error message if they can't browse it.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
## `thread: Thread`
A thread to check permissions for.
"""
def __call__(
self,
action: CheckSeeThreadPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
thread: Thread,
) -> None: ...
class CheckSeeThreadPermissionHook(
FilterHook[
CheckSeeThreadPermissionHookAction,
CheckSeeThreadPermissionHookFilter,
]
):
"""
This hook wraps the standard Misago function used to check if the user has
a permission to see a thread. Raises Django's `Http404` if they can't see
it or `PermissionDenied` with an error message if they can't browse it.
# Example
The code below implements a custom filter function that blocks a user from seeing
a specified thread if there is a custom flag set on their account.
```python
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
from misago.categories.models import Category
from misago.permissions.hooks import check_see_thread_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
from misago.threads.models import Thread
@check_see_thread_permission_hook.append_filter
def check_user_can_see_thread(
action,
permissions: UserPermissionsProxy,
category: Category,
thread: Thread,
) -> None:
# Run standard permission checks
action(permissions, category)
if thread.id in permissions.user.plugin_data.get("banned_thread", []):
raise PermissionDenied(
pgettext(
"thread permission error",
"Site admin has removed your access to this thread."
)
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckSeeThreadPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
thread: Thread,
) -> None:
return super().__call__(action, permissions, category, thread)
check_see_thread_permission_hook = CheckSeeThreadPermissionHook()
| 3,741
|
Python
|
.py
| 96
| 32.260417
| 85
| 0.695484
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,576
|
build_user_permissions.py
|
rafalp_Misago/misago/permissions/hooks/build_user_permissions.py
|
from typing import Protocol
from ...plugins.hooks import FilterHook
from ...users.models import Group
class BuildUserPermissionsHookAction(Protocol):
"""
A standard Misago function used to build user permissions from their groups.
# Arguments
## `groups: list[Group]`
A list of groups user belongs to.
# Return value
A Python `dict` with user permissions build from their groups.
"""
def __call__(self, groups: list[Group]) -> dict: ...
class BuildUserPermissionsHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: BuildUserPermissionsHookAction`
A standard Misago function used to build user permissions from their groups
or the next filter function from another plugin.
See the [action](#action) section for details.
## `groups: list[Group]`
A list of groups user belongs to.
# Return value
A Python `dict` with user permissions build from their groups.
"""
def __call__(
self, action: BuildUserPermissionsHookAction, groups: list[Group]
) -> dict: ...
class BuildUserPermissionsHook(
FilterHook[BuildUserPermissionsHookAction, BuildUserPermissionsHookFilter]
):
"""
This hook wraps the standard function that Misago uses to build user permissions
from their groups.
# Example
The code below implements a custom filter function that includes a custom permission
in user permissions:
```python
from misago.permissions.hooks import build_user_permissions_hook
from misago.users.models import Group
@build_user_permissions_hook.append_filter
def include_plugin_permission(
action, groups: list[Group]
) -> dict:
permissions = action(groups)
permissions["plugin_permission"] = False
for group in groups:
if group.plugin_data.get("plugin_permission"):
permissions["plugin_permission"] = True
return permissions
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self, action: BuildUserPermissionsHookAction, groups: list[Group]
) -> dict:
return super().__call__(action, groups)
build_user_permissions_hook = BuildUserPermissionsHook()
| 2,296
|
Python
|
.py
| 59
| 33.016949
| 88
| 0.706897
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,577
|
get_category_threads_pinned_category_query.py
|
rafalp_Misago/misago/permissions/hooks/get_category_threads_pinned_category_query.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
from ..enums import CategoryQueryContext
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class GetCategoryThreadsPinnedCategoryQueryHookAction(Protocol):
"""
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
pinned threads from the given category for displaying on
the category threads page.
Standard `WHERE` clauses implemented by Misago can be retrieved from the
`CategoryThreadsQuery` `StrEnum`:
```python
from misago.permissions.enums import CategoryThreadsQuery
```
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
## `context: CategoryQueryContext`
A `CategoryQueryContext` `StrEnum` member describing the `category` position
in the categories tree.
Possible values:
- `CURRENT`: the category for which the threads list is retrieved.
- `CHILD`: a child (or other descendant) category of the current category.
- `OTHER`: a category located elsewhere in the categories tree.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving pinned threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None: ...
class GetCategoryThreadsPinnedCategoryQueryHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetCategoryThreadsPinnedCategoryQueryHookAction`
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
pinned threads from the given category for displaying on
the category threads page.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
## `context: CategoryQueryContext`
A `CategoryQueryContext` `StrEnum` member describing the `category` position
in the categories tree.
Possible values:
- `CURRENT`: the category for which the threads list is retrieved.
- `CHILD`: a child (or other descendant) category of the current category.
- `OTHER`: a category located elsewhere in the categories tree.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving pinned threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
action: GetCategoryThreadsPinnedCategoryQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None: ...
class GetCategoryThreadsPinnedCategoryQueryHook(
FilterHook[
GetCategoryThreadsPinnedCategoryQueryHookAction,
GetCategoryThreadsPinnedCategoryQueryHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to get the name of
the predefined database `WHERE` clause (represented as a `Q` object instance)
to use to retrieve pinned threads from the given category for displaying on
the category threads page.
# Example
The code below implements a custom filter function that specifies a custom
`WHERE` clause supported by the `get_threads_query_orm_filter_hook`.
```python
from misago.permissions.enums import CategoryQueryContext
from misago.permissions.hooks import get_category_threads_pinned_category_query_hook
from misago.permissions.proxy import UserPermissionsProxy
@get_category_threads_pinned_category_query_hook.append_filter
def get_category_threads_pinned_category_query(
action,
permissions: UserPermissionsProxy,
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None:
if (
category.get("plugin_flag") and context == CategoryQueryContext.CURRENT
):
return "plugin-where"
return action(permissions, category, context)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetCategoryThreadsPinnedCategoryQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
context: CategoryQueryContext,
) -> str | list[str] | None:
return super().__call__(action, permissions, category, context)
get_category_threads_pinned_category_query_hook = (
GetCategoryThreadsPinnedCategoryQueryHook()
)
| 5,210
|
Python
|
.py
| 118
| 38.152542
| 88
| 0.725922
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,578
|
check_private_threads_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_private_threads_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckPrivateThreadsPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has a permission to access
private threads feature. Raises Django's `PermissionDenied` with an error
message if they don't.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
) -> None: ...
class CheckPrivateThreadsPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckPrivateThreadsPermissionHookAction`
A standard Misago function used to check if the user has a permission to access
private threads feature. Raises Django's `PermissionDenied` with an error
message if they don't.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
"""
def __call__(
self,
action: CheckPrivateThreadsPermissionHookAction,
permissions: "UserPermissionsProxy",
) -> None: ...
class CheckPrivateThreadsPermissionHook(
FilterHook[
CheckPrivateThreadsPermissionHookAction,
CheckPrivateThreadsPermissionHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to check if the user
has a permission to access private threads feature. Raises Django's
`PermissionDenied` with an error message if they don't.
# Example
The code below implements a custom filter function that blocks user from using
private threads if there's a custom flag set on their account.
```python
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
from misago.permissions.hooks import check_private_threads_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
@check_private_threads_permission_hook.append_filter
def check_user_is_banned_from_private_threads(
action,
permissions: UserPermissionsProxy,
) -> None:
# Run standard permission checks
action(permissions)
if permissions.user.plugin_data.get("ban_private_threads"):
raise PermissionDenied(
pgettext(
"private threads permission error",
"Site admin has removed your access to private threads."
)
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckPrivateThreadsPermissionHookAction,
permissions: "UserPermissionsProxy",
) -> None:
return super().__call__(action, permissions)
check_private_threads_permission_hook = CheckPrivateThreadsPermissionHook()
| 3,057
|
Python
|
.py
| 76
| 33.486842
| 83
| 0.71148
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,579
|
get_threads_query_orm_filter.py
|
rafalp_Misago/misago/permissions/hooks/get_threads_query_orm_filter.py
|
from typing import Protocol
from django.db.models import Q
from ...plugins.hooks import FilterHook
from ..enums import CategoryThreadsQuery
class GetThreadsQueryORMFilterHookAction(Protocol):
"""
A standard Misago function used to get Django's `Q` object instance to
retrieve threads using a specified query.
# Arguments
## `query: CategoryThreadsQuery | str`
A `CategoryThreadsQuery` `StrEnum` or a `str` with the name of a query to use.
## `categories: set[int]`
A `set` of `int`s with category IDs.
## `user_id: int | None`
An `int` with the currently authenticated user ID, or `None` if the user
is anonymous.
# Return value
A `Q` object instance to pass to the threads queryset's `filter()`.
"""
def __call__(
self,
query: CategoryThreadsQuery | str,
categories: set[int],
user_id: int | None,
) -> Q | None: ...
class GetThreadsQueryORMFilterHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetThreadsQueryORMFilterHookAction`
A standard Misago function used to get Django's `Q` object instance to
retrieve threads using a specified query.
See the [action](#action) section for details.
## `query: CategoryThreadsQuery | str`
A `CategoryThreadsQuery` `StrEnum` or a `str` with the name of a query to use.
## `categories: set[int]`
A `set` of `int`s with category IDs.
## `user_id: int | None`
An `int` with the currently authenticated user ID, or `None` if the user
is anonymous.
# Return value
A `Q` object instance to pass to the threads queryset's `filter()`.
"""
def __call__(
self,
action: GetThreadsQueryORMFilterHookAction,
query: CategoryThreadsQuery | str,
categories: list[int],
user_id: int | None,
) -> Q | None: ...
class GetThreadsQueryORMFilterHook(
FilterHook[GetThreadsQueryORMFilterHookAction, GetThreadsQueryORMFilterHookFilter]
):
"""
This hook wraps the standard function that Misago uses to get Django's `Q`
object instance to retrieve threads using a specified query.
# Example
The code below implements a custom filter function that specifies a custom
query to use when retrieving the threads list:
```python
from django.db.models import Q
from misago.permissions.hooks import get_threads_query_orm_filter_hook
@get_threads_query_orm_filter_hook.append_filter
def get_category_access_level(
action,
query: str,
categories: set[int],
user_id: int | None,
) -> Q | None:
# Show user only their unapproved threads
if query == "unapproved_only":
return Q(
category_id__in=categories,
starter_id=user_id,
is_unapproved=True,
)
return action(query, categories, user_id)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetThreadsQueryORMFilterHookAction,
query: CategoryThreadsQuery | str,
categories: set[int],
user_id: int | None,
) -> Q | None:
return super().__call__(action, query, categories, user_id)
get_threads_query_orm_filter_hook = GetThreadsQueryORMFilterHook()
| 3,392
|
Python
|
.py
| 89
| 31.494382
| 86
| 0.666258
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,580
|
check_see_category_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_see_category_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckSeeCategoryPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has a permission to see
a category. Raises Django's `Http404` error if they don't.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: Category,
) -> None: ...
class CheckSeeCategoryPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckSeeCategoryPermissionHookAction`
A standard Misago function used to check if the user has a permission to see
a category. Raises Django's `Http404` error if they don't.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
"""
def __call__(
self,
action: CheckSeeCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
) -> None: ...
class CheckSeeCategoryPermissionHook(
FilterHook[
CheckSeeCategoryPermissionHookAction,
CheckSeeCategoryPermissionHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to check if the user
has a permission to see a category. Raises Django's `Http404` error if they don't.
# Example
The code below implements a custom filter function that blocks a user from seeing
a specified category if there is a custom flag set on their account.
```python
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
from misago.categories.models import Category
from misago.permissions.hooks import check_see_category_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
@check_see_category_permission_hook.append_filter
def check_user_can_see_category(
action,
permissions: UserPermissionsProxy,
category: Category,
) -> None:
# Run standard permission checks
action(permissions, category)
if category.id in permissions.user.plugin_data.get("banned_categories", []):
raise PermissionDenied(
pgettext(
"category permission error",
"Site admin has removed your access to this category."
)
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckSeeCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
) -> None:
return super().__call__(action, permissions, category)
check_see_category_permission_hook = CheckSeeCategoryPermissionHook()
| 3,255
|
Python
|
.py
| 83
| 32.433735
| 86
| 0.7
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,581
|
get_category_threads_query.py
|
rafalp_Misago/misago/permissions/hooks/get_category_threads_query.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
from ..enums import CategoryQueryContext
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class GetCategoryThreadsQueryHookAction(Protocol):
"""
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
threads from the given category.
Standard `WHERE` clauses implemented by Misago can be retrieved from the
`CategoryThreadsQuery` `StrEnum`:
```python
from misago.permissions.enums import CategoryThreadsQuery
```
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None: ...
class GetCategoryThreadsQueryHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetCategoryThreadsQueryHookAction`
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
threads from the given category.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving threads will skip this category. If multiple
clauses should be `OR`ed together, a list of strings or `CategoryThreadsQuery`
members can be returned.
"""
def __call__(
self,
action: GetCategoryThreadsQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None: ...
class GetCategoryThreadsQueryHook(
FilterHook[
GetCategoryThreadsQueryHookAction,
GetCategoryThreadsQueryHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to get the name of
the predefined database `WHERE` clause (represented as a `Q` object instance)
to use to retrieve threads from the given category.
# Example
The code below implements a custom filter function that specifies a custom
`WHERE` clause supported by the `get_threads_query_orm_filter_hook`.
```python
from misago.permissions.hooks import get_category_threads_query_hook
from misago.permissions.proxy import UserPermissionsProxy
@get_category_threads_query_hook.append_filter
def get_category_threads_query(
action,
permissions: UserPermissionsProxy,
category: dict,
) -> str | list[str] | None:
if (
category.get("plugin_flag") and context == CategoryQueryContext.CURRENT
):
return "plugin-where"
return action(permissions, category)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetCategoryThreadsQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None:
return super().__call__(action, permissions, category)
get_category_threads_query_hook = GetCategoryThreadsQueryHook()
| 3,815
|
Python
|
.py
| 94
| 34.542553
| 83
| 0.708118
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,582
|
filter_thread_posts_queryset.py
|
rafalp_Misago/misago/permissions/hooks/filter_thread_posts_queryset.py
|
from typing import TYPE_CHECKING, Protocol
from django.db.models import QuerySet
from ...plugins.hooks import FilterHook
from ...threads.models import Thread
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class FilterThreadPostsQuerysetHookAction(Protocol):
"""
A standard Misago function used to set filters on a queryset used to retrieve
specified thread's posts that user can see.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `thread: Thread`
A thread instance which's posts are retrieved.
## `queryset: Queryset`
A queryset returning thread's posts.
## Return value
A `queryset` filtered to show only thread posts that the user can see.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
thread: Thread,
queryset: QuerySet,
) -> QuerySet: ...
class FilterThreadPostsQuerysetHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: FilterThreadPostsQuerysetHookAction`
A standard Misago function used to set filters on a queryset used to retrieve
specified thread's posts that user can see.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `thread: Thread`
A thread instance which's posts are retrieved.
## `queryset: Queryset`
A queryset returning thread's posts.
## Return value
A `queryset` filtered to show only thread posts that the user can see.
"""
def __call__(
self,
action: FilterThreadPostsQuerysetHookAction,
permissions: "UserPermissionsProxy",
thread: Thread,
queryset: QuerySet,
) -> QuerySet: ...
class FilterThreadPostsQuerysetHook(
FilterHook[
FilterThreadPostsQuerysetHookAction,
FilterThreadPostsQuerysetHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses set filters on
thread's posts queryset to limit it only to posts that the user can see.
# Example
The code below implements a custom filter function hides deleted posts from
anonymous user.
```python
from misago.permissions.hooks import filter_thread_posts_queryset_hook
from misago.permissions.proxy import UserPermissionsProxy
@filter_thread_posts_queryset_hook.append_filter
def exclude_old_private_threads_queryset_hook(
action,
permissions: UserPermissionsProxy,
thread,
queryset,
) -> None:
queryset = action(permissions, thread, queryset)
if permissions.user.is_anonymous:
return queryset.filter(is_hidden=False)
return queryset
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: FilterThreadPostsQuerysetHookAction,
permissions: "UserPermissionsProxy",
thread: Thread,
queryset: QuerySet,
) -> QuerySet:
return super().__call__(action, permissions, thread, queryset)
filter_thread_posts_queryset_hook = FilterThreadPostsQuerysetHook()
| 3,272
|
Python
|
.py
| 88
| 30.977273
| 81
| 0.707511
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,583
|
__init__.py
|
rafalp_Misago/misago/permissions/hooks/__init__.py
|
from .build_user_category_permissions import build_user_category_permissions_hook
from .build_user_permissions import build_user_permissions_hook
from .check_browse_category_permission import check_browse_category_permission_hook
from .check_post_in_closed_category_permission import (
check_post_in_closed_category_permission_hook,
)
from .check_private_threads_permission import check_private_threads_permission_hook
from .check_see_category_permission import check_see_category_permission_hook
from .check_see_private_thread_permission import (
check_see_private_thread_permission_hook,
)
from .check_see_thread_permission import check_see_thread_permission_hook
from .check_start_private_threads_permission import (
check_start_private_threads_permission_hook,
)
from .check_start_thread_in_category_permission import (
check_start_thread_in_category_permission_hook,
)
from .copy_category_permissions import copy_category_permissions_hook
from .copy_group_permissions import copy_group_permissions_hook
from .filter_private_thread_posts_queryset import (
filter_private_thread_posts_queryset_hook,
)
from .filter_private_threads_queryset import filter_private_threads_queryset_hook
from .filter_thread_posts_queryset import filter_thread_posts_queryset_hook
from .get_admin_category_permissions import get_admin_category_permissions_hook
from .get_category_threads_category_query import (
get_category_threads_category_query_hook,
)
from .get_category_threads_pinned_category_query import (
get_category_threads_pinned_category_query_hook,
)
from .get_category_threads_query import get_category_threads_query_hook
from .get_threads_category_query import get_threads_category_query_hook
from .get_threads_pinned_category_query import get_threads_pinned_category_query_hook
from .get_threads_query_orm_filter import get_threads_query_orm_filter_hook
from .get_user_permissions import get_user_permissions_hook
__all__ = [
"build_user_category_permissions_hook",
"build_user_permissions_hook",
"check_browse_category_permission_hook",
"check_post_in_closed_category_permission_hook",
"check_private_threads_permission_hook",
"check_see_category_permission_hook",
"check_see_private_thread_permission_hook",
"check_see_thread_permission_hook",
"check_start_private_threads_permission_hook",
"check_start_thread_in_category_permission_hook",
"copy_category_permissions_hook",
"copy_group_permissions_hook",
"filter_private_thread_posts_queryset_hook",
"filter_private_threads_queryset_hook",
"filter_thread_posts_queryset_hook",
"get_admin_category_permissions_hook",
"get_category_threads_category_query_hook",
"get_category_threads_pinned_category_query_hook",
"get_category_threads_query_hook",
"get_threads_category_query_hook",
"get_threads_pinned_category_query_hook",
"get_threads_query_orm_filter_hook",
"get_user_permissions_hook",
]
| 2,964
|
Python
|
.py
| 62
| 44.854839
| 85
| 0.797311
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,584
|
check_post_in_closed_category_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_post_in_closed_category_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckPostInClosedCategoryPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has permission to
post in a closed category. It raises Django's `PermissionDenied` with an
error message if category is closed and they can't post in it.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: Category,
) -> None: ...
class CheckPostInClosedCategoryPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckPostInClosedCategoryPermissionHookAction`
A standard Misago function used to check if the user has permission to
post in a closed category. It raises Django's `PermissionDenied` with an
error message if category is closed and they can't post in it.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
"""
def __call__(
self,
action: CheckPostInClosedCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
) -> None: ...
class CheckPostInClosedCategoryPermissionHook(
FilterHook[
CheckPostInClosedCategoryPermissionHookAction,
CheckPostInClosedCategoryPermissionHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to check if the user
has permission to post in a closed category. It raises Django's `PermissionDenied`
with an error message if category is closed and they can't post in it.
# Example
The code below implements a custom filter function that permits a user to
post in the specific category if they have a custom flag set on their account.
```python
from misago.categories.models import Category
from misago.permissions.hooks import check_post_in_closed_category_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
@check_post_in_closed_category_permission_hook.append_filter
def check_user_can_post_in_closed_category(
action,
permissions: UserPermissionsProxy,
category: Category,
) -> None:
user = permissions.user
if user.is_authenticated:
post_in_closed_categories = (
user.plugin_data.get("post_in_closed_categories") or []
)
else:
post_in_closed_categories = None
if (
not post_in_closed_categories
or category.id not in post_in_closed_categories
):
action(permissions, category)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckPostInClosedCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
) -> None:
return super().__call__(action, permissions, category)
check_post_in_closed_category_permission_hook = (
CheckPostInClosedCategoryPermissionHook()
)
| 3,548
|
Python
|
.py
| 89
| 33.292135
| 86
| 0.707908
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,585
|
check_start_thread_in_category_permission.py
|
rafalp_Misago/misago/permissions/hooks/check_start_thread_in_category_permission.py
|
from typing import TYPE_CHECKING, Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class CheckStartThreadInCategoryPermissionHookAction(Protocol):
"""
A standard Misago function used to check if the user has permission to
start a new thread in a category. It raises Django's `PermissionDenied` with
an error message if they can't start thread in a category.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: Category,
) -> None: ...
class CheckStartThreadInCategoryPermissionHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CheckStartThreadInCategoryPermissionHookAction`
A standard Misago function used to check if the user has permission to
start a new thread in a category. It raises Django's `PermissionDenied` with
an error message if they can't start thread in a category.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: Category`
A category to check permissions for.
"""
def __call__(
self,
action: CheckStartThreadInCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
) -> None: ...
class CheckStartThreadInCategoryPermissionHook(
FilterHook[
CheckStartThreadInCategoryPermissionHookAction,
CheckStartThreadInCategoryPermissionHookFilter,
]
):
"""
This hook wraps the standard Misago function used to check if the user has
permission to start a new thread in a category. It raises Django's
`PermissionDenied` with an error message if they can't start thread in a category.
# Example
The code below implements a custom filter function that prevents the user from
starting a thread in category if their account is newer than 7 days.
```python
from datetime import timedelta
from django.core.exceptions import PermissionDenied
from django.utils import timezone
from misago.categories.models import Category
from misago.permissions.hooks import check_start_thread_in_category_permission_hook
from misago.permissions.proxy import UserPermissionsProxy
@check_start_thread_in_category_permission_hook.append_filter
def check_user_can_start_thread(
action,
permissions: UserPermissionsProxy,
category: Category,
) -> None:
action(permissions, category)
user = permissions.user
if (
user.is_authenticated
and user.joined_on > timezone.now() - timedelta(days=7):
):
raise PermissionDenied(
"Your account was created less than 7 days ago. "
"You can't start threads yet."
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CheckStartThreadInCategoryPermissionHookAction,
permissions: "UserPermissionsProxy",
category: Category,
) -> None:
return super().__call__(action, permissions, category)
check_start_thread_in_category_permission_hook = (
CheckStartThreadInCategoryPermissionHook()
)
| 3,608
|
Python
|
.py
| 90
| 33.611111
| 87
| 0.713056
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,586
|
filter_private_threads_queryset.py
|
rafalp_Misago/misago/permissions/hooks/filter_private_threads_queryset.py
|
from typing import TYPE_CHECKING, Protocol
from django.db.models import QuerySet
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class FilterPrivateThreadsQuerysetHookAction(Protocol):
"""
A standard Misago function used to set filters on a private threads queryset
to limit it only to threads that the user has access to.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `queryset: Queryset`
A queryset returning all private threads.
## Return value
A `queryset` filtered to show only private threads that the user has access to.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
queryset: QuerySet,
) -> QuerySet: ...
class FilterPrivateThreadsQuerysetHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: FilterPrivateThreadsQuerysetHookAction`
A standard Misago function used to set filters on a private threads queryset to limit
it only to threads that the user has access to.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `queryset: Queryset`
A queryset returning all private threads.
## Return value
A `queryset` filtered to show only private threads that the user has access to.
"""
def __call__(
self,
action: FilterPrivateThreadsQuerysetHookAction,
permissions: "UserPermissionsProxy",
queryset: QuerySet,
) -> QuerySet: ...
class FilterPrivateThreadsQuerysetHook(
FilterHook[
FilterPrivateThreadsQuerysetHookAction,
FilterPrivateThreadsQuerysetHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses set filters on
a private threads queryset to limit it only to threads that the user has access to.
# Example
The code below implements a custom filter function that makes old private threads
not available to the user.
```python
from datetime import timedelta
from django.utils import timezone
from misago.permissions.hooks import filter_private_threads_queryset_hook
from misago.permissions.proxy import UserPermissionsProxy
@filter_private_threads_queryset_hook.append_filter
def exclude_old_private_threads_queryset_hook(
action,
permissions: UserPermissionsProxy,
queryset,
) -> None:
queryset = action(permissions, queryset)
if permissions.private_threads_moderator:
return queryset
return queryset.filter(
last_post_on__gt=timezone.now - timedelta(days=30),
)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: FilterPrivateThreadsQuerysetHookAction,
permissions: "UserPermissionsProxy",
queryset: QuerySet,
) -> QuerySet:
return super().__call__(action, permissions, queryset)
filter_private_threads_queryset_hook = FilterPrivateThreadsQuerysetHook()
| 3,231
|
Python
|
.py
| 83
| 32.710843
| 89
| 0.717916
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,587
|
build_user_category_permissions.py
|
rafalp_Misago/misago/permissions/hooks/build_user_category_permissions.py
|
from typing import Protocol
from ...categories.models import Category
from ...plugins.hooks import FilterHook
from ...users.models import Group
class BuildUserCategoryPermissionsHookAction(Protocol):
"""
A standard Misago function used to get user category permissions.
# Arguments
## `groups: list[Group]`
A list of groups user belongs to.
## `categories: dict[int, Category]`
A `dict` of categories.
## `category_permissions: dict[int, list[str]]`
A Python `dict` containing lists of category permissions read from the database,
indexed by category IDs.
## `user_permissions: dict`
A Python `dict` with user permissions build so far.
# Return value
A Python `dict` with category permissions.
"""
def __call__(
self,
groups: list[Group],
categories: dict[int, Category],
category_permissions: dict[int, list[str]],
user_permissions: dict,
) -> dict: ...
class BuildUserCategoryPermissionsHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: BuildUserCategoryPermissionsHookAction`
A standard Misago function used to build user category permissions or the next
filter function from another plugin.
See the [action](#action) section for details.
## `groups: list[Group]`
A list of groups user belongs to.
## `categories: dict[int, Category]`
A `dict` of categories.
## `category_permissions: dict[int, list[str]]`
A Python `dict` containing lists of category permissions read from the database,
indexed by category IDs.
## `user_permissions: dict`
A Python `dict` with user permissions build so far.
# Return value
A Python `dict` with category permissions.
"""
def __call__(
self,
action: BuildUserCategoryPermissionsHookAction,
groups: list[Group],
categories: dict[int, Category],
category_permissions: dict[int, list[str]],
user_permissions: dict,
) -> dict: ...
class BuildUserCategoryPermissionsHook(
FilterHook[
BuildUserCategoryPermissionsHookAction, BuildUserCategoryPermissionsHookFilter
]
):
"""
This hook wraps the standard function that Misago uses to build user category
permissions.
Category permissions are stored as a Python `dict` with permission names as keys
and values being category IDs with the associated permission:
```python
category_permissions = {
"see": [1, 2, 3],
"browse": [1, 2, 3],
"start": [1, 2],
"reply": [1, 2, 3],
"attachments": [1, 2, 3],
}
```
Plugins can add custom permissions to this dict.
# Example
The code below implements a custom filter function that includes a custom
permission in user's category permissions, if they can browse it:
```python
from misago.categories.models import Category
from misago.permissions.enums import CategoryPermission
from misago.permissions.hooks import build_user_category_permissions_hook
from misago.users.models import Group
@build_user_category_permissions_hook.append_filter
def include_plugin_permission(
action,
groups: list[Group],
categories: dict[int, Category],
category_permissions: dict[int, list[str]],
user_permissions: dict,
) -> dict:
permissions = action(group, categories, category_permissions, user_permissions)
permissions["plugin"] = []
for category_id in categories:
if (
category_id in permissions[CategoryPermission.BROWSE]
and "plugin" in category_permissions.get(category_id, [])
):
permissions["plugin"].append(category_id)
return permissions
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: BuildUserCategoryPermissionsHookAction,
groups: list[Group],
categories: dict[int, Category],
category_permissions: dict[int, list[str]],
user_permissions: dict,
) -> dict:
return super().__call__(
action, groups, categories, category_permissions, user_permissions
)
build_user_category_permissions_hook = BuildUserCategoryPermissionsHook()
| 4,396
|
Python
|
.py
| 115
| 31.417391
| 87
| 0.676352
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,588
|
get_category_access_level.py
|
rafalp_Misago/misago/permissions/hooks/get_category_access_level.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class GetCategoryAccessLevelHookAction(Protocol):
"""
A standard Misago function used to get a user's access level for a category.
Access levels are used to build the final threads queryset for thread lists.
Default levels are:
- `moderator`: the user is a moderator for this category.
- `started_only` the user can see only the pinned threads or ones they started.
- `default`: the user has default access to threads in this category.
The enum with all access levels is also available:
```python
from misago.permissions.enums import CategoryAccess
CategoryAccess.MODERATOR
CategoryAccess.STARTED_ONLY
CategoryAccess.DEFAULT
```
Plugins can define custom levels by returning a `str` with their value.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryAccess` member or a `str` with a custom access level. If `none`,
threads from this category are excluded from the threads list.
"""
def __call__(
self,
user_permissions: "UserPermissionsProxy",
category: dict,
) -> str | None: ...
class GetCategoryAccessLevelHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetCategoryAccessLevelHookAction`
A standard Misago function used to get a user's access level for a category.
Access levels are used to build the final threads queryset for thread lists.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryAccess` member or a `str` with a custom access level. If `none`,
threads from this category are excluded from the threads list.
"""
def __call__(
self,
action: GetCategoryAccessLevelHookAction,
user_permissions: "UserPermissionsProxy",
category: dict,
) -> str | None: ...
class GetCategoryAccessLevelHook(
FilterHook[GetCategoryAccessLevelHookAction, GetCategoryAccessLevelHookFilter]
):
"""
This hook wraps the standard function that Misago uses to get category's access level
for the user.
# Example
The code below implements a custom filter function that specifies a custom access level
for categories that have special attribute set by the `get_category_data` hook:
```python
from misago.permissions.hooks import get_category_access_level_hook
from misago.permissions.proxy import UserPermissionsProxy
@get_category_access_level_hook.append_filter
def get_category_access_level(
action,
user_permissions: UserPermissionsProxy,
category: dict,
) -> str | None:
if category["special_access"]:
return "special_level"
return action(user_permissions, category)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetCategoryAccessLevelHookAction,
user_permissions: "UserPermissionsProxy",
category: dict,
) -> str | None:
return super().__call__(action, user_permissions, category)
get_category_access_level_hook = GetCategoryAccessLevelHook()
| 3,612
|
Python
|
.py
| 88
| 35.068182
| 91
| 0.71367
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,589
|
filter_private_thread_posts_queryset.py
|
rafalp_Misago/misago/permissions/hooks/filter_private_thread_posts_queryset.py
|
from typing import TYPE_CHECKING, Protocol
from django.db.models import QuerySet
from ...plugins.hooks import FilterHook
from ...threads.models import Thread
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class FilterPrivateThreadPostsQuerysetHookAction(Protocol):
"""
A standard Misago function used to set filters on a queryset used to retrieve
specified private thread's posts that user can see.
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `thread: Thread`
A private thread instance which's posts are retrieved.
## `queryset: Queryset`
A queryset returning thread's posts.
## Return value
A `queryset` filtered to show only thread posts that the user can see.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
thread: Thread,
queryset: QuerySet,
) -> QuerySet: ...
class FilterPrivateThreadPostsQuerysetHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: FilterPrivateThreadPostsQuerysetHookAction`
A standard Misago function used to set filters on a queryset used to retrieve
specified private thread's posts that user can see.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `thread: Thread`
A private thread instance which's posts are retrieved.
## `queryset: Queryset`
A queryset returning thread's posts.
## Return value
A `queryset` filtered to show only thread posts that the user can see.
"""
def __call__(
self,
action: FilterPrivateThreadPostsQuerysetHookAction,
permissions: "UserPermissionsProxy",
thread: Thread,
queryset: QuerySet,
) -> QuerySet: ...
class FilterPrivateThreadPostsQuerysetHook(
FilterHook[
FilterPrivateThreadPostsQuerysetHookAction,
FilterPrivateThreadPostsQuerysetHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses set filters on private
thread's posts queryset to limit it only to posts that the user can see.
# Example
The code below implements a custom filter function hides deleted posts from
anonymous user.
```python
from misago.permissions.hooks import filter_private_thread_posts_queryset_hook
from misago.permissions.proxy import UserPermissionsProxy
@filter_private_thread_posts_queryset_hook.append_filter
def exclude_old_private_threads_queryset_hook(
action,
permissions: UserPermissionsProxy,
thread,
queryset,
) -> None:
queryset = action(permissions, thread, queryset)
if permissions.user.is_anonymous:
return queryset.filter(is_hidden=False)
return queryset
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: FilterPrivateThreadPostsQuerysetHookAction,
permissions: "UserPermissionsProxy",
thread: Thread,
queryset: QuerySet,
) -> QuerySet:
return super().__call__(action, permissions, thread, queryset)
filter_private_thread_posts_queryset_hook = FilterPrivateThreadPostsQuerysetHook()
| 3,399
|
Python
|
.py
| 88
| 32.420455
| 82
| 0.716427
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,590
|
copy_group_permissions.py
|
rafalp_Misago/misago/permissions/hooks/copy_group_permissions.py
|
from typing import Protocol
from django.http import HttpRequest
from ...plugins.hooks import FilterHook
from ...users.models import Group
class CopyGroupPermissionsHookAction(Protocol):
"""
A standard Misago function used to copy permissions from one user group to another
or the next filter function from another plugin.
# Arguments
## `src: Group`
A group to copy permissions from.
## `dst: Group`
A group to copy permissions to.
## `request: Optional[HttpRequest]`
The request object or `None` if it was not provided.
"""
def __call__(
self,
src: Group,
dst: Group,
request: HttpRequest | None = None,
) -> None: ...
class CopyGroupPermissionsHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CopyGroupPermissionsHookAction`
A standard Misago function used to copy permissions from one user group to another
or the next filter function from another plugin.
See the [action](#action) section for details.
## `src: Group`
A group to copy permissions from.
## `dst: Group`
A group to copy permissions to.
## `request: Optional[HttpRequest]`
The request object or `None` if it was not provided.
"""
def __call__(
self,
action: CopyGroupPermissionsHookAction,
src: Group,
dst: Group,
request: HttpRequest | None = None,
) -> None: ...
class CopyGroupPermissionsHook(
FilterHook[CopyGroupPermissionsHookAction, CopyGroupPermissionsHookFilter]
):
"""
This hook wraps the standard function that Misago uses to copy group permissions.
# Example
The code below implements a custom filter function that copies a permission from
one group's `plugin_data` to the other:
```python
from django.http import HttpRequest
from misago.permissions.hooks import copy_group_permissions_hook
from misago.users.models import Group
@copy_group_permissions_hook.append_filter
def copy_group_plugin_perms(
action, src: Group, dst: Group, request: HttpRequest | None = None,
) -> None:
dst.plugin_data["can_do_plugin_thing"] = src.plugin_data["can_do_plugin_thing"]
# Call the next function in chain
return action(group, **kwargs)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CopyGroupPermissionsHookAction,
src: Group,
dst: Group,
request: HttpRequest | None = None,
) -> None:
return super().__call__(action, src, dst, request)
copy_group_permissions_hook = CopyGroupPermissionsHook()
| 2,734
|
Python
|
.py
| 75
| 30.426667
| 87
| 0.683066
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,591
|
copy_category_permissions.py
|
rafalp_Misago/misago/permissions/hooks/copy_category_permissions.py
|
from typing import Protocol
from django.http import HttpRequest
from ...categories.models import Category
from ...plugins.hooks import FilterHook
class CopyCategoryPermissionsHookAction(Protocol):
"""
A standard Misago function used to copy permissions from one category to another
or the next filter function from another plugin.
# Arguments
## `src: Category`
A category to copy permissions from.
## `dst: Category`
A category to copy permissions to.
## `request: Optional[HttpRequest]`
The request object or `None` if it was not provided.
"""
def __call__(
self,
src: Category,
dst: Category,
request: HttpRequest | None = None,
) -> None: ...
class CopyCategoryPermissionsHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: CopyCategoryPermissionsHookAction`
A standard Misago function used to copy permissions from one category to another
or the next filter function from another plugin.
See the [action](#action) section for details.
## `src: Category`
A category to copy permissions from.
## `dst: Category`
A category to copy permissions to.
## `request: Optional[HttpRequest]`
The request object or `None` if it was not provided.
"""
def __call__(
self,
action: CopyCategoryPermissionsHookAction,
src: Category,
dst: Category,
request: HttpRequest | None = None,
) -> None: ...
class CopyCategoryPermissionsHook(
FilterHook[CopyCategoryPermissionsHookAction, CopyCategoryPermissionsHookFilter]
):
"""
This hook wraps the standard function that Misago uses to copy category permissions.
# Example
The code below implements a custom filter function that copies additional models with
the plugin's category permissions:
```python
from django.http import HttpRequest
from misago.permissions.hooks import copy_category_permissions_hook
from misago.users.models import Category
from .models PluginCategoryPermissions
@copy_category_permissions_hook.append_filter
def copy_group_plugin_perms(
action, src: Category, dst: Category, request: HttpRequest | None = None,
) -> None:
# Delete old permissions
PluginCategoryPermissions.objects.filter(category=dst).delete()
# Copy permissions
for permission in PluginCategoryPermissions.objects.filter(category=src):
PluginCategoryPermissions.objects.create(
category=dst,
group_id=permission.group_id,
can_do_something=permission.can_do_something,
)
# Call the next function in chain
return action(group, **kwargs)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: CopyCategoryPermissionsHookAction,
src: Category,
dst: Category,
request: HttpRequest | None = None,
) -> None:
return super().__call__(action, src, dst, request)
copy_category_permissions_hook = CopyCategoryPermissionsHook()
| 3,205
|
Python
|
.py
| 84
| 31.452381
| 89
| 0.692408
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,592
|
get_user_permissions.py
|
rafalp_Misago/misago/permissions/hooks/get_user_permissions.py
|
from typing import Protocol
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from ...plugins.hooks import FilterHook
User = get_user_model()
class GetUserPermissionsHookAction(Protocol):
"""
A standard Misago function used to get user permissions.
Retrieves permissions data from cache or builds new ones.
# Arguments
## `user: User | AnonymousUser`
A user to return permissions for.
## `cache_versions: dict`
A Python `dict` with cache versions.
# Return value
A Python `dict` with user permissions.
"""
def __call__(self, user: User | AnonymousUser, cache_versions: dict) -> dict: ...
class GetUserPermissionsHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetUserPermissionsHookAction`
A standard Misago function used to get user permissions or the next filter
function from another plugin.
See the [action](#action) section for details.
## `user: User | AnonymousUser`
A user to return permissions for.
## `cache_versions: dict`
A Python `dict` with cache versions.
# Return value
A Python `dict` with user permissions.
"""
def __call__(
self,
action: GetUserPermissionsHookAction,
user: User | AnonymousUser,
cache_versions: dict,
) -> dict: ...
class GetUserPermissionsHook(
FilterHook[GetUserPermissionsHookAction, GetUserPermissionsHookFilter]
):
"""
This hook wraps the standard function that Misago uses to get user permissions.
User permissions are a Python `dict`. This `dict` is first retrieved from the cache,
and if that fails, a new `dict` is built from the user's groups.
Plugins can use this hook to make additional changes to the final Python `dict`
based on user data.
# Example
The code below implements a custom filter function that includes a custom
permission into the final user permissions, retrieved from their
`plugin_data` attribute:
```python
from django.contrib.auth.models import AnonymousUser
from misago.permissions.hooks import build_user_permissions_hook
from misago.users.models import User
@get_user_permissions_hook.append_filter
def include_plugin_permission(
action, user: User | AnonymousUser, cache_versions: dict
) -> dict:
permissions = action(user, cache_versions)
permissions["plugin_permission"] = False
if user.plugin_data.get("plugin_permission"):
permissions["plugin_permission"] = True
return permissions
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetUserPermissionsHookAction,
user: User | AnonymousUser,
cache_versions: dict,
) -> dict:
return super().__call__(action, user, cache_versions)
get_user_permissions_hook = GetUserPermissionsHook()
| 3,019
|
Python
|
.py
| 76
| 33.855263
| 88
| 0.707342
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,593
|
get_threads_pinned_category_query.py
|
rafalp_Misago/misago/permissions/hooks/get_threads_pinned_category_query.py
|
from typing import TYPE_CHECKING, Protocol
from ...plugins.hooks import FilterHook
if TYPE_CHECKING:
from ..proxy import UserPermissionsProxy
class GetThreadsCategoryPinnedQueryHookAction(Protocol):
"""
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
pinned threads from the given category for displaying on the threads page.
Standard `WHERE` clauses implemented by Misago can be retrieved from the
`CategoryThreadsQuery` `StrEnum`:
```python
from misago.permissions.enums import CategoryThreadsQuery
```
# Arguments
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving pinned threads will skip this category. If
multiple clauses should be `OR`ed together, a list of strings or
`CategoryThreadsQuery` members can be returned.
"""
def __call__(
self,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None: ...
class GetThreadsCategoryPinnedQueryHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Arguments
## `action: GetThreadsCategoryPinnedQueryHookAction`
A standard Misago function used to get the name of the predefined database
`WHERE` clause (represented as a `Q` object instance) to use to retrieve
pinned threads from the given category for displaying on the threads page.
See the [action](#action) section for details.
## `user_permissions: UserPermissionsProxy`
A proxy object with the current user's permissions.
## `category: dict`
A `dict` with category data.
# Return value
A `CategoryThreadsQuery` member or a `str` with a custom clause name. If
`None`, the query retrieving pinned threads will skip this category. If
multiple clauses should be `OR`ed together, a list of strings or
`CategoryThreadsQuery` members can be returned.
"""
def __call__(
self,
action: GetThreadsCategoryPinnedQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None: ...
class GetThreadsCategoryPinnedQueryHook(
FilterHook[
GetThreadsCategoryPinnedQueryHookAction,
GetThreadsCategoryPinnedQueryHookFilter,
]
):
"""
This hook wraps the standard function that Misago uses to get the name of
the predefined database `WHERE` clause (represented as a `Q` object instance)
to use to retrieve pinned threads from the given category for displaying on
the threads page.
# Example
The code below implements a custom filter function that specifies a custom
`WHERE` clause supported by the `get_threads_query_orm_filter_hook`.
```python
from misago.permissions.hooks import get_threads_pinned_category_query_hook
from misago.permissions.proxy import UserPermissionsProxy
@get_threads_pinned_category_query_hook.append_filter
def get_threads_category_pinned_query(
action,
permissions: UserPermissionsProxy,
category: dict,
) -> str | list[str] | None:
if category.get("plugin_flag"):
return "plugin-where"
return action(permissions, category)
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self,
action: GetThreadsCategoryPinnedQueryHookAction,
permissions: "UserPermissionsProxy",
category: dict,
) -> str | list[str] | None:
return super().__call__(action, permissions, category)
get_threads_pinned_category_query_hook = GetThreadsCategoryPinnedQueryHook()
| 3,932
|
Python
|
.py
| 92
| 36.76087
| 81
| 0.718306
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,594
|
urls.py
|
rafalp_Misago/misago/posting/urls.py
|
from django.urls import path
from .views.selectcategory import SelectCategoryView
from .views.start import StartPrivateThreadView, StartThreadView
urlpatterns = [
path(
"start-thread/",
SelectCategoryView.as_view(),
name="start-thread",
),
path(
"c/<slug:slug>/<int:id>/start-thread/",
StartThreadView.as_view(),
name="start-thread",
),
path(
"private/start-thread/",
StartPrivateThreadView.as_view(),
name="start-private-thread",
),
]
| 535
|
Python
|
.py
| 20
| 20.8
| 64
| 0.644531
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,595
|
apps.py
|
rafalp_Misago/misago/posting/apps.py
|
from django.apps import AppConfig
class MisagoPostingConfig(AppConfig):
name = "misago.posting"
label = "misago_posting"
verbose_name = "Misago Posting"
| 167
|
Python
|
.py
| 5
| 29.6
| 37
| 0.75625
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,596
|
selectcategory.py
|
rafalp_Misago/misago/posting/views/selectcategory.py
|
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpRequest, HttpResponse
from django.views import View
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import pgettext
from ...categories.models import Category
from ...permissions.threads import check_start_thread_in_category_permission
class SelectCategoryView(View):
template_name = "misago/posting/select_category/page.html"
template_name_htmx = "misago/posting/select_category/modal.html"
def get(self, request: HttpRequest) -> HttpResponse:
choices = self.get_category_choices(request)
if request.is_htmx:
template_name = self.template_name_htmx
else:
template_name = self.template_name
if not choices and not request.is_htmx:
raise PermissionDenied(
pgettext(
"start thread page",
"You can't start new threads.",
)
)
return render(request, template_name, {"start_thread_choices": choices})
def get_category_choices(self, request: HttpRequest) -> list[dict]:
queryset = Category.objects.filter(
id__in=list(request.categories.categories),
).order_by("lft")
choices: list[dict] = []
for category in queryset:
try:
check_start_thread_in_category_permission(
request.user_permissions, category
)
except (Http404, PermissionDenied):
has_permission = False
else:
has_permission = True
choice = {
"id": category.id,
"name": category.name,
"description": category.description,
"color": category.color,
"level": "",
"is_vanilla": category.is_vanilla,
"disabled": category.is_vanilla or not has_permission,
"url": reverse(
"misago:start-thread",
kwargs={"id": category.id, "slug": category.slug},
),
"category": category,
}
if category.level == 1:
choice["children"] = []
choices.append(choice)
else:
parent = choices[-1]
choice["level"] = "1" * (category.level - 1)
parent["children"].append(choice)
# Remove branches where entire branch is disabled
clean_choices: list[dict] = []
for category in choices:
clean_children: list[dict] = []
for child in reversed(category["children"]):
if not child["disabled"] or (
clean_children and clean_children[-1]["level"] > child["level"]
):
clean_children.append(child)
if not category["disabled"] or clean_children:
category["children"] = list(reversed(clean_children))
clean_choices.append(category)
return clean_choices
| 3,150
|
Python
|
.py
| 73
| 30.452055
| 83
| 0.570356
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,597
|
start.py
|
rafalp_Misago/misago/posting/views/start.py
|
from django.http import Http404, HttpRequest, HttpResponse
from django.views import View
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.translation import pgettext
from ...auth.decorators import login_required
from ...categories.enums import CategoryTree
from ...categories.models import Category
from ...permissions.categories import check_browse_category_permission
from ...permissions.privatethreads import (
check_private_threads_permission,
check_start_private_threads_permission,
)
from ...permissions.threads import check_start_thread_in_category_permission
from ...threads.models import Thread
from ..forms.start import (
StartPrivateThreadForm,
StartThreadForm,
StartThreadFormset,
)
from ..state.start import StartPrivateThreadState, StartThreadState
def start_thread_login_required():
return login_required(
pgettext(
"start thread page",
"Sign in to start new thread",
)
)
class StartThreadView(View):
template_name: str = "misago/posting/start_thread.html"
state_class = StartThreadState
@method_decorator(start_thread_login_required())
def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
return super().dispatch(request, *args, **kwargs)
def get(self, request: HttpRequest, **kwargs) -> HttpResponse:
category = self.get_category(request, kwargs)
formset = self.get_formset(request, category)
return render(
request,
self.template_name,
self.get_context_data(request, category, formset),
)
def post(self, request: HttpRequest, **kwargs) -> HttpResponse:
category = self.get_category(request, kwargs)
state = self.get_state(request, category)
formset = self.get_formset(request, category)
formset.update_state(state)
if request.POST.get("preview"):
context = self.get_context_data(request, category, formset)
context["preview"] = state.post.parsed
return render(request, self.template_name, context)
if not formset.is_valid():
return render(
request,
self.template_name,
self.get_context_data(request, category, formset),
)
state.save()
thread_url = self.get_thread_url(request, state.thread)
return redirect(thread_url)
def get_category(self, request: HttpRequest, kwargs: dict) -> Category:
try:
category = Category.objects.get(
id=kwargs["id"],
tree_id=CategoryTree.THREADS,
level__gt=0,
)
except Category.DoesNotExist:
raise Http404()
check_browse_category_permission(
request.user_permissions, category, can_delay=True
)
check_start_thread_in_category_permission(request.user_permissions, category)
return category
def get_formset(
self, request: HttpRequest, category: Category
) -> StartThreadFormset:
formset = StartThreadFormset()
formset.add_form(self.get_start_thread_form(request, category))
return formset
def get_start_thread_form(
self, request: HttpRequest, category: Category
) -> StartThreadForm:
prefix = "thread"
if request.method == "POST":
return StartThreadForm(request.POST, request.FILES, prefix=prefix)
return StartThreadForm(prefix=prefix)
def get_state(self, request: HttpRequest, category: Category) -> StartThreadState:
return self.state_class(request, category)
def get_context_data(
self, request: HttpRequest, category: Category, formset: StartThreadFormset
) -> dict:
return {"category": category, "formset": formset}
def get_thread_url(self, request: HttpRequest, thread: Thread) -> str:
return reverse(
"misago:thread",
kwargs={"id": thread.id, "slug": thread.slug},
)
class StartPrivateThreadView(StartThreadView):
template_name: str = "misago/posting/start_private_thread.html"
state_class = StartPrivateThreadState
def get_category(self, request: HttpRequest, kwargs: dict) -> Category:
check_private_threads_permission(request.user_permissions)
check_start_private_threads_permission(request.user_permissions)
return Category.objects.private_threads()
def get_formset(
self, request: HttpRequest, category: Category
) -> StartThreadFormset:
formset = super().get_formset(request, category)
formset.add_form(
self.get_start_private_thread_form(request, category), append=False
)
return formset
def get_start_private_thread_form(
self, request: HttpRequest, category: Category
) -> StartThreadForm:
prefix = "users"
if request.method == "POST":
return StartPrivateThreadForm(request.POST, prefix=prefix, request=request)
return StartPrivateThreadForm(prefix=prefix, request=request)
def get_thread_url(self, request: HttpRequest, thread: Thread) -> str:
return reverse(
"misago:private-thread",
kwargs={"id": thread.id, "slug": thread.slug},
)
| 5,409
|
Python
|
.py
| 126
| 34.873016
| 87
| 0.677198
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,598
|
start.py
|
rafalp_Misago/misago/posting/state/start.py
|
from datetime import datetime
from typing import TYPE_CHECKING
from django.db import models, transaction
from django.http import HttpRequest
from ...categories.models import Category
from ...core.utils import slugify
from ...parser.context import ParserContext
from ...threads.checksums import update_post_checksum
from ...threads.models import Post, Thread, ThreadParticipant
from .base import PostingState
if TYPE_CHECKING:
from ...users.models import User
class StartThreadState(PostingState):
request: HttpRequest
timestamp: datetime
category: Category
thread: Thread
post: Post
user: "User"
parser_context: ParserContext | None
message_ast: list[dict] | None
message_metadata: dict | None
def __init__(self, request: HttpRequest, category: Category):
super().__init__(request)
self.category = category
self.thread = self.initialize_thread()
self.post = self.initialize_post()
self.store_model_state(category)
def initialize_thread(self) -> Thread:
return Thread(
category=self.category,
started_on=self.timestamp,
last_post_on=self.timestamp,
starter=self.user,
starter_name=self.user.username,
starter_slug=self.user.slug,
last_poster=self.user,
last_poster_name=self.user.username,
last_poster_slug=self.user.slug,
)
def initialize_post(self) -> Post:
return Post(
category=self.category,
thread=self.thread,
poster=self.user,
poster_name=self.user.username,
posted_on=self.timestamp,
updated_on=self.timestamp,
)
def set_thread_title(self, title: str):
self.thread.title = title
self.thread.slug = slugify(title)
@transaction.atomic()
def save(self):
self.thread.save()
self.post.save()
self.save_action()
def save_action(self):
self.save_thread()
self.save_post()
self.save_category()
self.save_user()
def save_thread(self):
self.thread.first_post = self.thread.last_post = self.post
self.thread.save()
def save_post(self):
update_post_checksum(self.post)
self.post.update_search_vector()
self.post.save()
def save_category(self):
self.category.threads = models.F("threads") + 1
self.category.posts = models.F("posts") + 1
self.category.set_last_thread(self.thread)
self.save_model_changes(self.category)
def save_user(self):
self.user.threads = models.F("threads") + 1
self.user.posts = models.F("posts") + 1
self.save_model_changes(self.user)
class StartPrivateThreadState(StartThreadState):
invite_users: list["User"]
def __init__(self, request: HttpRequest, category: Category):
super().__init__(request, category)
self.invite_users: list["User"] = []
def set_invite_users(self, users: list["User"]):
self.invite_users = users
def save_action(self):
super().save_action()
self.save_users()
def save_users(self):
users: list[ThreadParticipant] = [
ThreadParticipant(thread=self.thread, user=self.user, is_owner=True),
]
for invite_user in self.invite_users:
users.append(
ThreadParticipant(thread=self.thread, user=invite_user),
)
ThreadParticipant.objects.bulk_create(users)
| 3,566
|
Python
|
.py
| 97
| 28.773196
| 81
| 0.646118
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,599
|
base.py
|
rafalp_Misago/misago/posting/state/base.py
|
from copy import deepcopy
from datetime import datetime
from typing import Any, TYPE_CHECKING
from django.db import models
from django.http import HttpRequest
from django.utils import timezone
from ...categories.models import Category
from ...core.utils import slugify
from ...parser.context import ParserContext, create_parser_context
from ...parser.enums import ContentType, PlainTextFormat
from ...parser.factory import create_parser
from ...parser.html import render_ast_to_html
from ...parser.metadata import create_ast_metadata
from ...parser.plaintext import render_ast_to_plaintext
from ...threads.models import Post, Thread
if TYPE_CHECKING:
from ...users.models import User
class PostingState:
request: HttpRequest
timestamp: datetime
user: "User"
category: Category
thread: Thread
post: Post
parser_context: ParserContext
message_ast: list[dict] | None
message_metadata: dict | None
models_states: dict
def __init__(self, request: HttpRequest):
self.request = request
self.timestamp = timezone.now()
self.user = request.user
self.parser_context = self.initialize_parser_context()
self.message_ast = None
self.message_metadata = None
self.models_states = {}
self.store_model_state(self.user)
def store_model_state(self, model: models.Model):
state_key = self.get_model_state_key(model)
self.models_states[state_key] = self.get_model_state(model)
def get_model_state_key(self, model: models.Model) -> str:
return f"{model.__class__.__name__}:{model.pk}"
def get_model_state(self, model: models.Model) -> dict[str, Any]:
state = {}
for field in model._meta.get_fields():
if not isinstance(
field,
(models.ManyToManyRel, models.ManyToOneRel, models.ManyToManyField),
):
state[field.name] = deepcopy(getattr(model, field.attname))
return state
def get_model_changed_fields(self, model: models.Model) -> set[str]:
state_key = self.get_model_state_key(model)
old_state = self.models_states[state_key]
changed_fields: set[str] = set()
for field, value in self.get_model_state(model).items():
if old_state[field] != value:
changed_fields.add(field)
return changed_fields
def save_model_changes(self, model: models.Model) -> set[str]:
update_fields = self.get_model_changed_fields(model)
if update_fields:
model.save(update_fields=update_fields)
return update_fields
def initialize_parser_context(self) -> ParserContext:
return create_parser_context(self.request, content_type=ContentType.POST)
def set_post_message(self, message: str):
parser = create_parser(self.parser_context)
ast = parser(message)
metadata = create_ast_metadata(self.parser_context, ast)
self.post.original = message
self.post.parsed = render_ast_to_html(self.parser_context, ast, metadata)
self.post.search_document = render_ast_to_plaintext(
self.parser_context,
ast,
metadata,
text_format=PlainTextFormat.SEARCH_DOCUMENT,
)
self.message_ast = ast
self.message_metadata = metadata
| 3,372
|
Python
|
.py
| 80
| 34.7
| 84
| 0.676561
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|