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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8,000
|
stack_context.py
|
CouchPotato_CouchPotatoServer/libs/tornado/stack_context.py
|
#!/usr/bin/env python
#
# Copyright 2010 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""`StackContext` allows applications to maintain threadlocal-like state
that follows execution as it moves to other execution contexts.
The motivating examples are to eliminate the need for explicit
``async_callback`` wrappers (as in `tornado.web.RequestHandler`), and to
allow some additional context to be kept for logging.
This is slightly magic, but it's an extension of the idea that an
exception handler is a kind of stack-local state and when that stack
is suspended and resumed in a new context that state needs to be
preserved. `StackContext` shifts the burden of restoring that state
from each call site (e.g. wrapping each `.AsyncHTTPClient` callback
in ``async_callback``) to the mechanisms that transfer control from
one context to another (e.g. `.AsyncHTTPClient` itself, `.IOLoop`,
thread pools, etc).
Example usage::
@contextlib.contextmanager
def die_on_error():
try:
yield
except Exception:
logging.error("exception in asynchronous operation",exc_info=True)
sys.exit(1)
with StackContext(die_on_error):
# Any exception thrown here *or in callback and its descendants*
# will cause the process to exit instead of spinning endlessly
# in the ioloop.
http_client.fetch(url, callback)
ioloop.start()
Most applications shouldn't have to work with `StackContext` directly.
Here are a few rules of thumb for when it's necessary:
* If you're writing an asynchronous library that doesn't rely on a
stack_context-aware library like `tornado.ioloop` or `tornado.iostream`
(for example, if you're writing a thread pool), use
`.stack_context.wrap()` before any asynchronous operations to capture the
stack context from where the operation was started.
* If you're writing an asynchronous library that has some shared
resources (such as a connection pool), create those shared resources
within a ``with stack_context.NullContext():`` block. This will prevent
``StackContexts`` from leaking from one request to another.
* If you want to write something like an exception handler that will
persist across asynchronous calls, create a new `StackContext` (or
`ExceptionStackContext`), and make your asynchronous calls in a ``with``
block that references your `StackContext`.
"""
from __future__ import absolute_import, division, print_function, with_statement
import sys
import threading
from tornado.util import raise_exc_info
class StackContextInconsistentError(Exception):
pass
class _State(threading.local):
def __init__(self):
self.contexts = (tuple(), None)
_state = _State()
class StackContext(object):
"""Establishes the given context as a StackContext that will be transferred.
Note that the parameter is a callable that returns a context
manager, not the context itself. That is, where for a
non-transferable context manager you would say::
with my_context():
StackContext takes the function itself rather than its result::
with StackContext(my_context):
The result of ``with StackContext() as cb:`` is a deactivation
callback. Run this callback when the StackContext is no longer
needed to ensure that it is not propagated any further (note that
deactivating a context does not affect any instances of that
context that are currently pending). This is an advanced feature
and not necessary in most applications.
"""
def __init__(self, context_factory):
self.context_factory = context_factory
self.contexts = []
self.active = True
def _deactivate(self):
self.active = False
# StackContext protocol
def enter(self):
context = self.context_factory()
self.contexts.append(context)
context.__enter__()
def exit(self, type, value, traceback):
context = self.contexts.pop()
context.__exit__(type, value, traceback)
# Note that some of this code is duplicated in ExceptionStackContext
# below. ExceptionStackContext is more common and doesn't need
# the full generality of this class.
def __enter__(self):
self.old_contexts = _state.contexts
self.new_contexts = (self.old_contexts[0] + (self,), self)
_state.contexts = self.new_contexts
try:
self.enter()
except:
_state.contexts = self.old_contexts
raise
return self._deactivate
def __exit__(self, type, value, traceback):
try:
self.exit(type, value, traceback)
finally:
final_contexts = _state.contexts
_state.contexts = self.old_contexts
# Generator coroutines and with-statements with non-local
# effects interact badly. Check here for signs of
# the stack getting out of sync.
# Note that this check comes after restoring _state.context
# so that if it fails things are left in a (relatively)
# consistent state.
if final_contexts is not self.new_contexts:
raise StackContextInconsistentError(
'stack_context inconsistency (may be caused by yield '
'within a "with StackContext" block)')
# Break up a reference to itself to allow for faster GC on CPython.
self.new_contexts = None
class ExceptionStackContext(object):
"""Specialization of StackContext for exception handling.
The supplied ``exception_handler`` function will be called in the
event of an uncaught exception in this context. The semantics are
similar to a try/finally clause, and intended use cases are to log
an error, close a socket, or similar cleanup actions. The
``exc_info`` triple ``(type, value, traceback)`` will be passed to the
exception_handler function.
If the exception handler returns true, the exception will be
consumed and will not be propagated to other exception handlers.
"""
def __init__(self, exception_handler):
self.exception_handler = exception_handler
self.active = True
def _deactivate(self):
self.active = False
def exit(self, type, value, traceback):
if type is not None:
return self.exception_handler(type, value, traceback)
def __enter__(self):
self.old_contexts = _state.contexts
self.new_contexts = (self.old_contexts[0], self)
_state.contexts = self.new_contexts
return self._deactivate
def __exit__(self, type, value, traceback):
try:
if type is not None:
return self.exception_handler(type, value, traceback)
finally:
final_contexts = _state.contexts
_state.contexts = self.old_contexts
if final_contexts is not self.new_contexts:
raise StackContextInconsistentError(
'stack_context inconsistency (may be caused by yield '
'within a "with StackContext" block)')
# Break up a reference to itself to allow for faster GC on CPython.
self.new_contexts = None
class NullContext(object):
"""Resets the `StackContext`.
Useful when creating a shared resource on demand (e.g. an
`.AsyncHTTPClient`) where the stack that caused the creating is
not relevant to future operations.
"""
def __enter__(self):
self.old_contexts = _state.contexts
_state.contexts = (tuple(), None)
def __exit__(self, type, value, traceback):
_state.contexts = self.old_contexts
def _remove_deactivated(contexts):
"""Remove deactivated handlers from the chain"""
# Clean ctx handlers
stack_contexts = tuple([h for h in contexts[0] if h.active])
# Find new head
head = contexts[1]
while head is not None and not head.active:
head = head.old_contexts[1]
# Process chain
ctx = head
while ctx is not None:
parent = ctx.old_contexts[1]
while parent is not None:
if parent.active:
break
ctx.old_contexts = parent.old_contexts
parent = parent.old_contexts[1]
ctx = parent
return (stack_contexts, head)
def wrap(fn):
"""Returns a callable object that will restore the current `StackContext`
when executed.
Use this whenever saving a callback to be executed later in a
different execution context (either in a different thread or
asynchronously in the same thread).
"""
# Check if function is already wrapped
if fn is None or hasattr(fn, '_wrapped'):
return fn
# Capture current stack head
# TODO: Any other better way to store contexts and update them in wrapped function?
cap_contexts = [_state.contexts]
if not cap_contexts[0][0] and not cap_contexts[0][1]:
# Fast path when there are no active contexts.
def null_wrapper(*args, **kwargs):
try:
current_state = _state.contexts
_state.contexts = cap_contexts[0]
return fn(*args, **kwargs)
finally:
_state.contexts = current_state
null_wrapper._wrapped = True
return null_wrapper
def wrapped(*args, **kwargs):
ret = None
try:
# Capture old state
current_state = _state.contexts
# Remove deactivated items
cap_contexts[0] = contexts = _remove_deactivated(cap_contexts[0])
# Force new state
_state.contexts = contexts
# Current exception
exc = (None, None, None)
top = None
# Apply stack contexts
last_ctx = 0
stack = contexts[0]
# Apply state
for n in stack:
try:
n.enter()
last_ctx += 1
except:
# Exception happened. Record exception info and store top-most handler
exc = sys.exc_info()
top = n.old_contexts[1]
# Execute callback if no exception happened while restoring state
if top is None:
try:
ret = fn(*args, **kwargs)
except:
exc = sys.exc_info()
top = contexts[1]
# If there was exception, try to handle it by going through the exception chain
if top is not None:
exc = _handle_exception(top, exc)
else:
# Otherwise take shorter path and run stack contexts in reverse order
while last_ctx > 0:
last_ctx -= 1
c = stack[last_ctx]
try:
c.exit(*exc)
except:
exc = sys.exc_info()
top = c.old_contexts[1]
break
else:
top = None
# If if exception happened while unrolling, take longer exception handler path
if top is not None:
exc = _handle_exception(top, exc)
# If exception was not handled, raise it
if exc != (None, None, None):
raise_exc_info(exc)
finally:
_state.contexts = current_state
return ret
wrapped._wrapped = True
return wrapped
def _handle_exception(tail, exc):
while tail is not None:
try:
if tail.exit(*exc):
exc = (None, None, None)
except:
exc = sys.exc_info()
tail = tail.old_contexts[1]
return exc
def run_with_stack_context(context, func):
"""Run a coroutine ``func`` in the given `StackContext`.
It is not safe to have a ``yield`` statement within a ``with StackContext``
block, so it is difficult to use stack context with `.gen.coroutine`.
This helper function runs the function in the correct context while
keeping the ``yield`` and ``with`` statements syntactically separate.
Example::
@gen.coroutine
def incorrect():
with StackContext(ctx):
# ERROR: this will raise StackContextInconsistentError
yield other_coroutine()
@gen.coroutine
def correct():
yield run_with_stack_context(StackContext(ctx), other_coroutine)
.. versionadded:: 3.1
"""
with context:
return func()
| 13,174
|
Python
|
.tac
| 305
| 34.314754
| 94
| 0.643125
|
CouchPotato/CouchPotatoServer
| 3,869
| 1,214
| 1,266
|
GPL-3.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,001
|
manage.py
|
mdn_kuma/manage.py
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kuma.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()
| 666
|
Python
|
.py
| 18
| 31.111111
| 74
| 0.677019
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,002
|
conf.py
|
mdn_kuma/docs/conf.py
|
#
# Kuma documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 5 15:41:51 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "Kuma"
copyright = "Mozilla"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "latest"
# The full version, including alpha/beta/rc tags.
release = "latest"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
# pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "alabaster"
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["."]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"github_user": "mozilla",
"github_repo": "kuma",
"github_button": False,
"description": (
"The platform that powers "
'<a href="https://developer.mozilla.org/en-US/">MDN</a>'
),
"travis_button": False,
"codecov_button": False,
"extra_nav_links": {
"MDN": "https://developer.mozilla.org",
"MDN Staging": "https://developer.allizom.org",
"Kuma on GitHub": "https://github.com/mdn/kuma",
},
"show_related": True,
"page_width": "100%",
}
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "Kuma Documentation"
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
"**": [
"about.html",
"navigation.html",
"relations.html",
"searchbox.html",
"donate.html",
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "Kumadoc"
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
("index", "Kuma.tex", "Kuma Documentation", "Mozilla", "manual"),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then top-level headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [("index", "kuma", "Kuma Documentation", ["Mozilla"], 1)]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
"index",
"Kuma",
"Kuma Documentation",
"Mozilla",
"Kuma",
"The Django based project of developer.mozilla.org.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
| 8,656
|
Python
|
.py
| 208
| 39.225962
| 80
| 0.703447
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,003
|
conftest.py
|
mdn_kuma/kuma/conftest.py
|
import pytest
import requests_mock
from django.contrib.auth.models import Group
from django.core.cache import caches
from django.urls import set_urlconf
from django.utils import timezone
from django.utils.translation import activate
from kuma.users.models import UserProfile
@pytest.fixture(autouse=True)
def clear_cache():
"""
Before every pytest test function starts, it clears the cache.
"""
caches["default"].clear()
@pytest.fixture(autouse=True)
def set_default_language():
activate("en-US")
@pytest.fixture(autouse=True)
def reset_urlconf():
"""
Reset the default urlconf used by "reverse" to the one provided
by settings.ROOT_URLCONF.
Django resets the default urlconf back to settings.ROOT_URLCONF at
the beginning of each request, but if the incoming request has a
"urlconf" attribute, the default urlconf is changed to its value for
the remainder of the request, so that all subsequent "reverse" calls
use that value (unless they explicitly specify a different one). The
problem occurs when a test is run that uses the "request.urlconf"
mechanism, setting the default urlconf to something other than
settings.ROOT_URLCONF, and then subsequent tests make "reverse" calls
that fail because they're expecting a default urlconf of
settings.ROOT_URLCONF (i.e., they're not explicitly providing a
urlconf value to the "reverse" call).
"""
set_urlconf(None)
yield
set_urlconf(None)
@pytest.fixture
def beta_testers_group(db):
return Group.objects.create(name="Beta Testers")
@pytest.fixture
def wiki_user(db, django_user_model):
"""A test user."""
return django_user_model.objects.create(
username="wiki_user",
email="wiki_user@example.com",
date_joined=timezone.now(),
)
@pytest.fixture
def user_client(client, wiki_user):
"""A test client with wiki_user logged in."""
wiki_user.set_password("password")
wiki_user.save()
client.login(username=wiki_user.username, password="password")
return client
@pytest.fixture
def subscriber_client(client, wiki_user):
"""A test client with wiki_user logged in and a paying subscriber."""
UserProfile.objects.create(user=wiki_user, is_subscriber=True)
wiki_user.set_password("password")
wiki_user.save()
client.login(username=wiki_user.username, password="password")
return client
@pytest.fixture
def stripe_user(wiki_user):
wiki_user.stripe_customer_id = "fakeCustomerID123"
wiki_user.save()
return wiki_user
@pytest.fixture
def stripe_user_client(client, stripe_user):
"""A test client with wiki_user logged in and with a stripe_customer_id."""
stripe_user.set_password("password")
stripe_user.save()
client.login(username=stripe_user.username, password="password")
return client
@pytest.fixture
def mock_requests():
with requests_mock.Mocker() as mocker:
yield mocker
| 2,954
|
Python
|
.py
| 79
| 33.329114
| 79
| 0.744129
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,004
|
celery.py
|
mdn_kuma/kuma/celery.py
|
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kuma.settings.local")
app = Celery("kuma")
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print("Request: {0!r}".format(self.request))
@app.task()
def debug_task_returning(a, b):
"""Useful to see if the results backend is working.
And it also checks that called with a `datetime.date`
it gets that as parameters in the task."""
import datetime
assert isinstance(a, datetime.date), type(a)
assert isinstance(b, datetime.date), type(b)
return a < b
| 1,004
|
Python
|
.py
| 24
| 39.083333
| 70
| 0.752577
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,005
|
urls.py
|
mdn_kuma/kuma/urls.py
|
from django.conf import settings
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.decorators.cache import never_cache
from django.views.generic import RedirectView
from kuma.attachments import views as attachment_views
from kuma.core import views as core_views
from kuma.users import views as users_views
DAY = 60 * 60 * 24
MONTH = DAY * 30
admin.autodiscover()
urlpatterns = [re_path("", include("kuma.health.urls"))]
if settings.MAINTENANCE_MODE:
urlpatterns.append(
re_path(
r"^admin/.*",
never_cache(RedirectView.as_view(url="/", permanent=False)),
)
)
else:
# Django admin:
urlpatterns += [
# We don't worry about decorating the views within django.contrib.admin
# with "never_cache", since most have already been decorated, and the
# remaining can be safely cached.
re_path(r"^admin/", admin.site.urls),
]
urlpatterns += [re_path("", include("kuma.attachments.urls"))]
urlpatterns += [
path("users/fxa/login/", include("mozilla_django_oidc.urls")),
path(
"users/fxa/login/no-prompt/",
users_views.no_prompt_login,
name="no_prompt_login",
),
path(
"events/fxa",
users_views.WebhookView.as_view(),
name="fxa_webhook",
),
]
urlpatterns += [
# Services and sundry.
re_path("^admin-api/", include("kuma.api.admin_urls")),
re_path("^api/", include("kuma.api.urls")),
re_path("", include("kuma.version.urls")),
re_path(r"^humans.txt$", core_views.humans_txt, name="humans_txt"),
# We use our own views for setting language in cookies. But to just align with django, set it like this.
# re_path(r"^i18n/setlang/", core_views.set_language, name="set-language-cookie"),
]
# Legacy MindTouch redirects. These go last so that they don't mess
# with local instances' ability to serve media.
urlpatterns += [
re_path(
r"^@api/deki/files/(?P<file_id>\d+)/=(?P<filename>.+)$",
attachment_views.mindtouch_file_redirect,
name="attachments.mindtouch_file_redirect",
),
]
| 2,136
|
Python
|
.py
| 59
| 31.322034
| 108
| 0.672147
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,006
|
__init__.py
|
mdn_kuma/kuma/__init__.py
|
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
__all__ = ("celery_app",)
| 174
|
Python
|
.py
| 4
| 42.25
| 54
| 0.745562
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,007
|
wsgi.py
|
mdn_kuma/kuma/wsgi.py
|
"""
WSGI config for kuma project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kuma.settings.local")
application = get_wsgi_application()
| 392
|
Python
|
.py
| 10
| 37.6
| 78
| 0.800532
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,008
|
models.py
|
mdn_kuma/kuma/plus/models.py
|
from uuid import uuid4
from django.db import models
class LandingPageSurvey(models.Model):
uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True)
# An insecure random string so that when a survey is submitted with more information
# it can not easily be guessed and the ratelimit will make it impossible to try
# all combinations.
response = models.JSONField(editable=False, null=True)
geo_information = models.TextField(editable=False, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.uuid)
| 651
|
Python
|
.py
| 13
| 45.384615
| 88
| 0.755521
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,009
|
apps.py
|
mdn_kuma/kuma/plus/apps.py
|
from django.apps import AppConfig
class PlusConfig(AppConfig):
name = "kuma.plus"
verbose_name = "Plus"
| 114
|
Python
|
.py
| 4
| 25
| 33
| 0.740741
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,010
|
admin.py
|
mdn_kuma/kuma/plus/admin.py
|
from django.contrib import admin
from .models import LandingPageSurvey
class HasResponseFilter(admin.SimpleListFilter):
title = "Has response"
parameter_name = "has_response"
def lookups(self, request, model_admin):
return (
("true", "Has response"),
("false", "No response"),
)
def queryset(self, request, queryset):
if self.value() == "true":
return queryset.filter(response__isnull=False)
if self.value() == "false":
return queryset.filter(response__isnull=True)
@admin.register(LandingPageSurvey)
class LandingPageSurveyAdmin(admin.ModelAdmin):
list_display = (
"uuid",
"geo_information",
"has_response",
"created",
)
fields = (
"geo_information",
"response",
)
readonly_fields = (
"geo_information",
"response",
)
list_filter = (HasResponseFilter,)
search_fields = ("response", "uuid", "geo_information")
ordering = ("-created",)
list_per_page = 10
def has_email(self, obj):
return bool(obj.email)
def has_response(self, obj):
return bool(obj.response)
def signed_in(self, obj):
return bool(obj.user)
| 1,253
|
Python
|
.py
| 41
| 23.536585
| 59
| 0.614488
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,011
|
0001_initial.py
|
mdn_kuma/kuma/plus/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-07-09 21:00
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="LandingPageSurvey",
fields=[
(
"uuid",
models.UUIDField(
default=uuid.uuid4,
editable=False,
primary_key=True,
serialize=False,
),
),
("email", models.CharField(blank=True, max_length=100)),
("variant", models.PositiveIntegerField()),
("response", models.JSONField(editable=False, null=True)),
("geo_information", models.TextField(editable=False, null=True)),
("created", models.DateTimeField(auto_now_add=True)),
("updated", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| 1,471
|
Python
|
.py
| 40
| 22.4
| 81
| 0.496489
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,012
|
0002_auto_20210723_1901.py
|
mdn_kuma/kuma/plus/migrations/0002_auto_20210723_1901.py
|
# Generated by Django 3.2.5 on 2021-07-23 19:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("plus", "0001_initial"),
]
operations = [
migrations.RemoveField(
model_name="landingpagesurvey",
name="email",
),
migrations.RemoveField(
model_name="landingpagesurvey",
name="user",
),
migrations.RemoveField(
model_name="landingpagesurvey",
name="variant",
),
]
| 551
|
Python
|
.py
| 20
| 19.1
| 47
| 0.572243
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,013
|
models.py
|
mdn_kuma/kuma/users/models.py
|
import json
from django.contrib.auth import get_user_model
from django.db import models
class UserProfile(models.Model):
class SubscriptionType(models.TextChoices):
"""Choices for MDN Subscription Types, add new subscription plans to be supported here"""
MDN_PLUS_5M = "mdn_plus_5m", "MDN Plus 5M"
MDN_PLUS_5Y = "mdn_plus_5y", "MDN Plus 5Y"
MDN_PLUS_10M = "mdn_plus_10m", "MDN Plus 10M"
MDN_PLUS_10Y = "mdn_plus_10y", "MDN Plus 10Y"
NONE = "", "None"
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
locale = models.CharField(max_length=6, null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
avatar = models.URLField(max_length=512, blank=True, default="")
fxa_refresh_token = models.CharField(blank=True, default="", max_length=128)
is_subscriber = models.BooleanField(default=False)
subscription_type = models.CharField(
max_length=512,
blank=True,
choices=SubscriptionType.choices,
default=SubscriptionType.NONE,
)
class Meta:
verbose_name = "User profile"
def __str__(self):
return json.dumps(
{
"uid": self.user.username,
"is_subscriber": self.is_subscriber,
"subscription_type": self.subscription_type,
"email": self.user.email,
"avatar": self.avatar,
}
)
class AccountEvent(models.Model):
"""Stores the Events received from Firefox Accounts.
Each event is processed by Celery and stored in this table.
"""
class EventType(models.IntegerChoices):
"""Type of event received from Firefox Accounts."""
PASSWORD_CHANGED = 1
PROFILE_CHANGED = 2
SUBSCRIPTION_CHANGED = 3
PROFILE_DELETED = 4
class EventStatus(models.IntegerChoices):
"""Status of each event received from Firefox Accounts."""
PROCESSED = 1
PENDING = 2
IGNORED = 3
NOT_IMPLEMENTED = 4
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
# This could be a ForeignKey to the UserProfile table (username). Decoupled for now
fxa_uid = models.CharField(max_length=128, blank=True, default="")
payload = models.TextField(max_length=2048, blank=True, default="")
event_type = models.IntegerField(choices=EventType.choices, default="", blank=True)
status = models.IntegerField(
choices=EventStatus.choices, default=EventStatus.PENDING
)
jwt_id = models.CharField(max_length=256, blank=True, default="")
issued_at = models.CharField(max_length=32, default="", blank=True)
class Meta:
ordering = ["-modified_at"]
| 2,830
|
Python
|
.py
| 65
| 35.892308
| 97
| 0.66315
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,014
|
checks.py
|
mdn_kuma/kuma/users/checks.py
|
from urllib.parse import urljoin, urlparse
from django.conf import settings
from django.core.checks import Error, Warning
from kuma.core.utils import requests_retry_session
MISSING_OIDC_RP_CLIENT_ID_ERROR = "kuma.users.E001"
MISSING_OIDC_RP_CLIENT_SECRET_ERROR = "kuma.users.E002"
MISSING_OIDC_CONFIGURATION_ERROR = "kuma.users.E003"
def oidc_config_check(app_configs, **kwargs):
errors = []
for id, key in (
(MISSING_OIDC_RP_CLIENT_ID_ERROR, "OIDC_RP_CLIENT_ID"),
(MISSING_OIDC_RP_CLIENT_SECRET_ERROR, "OIDC_RP_CLIENT_SECRET"),
):
if not getattr(settings, key, None):
class_ = Warning if settings.DEBUG else Error
errors.append(
class_(
f"{key} environment variable is not set or is empty",
id=id,
)
)
if settings.OIDC_CONFIGURATION_CHECK:
errors.extend(_get_oidc_configuration_errors(MISSING_OIDC_CONFIGURATION_ERROR))
return errors
def _get_oidc_configuration_errors(id):
errors = []
configuration_url = settings.OIDC_CONFIGURATION_URL
parsed = urlparse(configuration_url)
if not parsed.path or parsed.path == "/":
default_path = "/.well-known/openid-configuration"
parsed._replace(path=default_path)
configuration_url = urljoin(configuration_url, default_path)
response = requests_retry_session().get(configuration_url)
response.raise_for_status()
openid_configuration = response.json()
for key, setting_key in (
("userinfo_endpoint", "OIDC_OP_USER_ENDPOINT"),
("authorization_endpoint", "OIDC_OP_AUTHORIZATION_ENDPOINT"),
("token_endpoint", "OIDC_OP_TOKEN_ENDPOINT"),
):
setting_value = getattr(settings, setting_key, None)
if key not in openid_configuration and setting_value:
errors.append(
Warning(
f"{setting_key} is set but {key!r} is not exposed in {configuration_url}",
id=id,
)
)
continue
config_value = openid_configuration[key]
if setting_value and config_value != setting_value:
errors.append(
Error(
f"{setting_key}'s value is different from that on {configuration_url}"
f" ({setting_value!r} != {config_value!r}",
id=id,
)
)
# ##TODO 14/02/22 - The additional profile:subscriptions scope is currently missing from the supportes scopes in oidc config
# settings.OIDC_RP_SCOPES can have less but not more that what's supported
# scopes_requested = set(settings.OIDC_RP_SCOPES.split())
# scopes_supported = set(openid_configuration["scopes_supported"])
# if scopes_supported - scopes_requested:
# errors.append(
# Error(
# f"Invalid settings.OIDC_RP_SCOPES ({settings.OIDC_RP_SCOPES!r}). "
# f"Requested: {scopes_requested}, Supported: {scopes_supported}",
# id=id,
# )
# )
if settings.OIDC_RP_SIGN_ALGO not in set(
openid_configuration["id_token_signing_alg_values_supported"]
):
errors.append(
Error(
f"Invalid settings.OIDC_RP_SIGN_ALGO. "
f"{settings.OIDC_RP_SIGN_ALGO!r} not in "
f'{openid_configuration["id_token_signing_alg_values_supported"]}',
id=id,
)
)
return errors
| 3,540
|
Python
|
.py
| 82
| 33.792683
| 128
| 0.611095
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,015
|
tasks.py
|
mdn_kuma/kuma/users/tasks.py
|
import json
from celery import task
from django.contrib.auth import get_user_model
from kuma.users.auth import KumaOIDCAuthenticationBackend
from kuma.users.models import AccountEvent, UserProfile
from kuma.users.utils import get_valid_subscription_type_or_none
@task
def process_event_delete_user(event_id):
event = AccountEvent.objects.get(id=event_id)
try:
user = get_user_model().objects.get(username=event.fxa_uid)
except get_user_model().DoesNotExist:
return
user.delete()
event.status = AccountEvent.PROCESSED
event.save()
@task
def process_event_subscription_state_change(event_id):
event = AccountEvent.objects.get(id=event_id)
try:
user = get_user_model().objects.get(username=event.fxa_uid)
profile = UserProfile.objects.get(user=user)
except get_user_model().DoesNotExist:
return
payload = json.loads(event.payload)
last_event = AccountEvent.objects.filter(
fxa_uid=event.fxa_uid,
status=AccountEvent.EventStatus.PROCESSED,
event_type=AccountEvent.EventType.SUBSCRIPTION_CHANGED,
).first()
if last_event:
last_event_payload = json.loads(last_event.payload)
if last_event_payload["changeTime"] >= payload["changeTime"]:
event.status = AccountEvent.EventStatus.IGNORED
event.save()
return
subscription_type = get_valid_subscription_type_or_none(
payload.get("capabilities", [])
)
if not user.is_staff:
if payload["isActive"]:
profile.subscription_type = subscription_type
profile.is_subscriber = True
else:
profile.subscription_type = ""
profile.is_subscriber = False
profile.save()
event.status = AccountEvent.EventStatus.PROCESSED
event.save()
@task
def process_event_password_change(event_id):
event = AccountEvent.objects.get(id=event_id)
event.status = AccountEvent.EventStatus.PROCESSED
event.save()
@task
def process_event_profile_change(event_id):
event = AccountEvent.objects.get(id=event_id)
try:
user = get_user_model().objects.get(username=event.fxa_uid)
profile = UserProfile.objects.get(user=user)
except get_user_model().DoesNotExist:
return
refresh_token = profile.fxa_refresh_token
if not refresh_token:
event.status = AccountEvent.IGNORED
event.save()
return
fxa = KumaOIDCAuthenticationBackend()
token_info = fxa.get_token(
{
"client_id": fxa.OIDC_RP_CLIENT_ID,
"client_secret": fxa.OIDC_RP_CLIENT_SECRET,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"ttl": 60 * 5,
}
)
access_token = token_info.get("access_token")
user_info = fxa.get_userinfo(access_token, None, None)
fxa.update_user(user, user_info)
event.status = AccountEvent.EventStatus.PROCESSED
event.save()
| 2,991
|
Python
|
.py
| 82
| 29.658537
| 69
| 0.68144
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,016
|
apps.py
|
mdn_kuma/kuma/users/apps.py
|
from django.apps import AppConfig
from django.core.checks import register
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "kuma.users"
verbose_name = _("Users")
def ready(self):
self.register_checks()
def register_checks(self):
from .checks import oidc_config_check
register(oidc_config_check)
| 383
|
Python
|
.py
| 11
| 29.727273
| 54
| 0.72752
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,017
|
auth.py
|
mdn_kuma/kuma/users/auth.py
|
import time
import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from mozilla_django_oidc.auth import OIDCAuthenticationBackend
from kuma.users.utils import get_valid_subscription_type_or_none
from .models import UserProfile
class KumaOIDCAuthenticationBackend(OIDCAuthenticationBackend):
"""Extend mozilla-django-oidc authbackend."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.refresh_token = None
def get_token(self, payload):
"""Override get_token to extract the refresh token."""
token_info = super().get_token(payload)
self.refresh_token = token_info.get("refresh_token")
return token_info
@classmethod
def refresh_access_token(cls, refresh_token, ttl=None):
"""Gets a new access_token by using a refresh_token.
returns: the actual token or an empty dictionary
"""
if not refresh_token:
return {}
obj = cls()
payload = {
"client_id": obj.OIDC_RP_CLIENT_ID,
"client_secret": obj.OIDC_RP_CLIENT_SECRET,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
}
if ttl:
payload.update({"ttl": ttl})
try:
return obj.get_token(payload=payload)
except requests.exceptions.HTTPError:
return {}
def filter_users_by_claims(self, claims):
user_model = get_user_model()
if not (fxa_uid := claims.get("sub")):
return user_model.objects.none()
return user_model.objects.filter(username=fxa_uid)
def create_user(self, claims):
user = super().create_user(claims)
self._create_or_set_user_profile(user, claims)
self.request.created = True
return user
def update_user(self, user, claims):
self._create_or_set_user_profile(user, claims)
return user
def get_username(self, claims):
"""Get the username from the claims."""
# use the fxa_uid as the username
return claims.get("sub", claims.get("uid"))
@staticmethod
def create_or_update_subscriber(claims, user=None):
"""Retrieve or create a user with a profile.
Static helper method that routes requests that are not part of the login flow
"""
email = claims.get("email")
fxa_uid = claims.get("sub", claims.get("uid"))
if not fxa_uid:
return
try:
# short-circuit if we already have a user
user = user or get_user_model().objects.get(username=fxa_uid)
except get_user_model().DoesNotExist:
user = get_user_model().objects.create_user(email=email, username=fxa_uid)
# update the email if needed
if email and user.email != email:
user.email = email
# toggle user status based on subscriptions
user.is_active = True
user.save()
profile, _ = UserProfile.objects.get_or_create(user=user)
if avatar := claims.get("avatar"):
profile.avatar = avatar
profile.is_subscriber = settings.MDN_PLUS_SUBSCRIPTION in claims.get(
"subscriptions", []
) or settings.MDN_PLUS_SUBSCRIPTION == claims.get("fxa-subscriptions", "")
profile.subscription_type = get_valid_subscription_type_or_none(
claims.get("subscriptions", [])
)
if user.is_staff:
profile.is_subscriber = True
profile.subscription_type = UserProfile.SubscriptionType.MDN_PLUS_10Y
profile.save()
return user
def _create_or_set_user_profile(self, user, claims):
"""Update user and profile attributes."""
user = self.create_or_update_subscriber(claims, user)
if self.refresh_token:
UserProfile.objects.filter(user=user).update(
fxa_refresh_token=self.refresh_token
)
def logout_url(request):
"""This gets called by mozilla_django_oidc when a user has signed out."""
return (
request.GET.get("next")
or request.session.get("oidc_login_next")
or getattr(settings, "LOGOUT_REDIRECT_URL", None)
or "/"
)
def is_authorized_request(token, **kwargs):
auth = token.split()
if auth[0].lower() != "bearer":
return {"error": "invalid token type"}
jwt_token = auth[1]
if not (payload := KumaOIDCAuthenticationBackend().verify_token(jwt_token)):
return {"error": "invalid token"}
issuer = payload["iss"]
exp = payload["exp"]
# # If the issuer is not Firefox Accounts log an error
if settings.FXA_TOKEN_ISSUER != issuer:
return {"error": "invalid token issuer"}
# Check if the token is expired
if exp < time.time():
return {"error": "token expired"}
return payload
| 4,910
|
Python
|
.py
| 119
| 32.680672
| 86
| 0.63108
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,018
|
utils.py
|
mdn_kuma/kuma/users/utils.py
|
from kuma.users.models import UserProfile
# Finds union of valid subscription id's from input and UserProfile.SubscriptionType.values
# Should only be mdn_plus + one of 'SubscriptionType.values'
def get_valid_subscription_type_or_none(input):
subscription_types = list(set(input) & set(UserProfile.SubscriptionType.values))
if len(subscription_types) > 1:
print("Multiple subscriptions found in update %s" % subscription_types)
# Sort array lexicographically. At least makes wrong answer consistent.
subscription_types.sort()
return subscription_types[0] if len(subscription_types) > 0 else ""
| 633
|
Python
|
.py
| 10
| 58.4
| 91
| 0.762903
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,019
|
middleware.py
|
mdn_kuma/kuma/users/middleware.py
|
import time
from django.conf import settings
from django.contrib.auth import logout
from django.core.exceptions import MiddlewareNotUsed
from mozilla_django_oidc.middleware import SessionRefresh
from kuma.users.auth import KumaOIDCAuthenticationBackend
class ValidateAccessTokenMiddleware(SessionRefresh):
"""Validate the access token every hour.
Verify that the access token has not been invalidated
by the user through the Firefox Accounts web interface.
"""
def __init__(self, *args, **kwargs):
if settings.DEV and settings.DEBUG:
raise MiddlewareNotUsed
super().__init__(*args, **kwargs)
def process_request(self, request):
if not self.is_refreshable_url(request):
return
expiration = request.session.get("oidc_id_token_expiration", 0)
now = time.time()
access_token = request.session.get("oidc_access_token")
profile = request.user.userprofile
if access_token and expiration < now:
token_info = KumaOIDCAuthenticationBackend.refresh_access_token(
profile.fxa_refresh_token
)
new_access_token = token_info.get("access_token")
if new_access_token:
request.session["oidc_access_token"] = new_access_token
request.session["oidc_id_token_expiration"] = (
now + settings.FXA_TOKEN_EXPIRY
)
else:
profile.fxa_refresh_token = ""
profile.save()
logout(request)
| 1,572
|
Python
|
.py
| 36
| 33.916667
| 76
| 0.651148
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,020
|
views.py
|
mdn_kuma/kuma/users/views.py
|
import json
import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import SuspiciousOperation
from django.http import Http404, HttpResponse
from django.utils.decorators import method_decorator
from django.utils.encoding import force_bytes
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from josepy.jwk import JWK
from josepy.jws import JWS
from mozilla_django_oidc.views import (
OIDCAuthenticationCallbackView,
OIDCAuthenticationRequestView,
)
from kuma.users.models import AccountEvent, UserProfile
from kuma.users.tasks import (
process_event_delete_user,
process_event_password_change,
process_event_profile_change,
process_event_subscription_state_change,
)
class NoPromptOIDCAuthenticationRequestView(OIDCAuthenticationRequestView):
def get_extra_params(self, request):
params = {"next": "/en-US/plus"}
email = request.GET.get("email")
if email:
# Note that "prompt=none" will fail if "login_hint"
# is not also provided with the user's correct email.
params.update(prompt="none", login_hint=email)
return params
no_prompt_login = NoPromptOIDCAuthenticationRequestView.as_view()
class KumaOIDCAuthenticationCallbackView(OIDCAuthenticationCallbackView):
@property
def success_url(self):
try:
profile = UserProfile.objects.get(user=self.user)
is_subscriber = profile.is_subscriber
except UserProfile.DoesNotExist:
is_subscriber = False
# Redirect new users to Plus.
if (
hasattr(self.request, "created")
and self.request.created
and not is_subscriber
):
return "/en-US/plus"
return super().success_url
@method_decorator(csrf_exempt, name="dispatch")
class WebhookView(View):
"""The flow here is based on the mozilla-django-oidc lib.
If/When the said lib supports SET tokens this will be replaced by the lib.
"""
def retrieve_matching_jwk(self, header):
"""Get the signing key by exploring the JWKS endpoint of the OP."""
response_jwks = requests.get(
settings.OIDC_OP_JWKS_ENDPOINT,
)
response_jwks.raise_for_status()
jwks = response_jwks.json()
key = None
for jwk in jwks["keys"]:
if jwk["kid"] != header.get("kid"):
continue
if "alg" in jwk and jwk["alg"] != header["alg"]:
raise SuspiciousOperation("alg values do not match.")
key = jwk
if key is None:
raise SuspiciousOperation("Could not find a valid JWKS.")
return key
def verify_token(self, token, **kwargs):
"""Validate the token signature."""
token = force_bytes(token)
jws = JWS.from_compact(token)
header = json.loads(jws.signature.protected)
try:
header.get("alg")
except KeyError:
msg = "No alg value found in header"
raise SuspiciousOperation(msg)
jwk_json = self.retrieve_matching_jwk(header)
jwk = JWK.from_json(jwk_json)
if not jws.verify(jwk):
msg = "JWS token verification failed."
raise SuspiciousOperation(msg)
# The 'token' will always be a byte string since it's
# the result of base64.urlsafe_b64decode().
# The payload is always the result of base64.urlsafe_b64decode().
# In Python 3 and 2, that's always a byte string.
# In Python3.6, the json.loads() function can accept a byte string
# as it will automagically decode it to a unicode string before
# deserializing https://bugs.python.org/issue17909
return json.loads(jws.payload.decode("utf-8"))
def process_events(self, payload):
"""Save the events in the db, and enqueue jobs to act upon them"""
fxa_uid = payload.get("sub")
events = payload.get("events")
try:
user = get_user_model().objects.get(username=fxa_uid)
except get_user_model().DoesNotExist:
user = None
print(user)
if not user:
return
for long_id, event in events.items():
short_id = long_id.replace(settings.FXA_SET_ID_PREFIX, "")
if short_id == "password-change":
event_type = AccountEvent.EventType.PASSWORD_CHANGED
elif short_id == "profile-change":
event_type = AccountEvent.EventType.PROFILE_CHANGED
elif short_id == "subscription-state-change":
event_type = AccountEvent.EventType.SUBSCRIPTION_CHANGED
elif short_id == "delete-user":
event_type = AccountEvent.EventType.PROFILE_DELETED
else:
event_type = None
if not event_type:
continue
account_event = AccountEvent.objects.create(
issued_at=payload["iat"],
jwt_id=payload["jti"],
fxa_uid=fxa_uid,
status=AccountEvent.EventStatus.PENDING,
payload=json.dumps(event),
event_type=event_type,
)
if user:
if event_type == AccountEvent.EventType.PROFILE_DELETED:
process_event_delete_user.delay(account_event.id)
elif event_type == AccountEvent.EventType.SUBSCRIPTION_CHANGED:
process_event_subscription_state_change.delay(account_event.id)
elif event_type == AccountEvent.EventType.PASSWORD_CHANGED:
process_event_password_change.delay(account_event.id)
elif event_type == AccountEvent.EventType.PROFILE_CHANGED:
process_event_profile_change.delay(account_event.id)
else:
pass
def post(self, request, *args, **kwargs):
authorization = request.META.get("HTTP_AUTHORIZATION")
print(authorization)
if not authorization:
raise Http404
auth = authorization.split()
if auth[0].lower() != "bearer":
raise Http404
id_token = auth[1]
payload = self.verify_token(id_token)
if payload:
issuer = payload["iss"]
events = payload.get("events", "")
fxa_uid = payload.get("sub", "")
exp = payload.get("exp")
# If the issuer is not Firefox Accounts raise a 404 error
if settings.FXA_SET_ISSUER != issuer:
raise Http404
# If exp is in the token then it's an id_token that should not be here
if any([not events, not fxa_uid, exp]):
return HttpResponse(status=400)
self.process_events(payload)
return HttpResponse(status=202)
raise Http404
| 6,984
|
Python
|
.py
| 162
| 32.845679
| 83
| 0.625055
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,021
|
0004_remove_userprofile_fxa_uid.py
|
mdn_kuma/kuma/users/migrations/0004_remove_userprofile_fxa_uid.py
|
# Generated by Django 3.2.7 on 2021-10-20 07:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("users", "0003_auto_20211014_1214"),
]
operations = [
migrations.RemoveField(
model_name="userprofile",
name="fxa_uid",
),
]
| 332
|
Python
|
.py
| 12
| 20.916667
| 47
| 0.612698
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,022
|
0005_userprofile_is_subscriber.py
|
mdn_kuma/kuma/users/migrations/0005_userprofile_is_subscriber.py
|
# Generated by Django 3.2.7 on 2021-12-15 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0004_remove_userprofile_fxa_uid"),
]
operations = [
migrations.AddField(
model_name="userprofile",
name="is_subscriber",
field=models.BooleanField(default=False),
),
]
| 405
|
Python
|
.py
| 13
| 23.923077
| 53
| 0.630491
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,023
|
0003_auto_20211014_1214.py
|
mdn_kuma/kuma/users/migrations/0003_auto_20211014_1214.py
|
# Generated by Django 3.2.7 on 2021-10-14 12:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0002_auto_20210922_1159"),
]
operations = [
migrations.RemoveField(
model_name="userprofile",
name="claims",
),
migrations.AddField(
model_name="userprofile",
name="avatar",
field=models.URLField(blank=True, default="", max_length=512),
),
migrations.AddField(
model_name="userprofile",
name="fxa_refresh_token",
field=models.CharField(blank=True, default="", max_length=128),
),
]
| 711
|
Python
|
.py
| 22
| 23.454545
| 75
| 0.583333
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,024
|
0001_initial.py
|
mdn_kuma/kuma/users/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-08-05 12:47
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="UserProfile",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("claims", models.JSONField(default=dict)),
("locale", models.CharField(max_length=6, null=True)),
("is_subscriber", models.DateTimeField(null=True)),
(
"subscriber_number",
models.PositiveIntegerField(null=True, unique=True),
),
("created", models.DateTimeField(auto_now_add=True)),
("modified", models.DateTimeField(auto_now=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"verbose_name": "User profile",
},
),
]
| 1,569
|
Python
|
.py
| 44
| 20.886364
| 72
| 0.472679
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,025
|
0007_userprofile_subscription_type.py
|
mdn_kuma/kuma/users/migrations/0007_userprofile_subscription_type.py
|
# Generated by Django 3.2.10 on 2022-03-03 13:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0006_accountevent"),
]
operations = [
migrations.AddField(
model_name="userprofile",
name="subscription_type",
field=models.CharField(
blank=True,
choices=[
("mdn_plus_5m", "MDN Plus 5M"),
("mdn_plus_5y", "MDN Plus 5Y"),
("mdn_plus_10m", "MDN Plus 10M"),
("mdn_plus_10y", "MDN Plus 10Y"),
("", "None"),
],
default="",
max_length=512,
),
),
]
| 772
|
Python
|
.py
| 24
| 19.791667
| 53
| 0.454913
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,026
|
0006_accountevent.py
|
mdn_kuma/kuma/users/migrations/0006_accountevent.py
|
# Generated by Django 3.2.10 on 2021-12-27 09:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0005_userprofile_is_subscriber"),
]
operations = [
migrations.CreateModel(
name="AccountEvent",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("modified_at", models.DateTimeField(auto_now=True)),
("fxa_uid", models.CharField(blank=True, default="", max_length=128)),
("payload", models.TextField(blank=True, default="", max_length=2048)),
(
"event_type",
models.IntegerField(
blank=True,
choices=[
(1, "Password Changed"),
(2, "Profile Changed"),
(3, "Subscription Changed"),
(4, "Profile Deleted"),
],
default="",
),
),
(
"status",
models.IntegerField(
choices=[
(1, "Processed"),
(2, "Pending"),
(3, "Ignored"),
(4, "Not Implemented"),
],
default=2,
),
),
("jwt_id", models.CharField(blank=True, default="", max_length=256)),
("issued_at", models.CharField(blank=True, default="", max_length=32)),
],
options={
"ordering": ["-modified_at"],
},
),
]
| 2,117
|
Python
|
.py
| 56
| 19.285714
| 87
| 0.377432
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,027
|
0002_auto_20210922_1159.py
|
mdn_kuma/kuma/users/migrations/0002_auto_20210922_1159.py
|
# Generated by Django 3.2.7 on 2021-09-22 11:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0001_initial"),
]
operations = [
migrations.RemoveField(
model_name="userprofile",
name="is_subscriber",
),
migrations.RemoveField(
model_name="userprofile",
name="subscriber_number",
),
migrations.AddField(
model_name="userprofile",
name="fxa_uid",
field=models.CharField(blank=True, max_length=255, null=True, unique=True),
),
]
| 648
|
Python
|
.py
| 21
| 22.190476
| 87
| 0.585209
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,028
|
test_auth.py
|
mdn_kuma/kuma/users/tests/test_auth.py
|
from django.test import RequestFactory
from kuma.users.auth import logout_url
# TODO: Check which new tests are needed.
def test_logout_url(settings):
request = RequestFactory().get("/some/path")
request.session = {}
url = logout_url(request)
assert url == "/"
request = RequestFactory().get("/some/path?next=/docs")
request.session = {}
url = logout_url(request)
assert url == "/docs"
settings.LOGOUT_REDIRECT_URL = "/loggedout"
request = RequestFactory().get("/some/path")
request.session = {}
url = logout_url(request)
assert url == "/loggedout"
request.session["oidc_login_next"] = "/original"
url = logout_url(request)
assert url == "/original"
| 720
|
Python
|
.py
| 20
| 31.5
| 59
| 0.675793
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,029
|
test_tasks.py
|
mdn_kuma/kuma/users/tests/test_tasks.py
|
import pytest
from kuma.users.models import AccountEvent, UserProfile
from kuma.users.tasks import process_event_subscription_state_change
@pytest.mark.django_db
def test_process_event_subscription_state_change(wiki_user):
profile = UserProfile.objects.create(user=wiki_user)
assert profile.subscription_type == ""
created_event = AccountEvent.objects.create(
event_type=AccountEvent.EventType.SUBSCRIPTION_CHANGED,
status=AccountEvent.EventStatus.PENDING,
fxa_uid=wiki_user.username,
id=1,
payload='{"capabilities": ["mdn_plus_5y"], "isActive": true}',
)
process_event_subscription_state_change(created_event.id)
profile.refresh_from_db()
assert profile.subscription_type == "mdn_plus_5y"
@pytest.mark.django_db
def test_empty_subscription_inactive_change(wiki_user):
profile = UserProfile.objects.create(user=wiki_user)
assert profile.subscription_type == ""
created_event = AccountEvent.objects.create(
event_type=AccountEvent.EventType.SUBSCRIPTION_CHANGED,
status=AccountEvent.EventStatus.PENDING,
fxa_uid=wiki_user.username,
id=1,
payload='{"capabilities": [], "isActive": false}',
)
process_event_subscription_state_change(created_event.id)
profile.refresh_from_db()
assert profile.subscription_type == ""
assert not profile.is_subscriber
@pytest.mark.django_db
def test_valid_subscription_inactive_change(wiki_user):
profile = UserProfile.objects.create(user=wiki_user)
assert profile.subscription_type == ""
created_event = AccountEvent.objects.create(
event_type=AccountEvent.EventType.SUBSCRIPTION_CHANGED,
status=AccountEvent.EventStatus.PENDING,
fxa_uid=wiki_user.username,
id=1,
payload='{"capabilities": ["mdn_plus_5m"], "isActive": false}',
)
process_event_subscription_state_change(created_event.id)
profile.refresh_from_db()
assert profile.subscription_type == ""
assert not profile.is_subscriber
@pytest.mark.django_db
def test_invalid_subscription_change(wiki_user):
profile = UserProfile.objects.create(user=wiki_user)
assert profile.subscription_type == ""
created_event = AccountEvent.objects.create(
event_type=AccountEvent.EventType.SUBSCRIPTION_CHANGED,
status=AccountEvent.EventStatus.PENDING,
fxa_uid=wiki_user.username,
id=1,
payload='{"capabilities": ["invalid_subscription"], "isActive": true}',
)
process_event_subscription_state_change(created_event.id)
profile.refresh_from_db()
assert profile.subscription_type == ""
@pytest.mark.django_db
def test_multiple_valid_subscription_change_takes_first_in_array(wiki_user):
profile = UserProfile.objects.create(user=wiki_user)
assert profile.subscription_type == ""
created_event = AccountEvent.objects.create(
event_type=AccountEvent.EventType.SUBSCRIPTION_CHANGED,
status=AccountEvent.EventStatus.PENDING,
fxa_uid=wiki_user.username,
id=1,
payload='{"capabilities": ["mdn_plus", "mdn_plus_5y", "mdn_plus_5m"], "isActive": true}',
)
process_event_subscription_state_change(created_event.id)
profile.refresh_from_db()
# Ensure only first (lexicographical) valid is persisted
assert profile.subscription_type == "mdn_plus_5m"
| 3,381
|
Python
|
.py
| 76
| 38.513158
| 97
| 0.725221
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,030
|
test_views.py
|
mdn_kuma/kuma/users/tests/test_views.py
|
import urllib
import pytest
from django.urls import reverse
@pytest.mark.django_db
@pytest.mark.parametrize(
"email", (None, "ringo@beatles.com"), ids=("without-email", "with-email")
)
def test_no_prompt_login(client, settings, email):
params = {}
if email:
params.update(email=email)
response = client.get(reverse("no_prompt_login"), data=params)
assert response.status_code == 302
location = response.headers.get("location")
assert location
location = urllib.parse.unquote(location)
assert settings.OIDC_OP_AUTHORIZATION_ENDPOINT in location
assert "next=/en-US/plus" in location
if email:
assert "prompt=none" in location
assert f"login_hint={email}" in location
| 737
|
Python
|
.py
| 21
| 30.714286
| 77
| 0.71669
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,031
|
test_checks.py
|
mdn_kuma/kuma/users/tests/test_checks.py
|
from kuma.users.checks import (
MISSING_OIDC_CONFIGURATION_ERROR,
MISSING_OIDC_RP_CLIENT_ID_ERROR,
MISSING_OIDC_RP_CLIENT_SECRET_ERROR,
oidc_config_check,
)
def test_happy_path_config_check(mock_requests, settings):
mock_requests.register_uri(
"GET",
settings.OIDC_CONFIGURATION_URL + "/.well-known/openid-configuration",
json={
"scopes_supported": settings.OIDC_RP_SCOPES.split(),
"id_token_signing_alg_values_supported": [settings.OIDC_RP_SIGN_ALGO],
"authorization_endpoint": settings.OIDC_OP_AUTHORIZATION_ENDPOINT,
"userinfo_endpoint": settings.OIDC_OP_USER_ENDPOINT,
"token_endpoint": settings.OIDC_OP_TOKEN_ENDPOINT,
},
)
errors = oidc_config_check(None)
assert not errors
def test_disable_checks(settings):
# Note! No mock_requests in this test
settings.OIDC_CONFIGURATION_CHECK = False
errors = oidc_config_check(None)
assert not errors
def test_not_happy_path_config_check(mock_requests, settings):
settings.OIDC_CONFIGURATION_URL += "/"
mock_requests.register_uri(
"GET",
settings.OIDC_CONFIGURATION_URL + ".well-known/openid-configuration",
json={
"scopes_supported": ["foo"],
"id_token_signing_alg_values_supported": ["XXX"],
"authorization_endpoint": "authorization?",
"token_endpoint": "token?",
},
)
errors = oidc_config_check(None)
assert errors
# TODO Put back to 5 when missing OIDC Scopes are correct. See checks.py
assert len(errors) == 4
ids = [error.id for error in errors]
assert ids == [MISSING_OIDC_CONFIGURATION_ERROR] * len(errors)
def test_missing_important_rp_client_credentials(mock_requests, settings):
settings.OIDC_CONFIGURATION_URL += "/.well-known/openid-configuration"
mock_requests.register_uri(
"GET",
settings.OIDC_CONFIGURATION_URL,
json={
"scopes_supported": settings.OIDC_RP_SCOPES.split(),
"id_token_signing_alg_values_supported": [settings.OIDC_RP_SIGN_ALGO],
"authorization_endpoint": settings.OIDC_OP_AUTHORIZATION_ENDPOINT,
"userinfo_endpoint": settings.OIDC_OP_USER_ENDPOINT,
"token_endpoint": settings.OIDC_OP_TOKEN_ENDPOINT,
},
)
settings.OIDC_RP_CLIENT_ID = None
settings.OIDC_RP_CLIENT_SECRET = ""
errors = oidc_config_check(None)
assert errors
ids = [error.id for error in errors]
assert ids == [MISSING_OIDC_RP_CLIENT_ID_ERROR, MISSING_OIDC_RP_CLIENT_SECRET_ERROR]
| 2,616
|
Python
|
.py
| 62
| 34.806452
| 88
| 0.668765
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,032
|
pytest.py
|
mdn_kuma/kuma/settings/pytest.py
|
from .local import *
DEBUG = False
ENABLE_RESTRICTIONS_BY_HOST = False
TEMPLATES[0]["OPTIONS"]["debug"] = True # Enable recording of templates
CELERY_TASK_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
ES_LIVE_INDEX = config("ES_LIVE_INDEX", default=False, cast=bool)
# Always make sure we never test against a real Elasticsearch server
ES_URLS = ["1.2.3.4:9200"]
# This makes sure that if we ever fail to mock the connection,
# it won't retry for many many seconds.
ES_RETRY_SLEEPTIME = 0
ES_RETRY_ATTEMPTS = 1
ES_RETRY_JITTER = 0
# SHA1 because it is fast, and hard-coded in the test fixture JSON.
PASSWORD_HASHERS = ("django.contrib.auth.hashers.SHA1PasswordHasher",)
LOGGING["loggers"].update(
{
"django.db.backends": {
"handlers": ["console"],
"propagate": True,
"level": "WARNING",
},
"kuma.search.utils": {"handlers": [], "propagate": False, "level": "CRITICAL"},
}
)
# Change the cache key prefix for tests, to avoid overwriting runtime.
for cache_settings in CACHES.values():
current_prefix = cache_settings.get("KEY_PREFIX", "")
cache_settings["KEY_PREFIX"] = "test." + current_prefix
# Always assume we prefer https.
PROTOCOL = "https://"
# Never rely on the .env
GOOGLE_ANALYTICS_ACCOUNT = None
# Silence warnings about defaults that change in django-storages 2.0
AWS_BUCKET_ACL = None
AWS_DEFAULT_ACL = None
# To make absolutely sure we never accidentally trigger the GA tracking
# within tests to the actual (and default) www.google-analytics.com this is
# an extra safeguard.
GOOGLE_ANALYTICS_TRACKING_URL = "https://thisllneverwork.example.com/collect"
# Because that's what all the tests presume.
SITE_ID = 1
# For legacy reasons, the tests assume these are always true so don't
# let local overrides take effect.
INDEX_HTML_ATTRIBUTES = True
INDEX_CSS_CLASSNAMES = True
# Amount for the monthly subscription.
# It's hardcoded here in case some test depends on the number and it futureproofs
# our tests to not deviate when the actual number changes since that number
# change shouldn't affect the tests.
CONTRIBUTION_AMOUNT_USD = 4.99
# So it never accidentally actually uses the real value
BOOKMARKS_BASE_URL = "https://developer.example.com"
# OIDC related
OIDC_CONFIGURATION_CHECK = True
OIDC_RP_CLIENT_ID = "123456789"
OIDC_RP_CLIENT_SECRET = "xyz-secret-123"
OIDC_CONFIGURATION_URL = "https://accounts.examples.com"
OIDC_OP_AUTHORIZATION_ENDPOINT = f"{OIDC_CONFIGURATION_URL}/authorization"
OIDC_OP_TOKEN_ENDPOINT = f"{OIDC_CONFIGURATION_URL}/v1/token"
OIDC_OP_USER_ENDPOINT = f"{OIDC_CONFIGURATION_URL}/v1/profile"
OIDC_OP_JWKS_ENDPOINT = f"{OIDC_CONFIGURATION_URL}/v1/jwks"
OIDC_RP_SIGN_ALGO = "XYZ"
OIDC_USE_NONCE = False
OIDC_RP_SCOPES = "openid profile email"
| 2,797
|
Python
|
.py
| 66
| 39.969697
| 87
| 0.74871
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,033
|
prod.py
|
mdn_kuma/kuma/settings/prod.py
|
from .common import *
ATTACHMENT_HOST = config("ATTACHMENT_HOST", default="mdn.mozillademos.org")
ALLOW_ROBOTS = config("ALLOW_ROBOTS", default=True, cast=bool)
# Email
DEFAULT_FROM_EMAIL = config(
"DEFAULT_FROM_EMAIL", default="no-reply@developer.mozilla.org"
)
SERVER_EMAIL = config("SERVER_EMAIL", default="mdn-prod-noreply@mozilla.com")
# Cache
CACHES["default"]["TIMEOUT"] = 60 * 60 * 24
MEDIA_URL = config("MEDIA_URL", default="https://developer.cdn.mozilla.net/media/")
CELERY_TASK_ALWAYS_EAGER = config("CELERY_TASK_ALWAYS_EAGER", False, cast=bool)
CELERYD_MAX_TASKS_PER_CHILD = (
config("CELERYD_MAX_TASKS_PER_CHILD", default=500, cast=int) or None
)
ES_INDEX_PREFIX = config("ES_INDEX_PREFIX", default="mdnprod")
ES_LIVE_INDEX = config("ES_LIVE_INDEX", default=True, cast=bool)
| 802
|
Python
|
.py
| 17
| 45.352941
| 83
| 0.741977
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,034
|
local.py
|
mdn_kuma/kuma/settings/local.py
|
from .common import *
# Settings for Docker Development
INTERNAL_IPS = ("127.0.0.1",)
# Default DEBUG to True, and recompute derived settings
DEBUG = config("DEBUG", default=True, cast=bool)
DEBUG_PROPAGATE_EXCEPTIONS = config(
"DEBUG_PROPAGATE_EXCEPTIONS", default=DEBUG, cast=bool
)
PROTOCOL = config("PROTOCOL", default="https://")
DOMAIN = config("DOMAIN", default="developer-local.allizom.org")
SITE_URL = config("SITE_URL", default=PROTOCOL + DOMAIN)
| 465
|
Python
|
.py
| 11
| 40.545455
| 64
| 0.753333
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,035
|
common.py
|
mdn_kuma/kuma/settings/common.py
|
import json
from collections import namedtuple
from email.utils import parseaddr
from pathlib import Path
import dj_database_url
import sentry_sdk
from decouple import Csv, config
from sentry_sdk.integrations.django import DjangoIntegration
DEBUG = config("DEBUG", default=False, cast=bool)
DEV = config("DEV", cast=bool, default=False)
BASE_DIR = Path(__file__).resolve().parent.parent
ADMIN_EMAILS = config("ADMIN_EMAILS", default="mdn-dev@mozilla.com", cast=Csv())
ADMINS = zip(config("ADMIN_NAMES", default="MDN devs", cast=Csv()), ADMIN_EMAILS)
PROTOCOL = config("PROTOCOL", default="https://")
DOMAIN = config("DOMAIN", default="developer.mozilla.org")
SITE_URL = config("SITE_URL", default=PROTOCOL + DOMAIN)
PRODUCTION_DOMAIN = "developer.mozilla.org"
PRODUCTION_URL = "https://" + PRODUCTION_DOMAIN
STAGING_DOMAIN = "developer.allizom.org"
STAGING_URL = "https://" + STAGING_DOMAIN
_PROD_INTERACTIVE_EXAMPLES = "https://interactive-examples.mdn.mozilla.net"
INTERACTIVE_EXAMPLES_BASE = config(
"INTERACTIVE_EXAMPLES_BASE", default=_PROD_INTERACTIVE_EXAMPLES
)
MAINTENANCE_MODE = config("MAINTENANCE_MODE", default=False, cast=bool)
REVISION_HASH = config("REVISION_HASH", default="undefined")
MANAGERS = ADMINS
CONN_MAX_AGE = config("CONN_MAX_AGE", default=60)
DATABASES = {
"default": config(
"DATABASE_URL",
default="postgresql://kuma:kuma@localhost/kuma",
cast=dj_database_url.parse,
)
}
# Cache Settings
CACHE_PREFIX = "kuma"
CACHE_COUNT_TIMEOUT = 60 # in seconds
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"TIMEOUT": CACHE_COUNT_TIMEOUT * 60,
"KEY_PREFIX": CACHE_PREFIX,
"LOCATION": config("REDIS_CACHE_SERVER", default="redis://127.0.0.1:6379"),
}
}
# Email
# vars().update(config("EMAIL_URL", default="console://", cast=dj_email_url.parse))
EMAIL_SUBJECT_PREFIX = config("EMAIL_SUBJECT_PREFIX", default="[mdn]")
# Ensure EMAIL_SUBJECT_PREFIX has one trailing space
EMAIL_SUBJECT_PREFIX = EMAIL_SUBJECT_PREFIX.strip() + " "
# Addresses email comes from
DEFAULT_FROM_EMAIL = config(
"DEFAULT_FROM_EMAIL", default="notifications@developer.mozilla.org"
)
SERVER_EMAIL = config("SERVER_EMAIL", default="server-error@developer.mozilla.org")
# PLATFORM_NAME = platform.node()
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "UTC"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-US"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Accepted locales.
# The order of some codes is important. For example, 'pt-PT' comes before
# 'pt-BR', so that 'pt-PT' will be selected when the generic 'pt' is requested.
# Candidate locales should be included here and in CANDIDATE_LOCALES
ACCEPTED_LOCALES = (
"en-US", # English
"de", # German
"es", # Spanish
"fr", # French
"ja", # Japanese
"ko", # Korean
"pl", # Polish
"pt-BR", # Portuguese (Brazil)
"ru", # Russian
"zh-CN", # Chinese (China)
"zh-TW", # Chinese (Taiwan, Province of China)
)
# When there are multiple options for a given language, this gives the
# preferred locale for that language (language => preferred locale).
PREFERRED_LOCALE = {
"zh": "zh-CN",
}
# Locales being considered for MDN. This makes the UI strings available for
# localization in Pontoon, but pages can not be translated into this language.
# https://developer.mozilla.org/en-US/docs/MDN/Contribute/Localize/Starting_a_localization
# These should be here and in the ACCEPTED_LOCALES list
CANDIDATE_LOCALES = ()
# Asserted here to avoid a unit test that is skipped when empty
for candidate in CANDIDATE_LOCALES:
assert candidate in ACCEPTED_LOCALES
ENABLE_CANDIDATE_LANGUAGES = config(
"ENABLE_CANDIDATE_LANGUAGES", default=DEBUG, cast=bool
)
if ENABLE_CANDIDATE_LANGUAGES:
ENABLED_LOCALES = ACCEPTED_LOCALES[:]
else:
ENABLED_LOCALES = [
locale for locale in ACCEPTED_LOCALES if locale not in CANDIDATE_LOCALES
]
# Override generic locale handling with explicit mappings.
# Keys are the requested locale (lowercase); values are the delivered locale.
LOCALE_ALIASES = {
# Create aliases for over-specific locales.
"cn": "zh-CN",
# Create aliases for locales which use region subtags to assume scripts.
"zh-hans": "zh-CN",
"zh-hant": "zh-TW",
# Map locale whose region subtag is separated by `_`(underscore)
"zh_cn": "zh-CN",
"zh_tw": "zh-TW",
}
LANGUAGE_URL_MAP = dict([(i.lower(), i) for i in ENABLED_LOCALES])
for requested_lang, delivered_lang in LOCALE_ALIASES.items():
if delivered_lang in ENABLED_LOCALES:
LANGUAGE_URL_MAP[requested_lang.lower()] = delivered_lang
def _get_locales():
"""
Load LOCALES data from languages.json
languages.json is from the product-details project:
https://product-details.mozilla.org/1.0/languages.json
"""
lang_path = BASE_DIR / "settings" / "languages.json"
with open(lang_path) as lang_file:
json_locales = json.load(lang_file)
locales = {}
_Language = namedtuple("Language", "english native")
for locale, meta in json_locales.items():
locales[locale] = _Language(meta["English"], meta["native"])
return locales
LOCALES = _get_locales()
LANGUAGES = [(locale, LOCALES[locale].native) for locale in ENABLED_LOCALES]
# Language list sorted for forms (English, then alphabetical by locale code)
SORTED_LANGUAGES = [LANGUAGES[0]] + sorted(LANGUAGES[1:])
LANGUAGE_COOKIE_NAME = "preferredlocale"
# The number of seconds we are keeping the language preference cookie. (3 years)
LANGUAGE_COOKIE_AGE = 3 * 365 * 24 * 60 * 60
LANGUAGE_COOKIE_SECURE = "localhost" not in DOMAIN
SITE_ID = config("SITE_ID", default=1, cast=int)
# The reason we need this set up is so the Django Admin static assets
# work in production.
STATIC_URL = config("STATIC_URL", default="/static/")
STATIC_ROOT = BASE_DIR / "static"
SERVE_MEDIA = False
# Paths that don't require a locale prefix.
LANGUAGE_URL_IGNORED_PATHS = (
"healthz",
"readiness",
"media",
"admin",
"robots.txt",
"contribute.json",
"services",
"static",
"1",
"files",
"@api",
"__debug__",
".well-known",
"users/github/login/callback/",
"favicon.ico",
"_kuma_status.json",
# Legacy files, circa 2008, served in AWS
"diagrams",
"presentations",
"samples",
# Legacy files, circa 2008, now return 404
"patches",
"web-tech",
"css",
"index.php", # Legacy MediaWiki endpoint, return 404
"i18n",
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = config(
"SECRET_KEY", default="#%tc(zja8j01!r#h_y)=hy!^k)9az74k+-ib&ij&+**s3-e^_z"
)
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
# Whitenoise is used to serve the static files for Django Admin.
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"kuma.users.middleware.ValidateAccessTokenMiddleware",
]
ROOT_URLCONF = "kuma.urls"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# Kuma
"kuma.core.apps.CoreConfig",
"kuma.users.apps.UsersConfig",
"kuma.api.apps.APIConfig",
"kuma.attachments.apps.AttachmentsConfig",
"kuma.plus.apps.PlusConfig",
"kuma.documenturls.apps.DocumentURLsConfig",
"kuma.bookmarks.apps.BookmarksConfig",
"kuma.notifications.apps.NotificationsConfig",
# 3rd party
"mozilla_django_oidc",
"django_extensions",
]
NOTIFICATIONS_ADMIN_TOKEN = config("NOTIFICATIONS_ADMIN_TOKEN", default="")
NOTIFICATIONS_CHANGES_URL = config(
"NOTIFICATIONS_CHANGES_URL",
default="https://updates.developer.allizom.org/notifications/",
)
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
# Authentication
AUTHENTICATION_BACKENDS = [
"kuma.users.auth.KumaOIDCAuthenticationBackend",
"django.contrib.auth.backends.ModelBackend",
]
# This will download the configuration and set up all the settings that
# the mozilla_django_oidc needs.
OIDC_CONFIGURATION_URL = config(
"OIDC_CONFIGURATION_URL",
# Change to https://accounts.stage.mozaws.net/.well-known/openid-configuration
# for stage.
default="https://accounts.firefox.com/.well-known/openid-configuration",
)
# This will open `OIDC_CONFIGURATION_URL` and compare its JSON with the
# other settings.
OIDC_CONFIGURATION_CHECK = config(
"OIDC_CONFIGURATION_CHECK", cast=bool, default=not DEBUG
)
OIDC_OP_AUTHORIZATION_ENDPOINT = config(
"OIDC_OP_AUTHORIZATION_ENDPOINT",
default="https://accounts.firefox.com/authorization",
)
OIDC_OP_TOKEN_ENDPOINT = config(
"OIDC_OP_TOKEN_ENDPOINT", default="https://oauth.accounts.firefox.com/v1/token"
)
OIDC_OP_USER_ENDPOINT = config(
"OIDC_OP_USER_ENDPOINT", default="https://profile.accounts.firefox.com/v1/profile"
)
OIDC_OP_JWKS_ENDPOINT = config(
"OIDC_OP_JWKS_ENDPOINT", default="https://oauth.accounts.firefox.com/v1/jwks"
)
OIDC_RP_SIGN_ALGO = config("OIDC_RP_SIGN_ALGO", default="RS256")
# Firefox Accounts doesn't support nonce, so don't bother sending it.
OIDC_USE_NONCE = config("OIDC_USE_NONCE", cast=bool, default=False)
# The default is 'openid email' but according to openid-configuration they
# will send 'openid profile email'.
OIDC_RP_SCOPES = config(
"OIDC_RP_SCOPES", default="openid profile email profile:subscriptions"
)
# If you're doing local development with Yari, it's recommened that you add
# echo 'OIDC_REDIRECT_ALLOWED_HOSTS=localhost:3000' >> .env
# so you get redirected back to http://localhost:3000/... after signing in.
OIDC_REDIRECT_ALLOWED_HOSTS = config(
"OIDC_REDIRECT_ALLOWED_HOSTS", default="", cast=Csv()
)
OIDC_AUTH_REQUEST_EXTRA_PARAMS = {"access_type": "offline"}
OIDC_CALLBACK_CLASS = "kuma.users.views.KumaOIDCAuthenticationCallbackView"
# Allow null on these because you should be able run Kuma with these set.
# It'll just mean you can't use kuma to authenticate. And a warning
# (or error if !DEBUG) from the system checks will remind you.
OIDC_RP_CLIENT_ID = config("OIDC_RP_CLIENT_ID", default=None)
OIDC_RP_CLIENT_SECRET = config("OIDC_RP_CLIENT_SECRET", default=None)
# Function that gets called
OIDC_OP_LOGOUT_URL_METHOD = "kuma.users.auth.logout_url"
# Store the access token in session
OIDC_STORE_ACCESS_TOKEN = config("OIDC_STORE_ACCESS_TOKEN", cast=bool, default=True)
# Set the issuer of the token.
FXA_TOKEN_ISSUER = config("FXA_TOKEN_ISSUER", default="https://accounts.firefox.com")
# Validate access token endpoint.
FXA_VERIFY_URL = config(
"FXA_VERIFY_URL", default="https://oauth.accounts.firefox.com/v1/verify"
)
# Set token re-check time to an hour in seconds
FXA_TOKEN_EXPIRY = config("FXA_TOKEN_EXPIRY", default=43200)
FXA_SET_ISSUER = config("FXA_SET_ISSUER", default="https://accounts.firefox.com")
FXA_SET_ID_PREFIX = config(
"FXA_SET_ID_PREFIX", default="https://schemas.accounts.firefox.com/event/"
)
# The mozilla-django-oidc package uses this URL if a "next" URL isn't specified.
LOGIN_REDIRECT_URL = "/"
# The mozilla-django-oidc package uses this URL if there's a failure during login.
# Note that if the user has an active FxA account, but is not an MDN-Plus subscriber,
# that's considered a login failure.
LOGIN_REDIRECT_URL_FAILURE = "/plus?reason=no-active-subscription-found"
# Session cookies
SESSION_COOKIE_DOMAIN = DOMAIN
SESSION_COOKIE_SECURE = config("SESSION_COOKIE_SECURE", default=True, cast=bool)
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = config("SESSION_COOKIE_AGE", default=60 * 60 * 24 * 365, cast=int)
# bug 856061
ALLOWED_HOSTS = config(
"ALLOWED_HOSTS",
default="developer-local.allizom.org, mdn-local.mozillademos.org",
cast=Csv(),
)
_PROD_ATTACHMENT_HOST = "mdn.mozillademos.org"
_PROD_ATTACHMENT_SITE_URL = "https://" + _PROD_ATTACHMENT_HOST
ATTACHMENT_HOST = config("ATTACHMENT_HOST", default=_PROD_ATTACHMENT_HOST)
ATTACHMENT_SITE_URL = PROTOCOL + ATTACHMENT_HOST
_PROD_ATTACHMENT_ORIGIN = "demos-origin.mdn.mozit.cloud"
ATTACHMENT_ORIGIN = config("ATTACHMENT_ORIGIN", default=_PROD_ATTACHMENT_ORIGIN)
# This should never be false for the production and stage deployments.
ENABLE_RESTRICTIONS_BY_HOST = config(
"ENABLE_RESTRICTIONS_BY_HOST", default=True, cast=bool
)
# Allow robots, but restrict some paths
# If the domain is a CDN, the CDN origin should be included.
ALLOW_ROBOTS_WEB_DOMAINS = set(
config(
"ALLOW_ROBOTS_WEB_DOMAINS",
default="developer.mozilla.org",
cast=Csv(),
)
)
# Allow robots, no path restrictions
# If the domain is a CDN, the CDN origin should be included.
ALLOW_ROBOTS_DOMAINS = set(
config(
"ALLOW_ROBOTS_DOMAINS",
default=",".join((_PROD_ATTACHMENT_HOST, _PROD_ATTACHMENT_ORIGIN)),
cast=Csv(),
)
)
# Email
EMAIL_BACKEND = config(
"EMAIL_BACKEND", default="django.core.mail.backends.filebased.EmailBackend"
)
EMAIL_FILE_PATH = "/app/tmp/emails"
# Celery (asynchronous tasks)
CELERY_BROKER_URL = config("CELERY_BROKER_URL", default="redis://0.0.0.0:6379/0")
CELERY_TASK_ALWAYS_EAGER = config("CELERY_TASK_ALWAYS_EAGER", False, cast=bool)
CELERY_SEND_TASK_ERROR_EMAILS = True
CELERY_WORKER_CONCURRENCY = config("CELERY_WORKER_CONCURRENCY", default=4, cast=int)
# Maximum tasks run before auto-restart of child process,
# to mitigate memory leaks. None / 0 means unlimited tasks
CELERY_WORKER_MAX_TASKS_PER_CHILD = (
config("CELERY_WORKER_MAX_TASKS_PER_CHILD", default=0, cast=int) or None
)
# Sadly, kuma depends on pickle being the default serializer.
# In Celery 4, the default is now JSON.
# It's probably too late to switch all tasks to work with either.
# Just remember, avoid passing types that are non-trivial and is
# different in pickle vs json. Keep things simple. Even if it means
# you have to do type conversions in the tasks' code.
CELERY_ACCEPT_CONTENT = ["pickle", "application/x-python-serialize"]
CELERY_TASK_SERIALIZER = "pickle"
CELERY_RESULT_SERIALIZER = "pickle"
CELERY_EVENT_SERIALIZER = "pickle"
CELERY_TASK_ROUTES = {
"kuma.core.tasks.clean_sessions": {"queue": "mdn_purgeable"},
}
# Do not change this without also deleting all wiki documents:
# WIKI_DEFAULT_LANGUAGE = LANGUAGE_CODE
# Number of expired sessions to cleanup up in one go.
SESSION_CLEANUP_CHUNK_SIZE = config(
"SESSION_CLEANUP_CHUNK_SIZE", default=1000, cast=int
)
# Email address from which welcome emails will be sent
WELCOME_EMAIL_FROM = config(
"WELCOME_EMAIL_FROM",
default="MDN team <mdn-admins@mozilla.org>",
)
# If this fails, SMTP will probably also fail.
# E.g. https://github.com/mdn/kuma/issues/7121
assert parseaddr(WELCOME_EMAIL_FROM)[1].count("@") == 1, parseaddr(WELCOME_EMAIL_FROM)
# Email address to request admin intervention
EMAIL_LIST_MDN_ADMINS = config(
"EMAIL_LIST_MDN_ADMINS", default="mdn-admins@mozilla.org"
)
# Elasticsearch related settings.
# XXX Peter: Need to audit which of these we actually use!
ES_DEFAULT_NUM_REPLICAS = 1
ES_DEFAULT_NUM_SHARDS = 5
ES_DEFAULT_REFRESH_INTERVAL = "5s"
ES_INDEX_PREFIX = config("ES_INDEX_PREFIX", default="mdn")
ES_INDEXES = {"default": "main_index"}
# Specify the extra timeout in seconds for the indexing ES connection.
ES_INDEXING_TIMEOUT = 30
ES_LIVE_INDEX = config("ES_LIVE_INDEX", default=False, cast=bool)
ES_URLS = config("ES_URLS", default="127.0.0.1:9200", cast=Csv())
# Specify a max length for the q param to avoid unnecessary burden on
# elasticsearch for queries that are probably either mistakes or junk.
ES_Q_MAXLENGTH = config("ES_Q_MAXLENGTH", default=200, cast=int)
ES_RETRY_SLEEPTIME = config("ES_RETRY_SLEEPTIME", default=1, cast=int)
ES_RETRY_ATTEMPTS = config("ES_RETRY_ATTEMPTS", default=5, cast=int)
ES_RETRY_JITTER = config("ES_RETRY_JITTER", default=1, cast=int)
# Logging is merged with the default logging
# https://github.com/django/django/blob/stable/1.11.x/django/utils/log.py
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {"require_debug_true": {"()": "django.utils.log.RequireDebugTrue"}},
"formatters": {"simple": {"format": "%(name)s:%(levelname)s %(message)s"}},
"handlers": {
"console": {
"level": "DEBUG",
"filters": ["require_debug_true"],
"class": "logging.StreamHandler",
},
"console-simple": {
"level": "DEBUG",
"filters": ["require_debug_true"],
"class": "logging.StreamHandler",
"formatter": "simple",
},
},
"loggers": {
"django": {"handlers": ["console"], "level": "INFO"}, # Drop mail_admins
"kuma": {"handlers": ["console-simple"], "propagate": True, "level": "ERROR"},
"elasticsearch": {
"handlers": ["console-simple"],
"level": config("ES_LOG_LEVEL", default="ERROR"),
},
"elasticsearch.trace": {
"handlers": ["console-simple"],
"level": config("ES_TRACE_LOG_LEVEL", default="ERROR"),
"propagate": False,
},
"urllib3": {"handlers": ["console-simple"], "level": "ERROR"},
},
}
CSRF_COOKIE_DOMAIN = DOMAIN
CSRF_COOKIE_SECURE = config("CSRF_COOKIE_SECURE", default=True, cast=bool)
# We need to explcitly set the trusted origins, because when CSRF_COOKIE_DOMAIN
# is explicitly set, as we do above, Django's CsrfViewMiddleware will reject
# the request unless the domain of the incoming referer header matches not just
# the CSRF_COOKIE_DOMAIN alone, but the CSRF_COOKIE_DOMAIN with the server port
# appended as well, and we don't want that behavior (a server port of 8000 is
# added both in secure local development as well as in K8s stage/production, so
# that will guarantee a mismatch with the referer).
CSRF_TRUSTED_ORIGINS = [DOMAIN]
X_FRAME_OPTIONS = "DENY"
# Caching constants for the Cache-Control header.
CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE = config(
"CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE", default=60 * 5, cast=int
)
ATTACHMENTS_AWS_S3_CUSTOM_DOMAIN = config(
"ATTACHMENTS_AWS_S3_CUSTOM_DOMAIN", default="media.prod.mdn.mozit.cloud"
) # For example, Cloudfront CDN domain
ATTACHMENTS_AWS_S3_SECURE_URLS = config(
"ATTACHMENTS_AWS_S3_SECURE_URLS", default=True, cast=bool
) # Does the custom domain use TLS
ATTACHMENTS_AWS_S3_CUSTOM_URL = f"{'https' if ATTACHMENTS_AWS_S3_SECURE_URLS else 'http'}://{ATTACHMENTS_AWS_S3_CUSTOM_DOMAIN}"
ATTACHMENTS_AWS_S3_ENDPOINT_URL = config(
"ATTACHMENTS_AWS_S3_ENDPOINT_URL", default=None
)
# Kuma doesn't index anything, that's done by the Yari Deployer, but we need
# to know what the index is called for searching.
SEARCH_INDEX_NAME = config("SEARCH_INDEX_NAME", default="mdn_docs")
# When someone wants to bookmark something we only allow the URI (pathname)
# to be supplied. We control what the absolute URL becomes based on that.
# It might be practical to override this in local development to something like:
#
# echo 'BOOKMARKS_BASE_URL=http://localhost:5000' >> .env
#
# So it can read from your local Yari instance.
BOOKMARKS_BASE_URL = config(
"BOOKMARKS_BASE_URL", default="https://developer.mozilla.org"
)
API_V1_BOOKMARKS_PAGE_SIZE = config("API_V1_BOOKMARKS_PAGE_SIZE", cast=int, default=20)
API_V1_PAGE_SIZE = config("API_V1_PAGE_SIZE", cast=int, default=20)
SENTRY_DSN = config("SENTRY_DSN", default="")
if SENTRY_DSN:
sentry_sdk.init(
dsn=SENTRY_DSN,
integrations=[DjangoIntegration()],
)
# Honor the X-Forwarded-Proto header, so we can detect HTTPS when deployed behind a
# load balancer that's terminating the HTTPS connection and speaking to us with HTTP.
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# MDN Plus section
MDN_PLUS_SUBSCRIPTION = config("MDN_PLUS_SUBSCRIPTION", default="mdn_plus")
MAX_NON_SUBSCRIBED = {"notification": 3, "collection": 5}
| 21,063
|
Python
|
.py
| 502
| 38.585657
| 127
| 0.723161
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,036
|
admin_urls.py
|
mdn_kuma/kuma/api/admin_urls.py
|
from django.urls import path
from kuma.api.v1.api import admin_api
from kuma.api.v1.plus.notifications import admin_router
admin_api.add_router("/", admin_router)
urlpatterns = [
path("", admin_api.urls),
]
| 214
|
Python
|
.py
| 7
| 28.571429
| 55
| 0.764706
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,037
|
urls.py
|
mdn_kuma/kuma/api/urls.py
|
from django.urls import include, re_path
urlpatterns = [
re_path("^v1/", include("kuma.api.v1.urls")),
]
| 110
|
Python
|
.py
| 4
| 25.25
| 49
| 0.685714
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,038
|
apps.py
|
mdn_kuma/kuma/api/apps.py
|
from django.apps import AppConfig
from django.conf import settings
from elasticsearch_dsl.connections import connections
class APIConfig(AppConfig):
"""
The Django App Config class to store information about the API app
and do startup time things.
"""
name = "kuma.api"
verbose_name = "API"
def ready(self):
# Configure Elasticsearch connections for connection pooling.
connections.configure(
default={"hosts": settings.ES_URLS},
)
| 500
|
Python
|
.py
| 15
| 27.8
| 70
| 0.70894
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,039
|
pagination.py
|
mdn_kuma/kuma/api/v1/pagination.py
|
from __future__ import annotations
from typing import Generic, TypeVar
from django.conf import settings
from django.db.models import QuerySet
from django.http import HttpRequest
from django.middleware.csrf import get_token
from ninja import Field
from ninja.pagination import LimitOffsetPagination
from ninja.schema import Schema
from pydantic.generics import GenericModel
ItemSchema = TypeVar("ItemSchema")
class PaginationInput(Schema):
page: int = Field(1, gt=0)
per_page: int = Field(settings.API_V1_PAGE_SIZE, ge=0, le=100)
class LimitOffsetInput(Schema):
limit: int = Field(20, gt=0)
offset: int = Field(0, ge=1)
class PaginatedMetadata(Schema):
total: int
page: int
per_page: int
max_non_subscribed: int
class PaginatedResponse(Schema, GenericModel, Generic[ItemSchema]):
items: list[ItemSchema]
metadata: PaginatedMetadata
csrfmiddlewaretoken: str
class LimitOffsetPaginatedData:
items: QuerySet | list
csrfmiddlewaretoken: str
def __init__(self, items: QuerySet | list, csrfmiddlewaretoken: str):
self.items = items
self.csrfmiddlewaretoken = csrfmiddlewaretoken
class LimitOffsetPaginatedResponse(Schema, GenericModel, Generic[ItemSchema]):
items: list[ItemSchema]
csrfmiddlewaretoken: str
class LimitOffsetPaginationWithMeta(LimitOffsetPagination):
def paginate_queryset(
self, items: QuerySet, request: HttpRequest, **params
) -> LimitOffsetPaginatedData:
paginated_items = super().paginate_queryset(items, request, **params)
return LimitOffsetPaginatedData(
paginated_items, csrfmiddlewaretoken=get_token(request)
)
| 1,679
|
Python
|
.py
| 43
| 34.55814
| 78
| 0.766996
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,040
|
urls.py
|
mdn_kuma/kuma/api/v1/urls.py
|
from django.urls import path
from . import search
from .api import api
from .plus.bookmarks import router as bookmarks_router
from .plus.landing_page import router as landing_page_router
from .plus.notifications import notifications_router, watch_router
from .views import settings_router
api.add_router("/settings", settings_router)
api.add_router("/plus/notifications/", notifications_router)
api.add_router("/plus/", watch_router)
api.add_router("/plus/collection/", bookmarks_router)
api.add_router("/plus/landing-page/", landing_page_router)
urlpatterns = [
path("", api.urls),
path("search/<locale>", search.search, name="api.v1.search_legacy"),
path("search", search.search, name="api.v1.search"),
]
| 722
|
Python
|
.py
| 17
| 40.588235
| 72
| 0.769231
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,041
|
api.py
|
mdn_kuma/kuma/api/v1/api.py
|
from django.http import HttpResponse
from django.utils.cache import add_never_cache_headers
from ninja import NinjaAPI
from ratelimit.exceptions import Ratelimited
from .auth import admin_auth, profile_auth
class NoCacheNinjaAPI(NinjaAPI):
def create_response(self, *args, **kwargs) -> HttpResponse:
response = super().create_response(*args, **kwargs)
add_never_cache_headers(response)
return response
api = NoCacheNinjaAPI(auth=profile_auth, csrf=True, version="v1")
admin_api = NoCacheNinjaAPI(
auth=admin_auth, csrf=False, version="v1", urls_namespace="admin_api"
)
@api.exception_handler(Ratelimited)
def rate_limited(request, exc):
return api.create_response(request, {"error": "Too many requests"}, status=429)
| 761
|
Python
|
.py
| 17
| 41.176471
| 83
| 0.764946
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,042
|
auth.py
|
mdn_kuma/kuma/api/v1/auth.py
|
from __future__ import annotations
from typing import Any
from django.conf import settings
from django.http import HttpRequest
from ninja.security import HttpBearer, SessionAuth
from kuma.users.auth import KumaOIDCAuthenticationBackend, is_authorized_request
from kuma.users.models import UserProfile
class NotASubscriber(Exception):
pass
def is_subscriber(request, raise_error=False) -> bool:
try:
user = request.user
if user.is_authenticated:
return True
if access_token := request.META.get("HTTP_AUTHORIZATION"):
payload = is_authorized_request(access_token)
if error := payload.get("error"):
raise NotASubscriber(error)
# create user if there is not one
request.user = KumaOIDCAuthenticationBackend.create_or_update_subscriber(
payload
)
return True
raise NotASubscriber("not a subscriber")
except NotASubscriber:
if raise_error:
raise
return False
class SubscriberAuth(SessionAuth):
def authenticate(self, request: HttpRequest, key: str | None) -> Any:
if is_subscriber(request):
return request.user
return None
subscriber_auth = SubscriberAuth()
class AdminAuth(HttpBearer):
def authenticate(self, request: HttpRequest, token: str) -> Any:
return token == settings.NOTIFICATIONS_ADMIN_TOKEN
admin_auth = AdminAuth()
class ProfileAuth(SessionAuth):
"""
Requires a Django authenticated user.
Does not actually *require* a profile, but for users without a profile will
rather return the unsaved profile ready for saving (available in
``request.auth``).
"""
def authenticate(self, request: HttpRequest, key: str | None) -> Any:
user = request.user
if not user.is_authenticated:
return None
try:
return UserProfile.objects.get(user=user)
except UserProfile.DoesNotExist:
return UserProfile(user=user)
profile_auth = ProfileAuth()
| 2,083
|
Python
|
.py
| 54
| 31.055556
| 85
| 0.686783
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,043
|
decorators.py
|
mdn_kuma/kuma/api/v1/decorators.py
|
from functools import wraps
from django.http import HttpResponseForbidden
from .auth import NotASubscriber, is_subscriber
def allow_CORS_GET(func):
"""Decorator to allow CORS for GET requests"""
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if "GET" == request.method:
response["Access-Control-Allow-Origin"] = "*"
return response
return inner
def require_subscriber(view_function):
"""Check if a user is authorized to retrieve a resource.
* Check if a user is logged in through kuma (django session).
* Check if there is a bearer token in the request header.
- Validate the token.
- Create a new user if there is not one
- Retrieve the resource for that user
"""
@wraps(view_function)
def is_authorized(request, *args, **kwargs):
try:
assert is_subscriber(request, raise_error=True)
except NotASubscriber as e:
return HttpResponseForbidden(e)
return view_function(request, *args, **kwargs)
return is_authorized
| 1,115
|
Python
|
.py
| 28
| 33.214286
| 65
| 0.679368
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,044
|
smarter_schema.py
|
mdn_kuma/kuma/api/v1/smarter_schema.py
|
"""
Since "Model" word would be very confusing when used in django context, this
module basically makes an alias for it named "Schema" and adds extra whistles to
be able to work with django querysets and managers.
The schema is a bit smarter than a standard pydantic Model because it can handle
dotted attributes and resolver methods. For example::
class UserSchema(User):
name: str
initials: str
boss: str = Field(None, alias="boss.first_name")
@staticmethod
def resolve_name(obj):
return f"{obj.first_name} {obj.last_name}"
def resolve_initials(self, obj):
return "".join(n[:1] for n in self.name.split())
"""
from inspect import getattr_static
from operator import attrgetter
from typing import Any, Type, TypeVar
import pydantic
from django.db.models import Manager, QuerySet
from django.db.models.fields.files import FieldFile
from pydantic import BaseModel, Field, validator
from pydantic.utils import GetterDict
pydantic_version = list(map(int, pydantic.VERSION.split(".")[:2]))
assert pydantic_version >= [1, 6], "Pydantic 1.6+ required"
__all__ = ["BaseModel", "Field", "validator", "DjangoGetter", "Schema"]
S = TypeVar("S", bound="Schema")
class DjangoGetter(GetterDict):
__slots__ = ("_obj", "_schema_cls")
def __init__(self, obj: Any, schema_cls: "Type[Schema]" = None):
self._obj = obj
self._schema_cls = schema_cls
def _fake_instance(self) -> "Schema":
"""
Generate a partial schema instance that can be used as the ``self``
attribute of resolver functions.
"""
getter_self = self
class PartialSchema(Schema):
def __getattr__(self, key: str) -> Any:
value = getter_self[key]
if getter_self._schema_cls:
field = getter_self._schema_cls.__fields__[key]
value = field.validate(value, values={}, loc=key, cls=None)[0]
return value
return PartialSchema()
def __getitem__(self, key: str) -> Any:
resolve_func = (
getattr_static(self._schema_cls, f"resolve_{key}", None)
if self._schema_cls
else None
)
if resolve_func and isinstance(resolve_func, staticmethod):
if not callable(resolve_func):
# Before Python 3.10, the staticmethod is not callable directly.
resolve_func = getattr(self._schema_cls, f"resolve_{key}")
item = resolve_func(self._obj)
elif resolve_func and callable(resolve_func):
item = resolve_func(self._fake_instance(), self._obj)
else:
try:
item = getattr(self._obj, key)
except AttributeError:
try:
item = attrgetter(key)(self._obj)
except AttributeError as e:
raise KeyError(key) from e
return self.format_result(item)
def get(self, key: Any, default: Any = None) -> Any:
try:
return self[key]
except KeyError:
return default
def format_result(self, result: Any) -> Any:
if isinstance(result, Manager):
return list(result.all())
elif isinstance(result, getattr(QuerySet, "__origin__", QuerySet)):
return list(result)
elif isinstance(result, FieldFile):
if not result:
return None
return result.url
return result
class Schema(BaseModel):
class Config:
orm_mode = True
getter_dict = DjangoGetter
@classmethod
def from_orm(cls: Type[S], obj: Any) -> S:
# DjangoGetter also needs the class so it can find resolver methods.
if not isinstance(obj, GetterDict):
getter_dict = cls.__config__.getter_dict
obj = (
getter_dict(obj, cls)
if issubclass(getter_dict, DjangoGetter)
else getter_dict(obj)
)
return super().from_orm(obj)
@classmethod
def _decompose_class(cls, obj: Any) -> GetterDict:
# This method has backported logic from Pydantic 1.9 and is no longer
# needed once that is the minimum version.
if isinstance(obj, GetterDict):
return obj
return super()._decompose_class(obj)
| 4,392
|
Python
|
.py
| 106
| 32.075472
| 82
| 0.610329
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,045
|
forms.py
|
mdn_kuma/kuma/api/v1/forms.py
|
from django import forms
from django.conf import settings
class AccountSettingsForm(forms.Form):
locale = forms.ChoiceField(
required=False,
# The `settings.LANGUAGES` looks like this:
# [('en-US', 'English (US)'), ...]
# But the valid choices actually come from Yari which is the only
# one that knows which ones are really valid.
# Here in kuma we can't enforce it as string. But at least we
# have a complete list of all possible languages
choices=[(code, name) for code, name in settings.LANGUAGES],
)
| 582
|
Python
|
.py
| 13
| 38.076923
| 73
| 0.66843
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,046
|
views.py
|
mdn_kuma/kuma/api/v1/views.py
|
from typing import Literal, Optional, Union
from django.conf import settings
from django.middleware.csrf import get_token
from ninja import Router, Schema
from kuma.api.v1.auth import profile_auth
from kuma.api.v1.forms import AccountSettingsForm
from kuma.api.v1.plus.notifications import Ok
from kuma.users.models import UserProfile
from .api import api
settings_router = Router(auth=profile_auth, tags=["settings"])
class AnonResponse(Schema):
geo: Optional[dict]
class AuthResponse(AnonResponse):
username: str
is_authenticated: bool = True
email: str
is_staff: Optional[bool]
is_superuser: Optional[bool]
avatar_url: Optional[str]
is_subscriber: Optional[bool]
subscription_type: Optional[str]
@api.get(
"/whoami",
auth=None,
exclude_none=True,
response=Union[AuthResponse, AnonResponse],
url_name="whoami",
)
def whoami(request):
"""
Return a JSON object representing the current user, either
authenticated or anonymous.
"""
data = {}
user = request.user
cloudfront_country_header = "HTTP_CLOUDFRONT_VIEWER_COUNTRY_NAME"
cloudfront_country_value = request.META.get(cloudfront_country_header)
if cloudfront_country_value:
data["geo"] = {"country": cloudfront_country_value}
if not user.is_authenticated:
return data
data["username"] = user.username
data["is_authenticated"] = True
data["email"] = user.email
if user.is_staff:
data["is_staff"] = True
if user.is_superuser:
data["is_superuser"] = True
profile = UserProfile.objects.filter(user=user).first()
if profile:
data["avatar_url"] = profile.avatar
data["is_subscriber"] = profile.is_subscriber
data["subscription_type"] = profile.subscription_type
return data
@settings_router.delete("/", url_name="settings")
def delete_user(request):
request.user.delete()
return {"deleted": True}
@settings_router.get("/", url_name="settings")
def account_settings(request):
user_profile: UserProfile = request.auth
return {
"csrfmiddlewaretoken": get_token(request),
"locale": user_profile.locale if user_profile.pk else None,
}
class FormErrors(Schema):
ok: Literal[False] = False
errors: dict[str, list[dict[str, str]]]
@settings_router.post("/", response={200: Ok, 400: FormErrors}, url_name="settings")
def save_settings(request):
user_profile: UserProfile = request.auth
form = AccountSettingsForm(request.POST)
if not form.is_valid():
return 400, {"errors": form.errors.get_json_data()}
set_locale = None
if form.cleaned_data.get("locale"):
user_profile.locale = form.cleaned_data["locale"]
user_profile.save()
response = api.create_response(request, Ok.from_orm(True))
response.set_cookie(
key=settings.LANGUAGE_COOKIE_NAME,
value=set_locale,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN,
secure=settings.LANGUAGE_COOKIE_SECURE,
)
return response
return True
| 3,187
|
Python
|
.py
| 89
| 30.258427
| 84
| 0.697364
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,047
|
bookmarks.py
|
mdn_kuma/kuma/api/v1/plus/bookmarks.py
|
from datetime import datetime
from typing import Optional, Union
from django.conf import settings
from django.db.models import Case, CharField, F, Q, When
from django.db.models.functions import Cast
from django.middleware.csrf import get_token
from django.utils import timezone
from ninja import Field, Form, Query, Router
from pydantic import validator
from kuma.api.v1.plus.notifications import NotOk
from kuma.api.v1.smarter_schema import Schema
from kuma.bookmarks.models import Bookmark
from kuma.documenturls.models import DocumentURL, download_url
from kuma.settings.common import MAX_NON_SUBSCRIBED
from kuma.users.models import UserProfile
class LimitOffsetInput(Schema):
limit: int = Field(20, gt=0)
offset: int = Field(0, ge=1)
class NotOKDocumentURLError(Exception):
"""When the document URL doesn't resolve as a 200 OK"""
router = Router(tags=["collection"])
class CollectionParent(Schema):
uri: str
title: str
class CollectionItemSchema(Schema):
id: int
url: str
title: str
notes: str
parents: list[CollectionParent]
created: datetime
@staticmethod
def resolve_url(bookmark):
return bookmark.documenturl.metadata["mdn_url"]
@staticmethod
def resolve_parents(bookmark):
return bookmark.documenturl.metadata.get("parents", [])[:-1]
class CollectionItemResponse(Schema):
bookmarked: Optional[CollectionItemSchema]
csrfmiddlewaretoken: str
subscription_limit_reached: Optional[bool]
class MultipleCollectionItemResponse(Schema):
items: list[CollectionItemSchema]
csrfmiddlewaretoken: str
subscription_limit_reached: Optional[bool]
class CollectionUpdateResponse(Schema):
subscription_limit_reached: Optional[bool]
ok: bool
class CollectionPaginatedInput(LimitOffsetInput):
url: str = None
terms: str = Field(None, alias="q")
sort: str = None
@validator("url")
def valid_bookmark_url(cls, url):
url = url.strip().replace("https://developer.mozilla.org", "")
assert (
url.startswith("/")
and ("/docs/" in url or "/plus/" in url)
and "://" not in url
), "invalid collection item url"
return url
@router.get(
"/",
response=Union[MultipleCollectionItemResponse, CollectionItemResponse],
summary="Get collection",
url_name="collections",
)
def bookmarks(request, filters: CollectionPaginatedInput = Query(...)):
"""
If `url` is passed, return that specific collection item, otherwise return
a paginated list of collection items.
"""
user = request.user
profile: UserProfile = request.auth
# Single bookmark request.
if filters.url:
bookmark: Optional[Bookmark] = user.bookmark_set.filter(
documenturl__uri=DocumentURL.normalize_uri(filters.url), deleted=None
).first()
response = {"bookmarked": bookmark, "csrfmiddlewaretoken": get_token(request)}
if not profile.is_subscriber:
response["subscription_limit_reached"] = (
user.bookmark_set.filter(deleted=None).count()
>= MAX_NON_SUBSCRIBED["collection"]
)
return response
# Otherwise return a paginated list of bookmarks.
qs = (
Bookmark.objects.filter(user_id=user.id, deleted__isnull=True)
.select_related("documenturl")
.order_by("-created")
)
if filters.sort == "title" or filters.terms:
qs = qs.annotate(
display_title=Case(
When(
custom_name="",
then=Cast("documenturl__metadata__title", CharField()),
),
default=F("custom_name"),
)
)
if filters.sort == "title":
qs = qs.order_by("display_title")
if filters.terms:
qs = qs.filter(
Q(display_title__icontains=filters.terms)
| Q(notes__icontains=filters.terms)
)
response = {}
response["csrfmiddlewaretoken"] = get_token(request)
qs = qs[filters.offset : filters.offset + filters.limit]
response["items"] = []
for item in qs:
response["items"].append(item)
if not profile.is_subscriber:
response["subscription_limit_reached"] = (
user.bookmark_set.filter(deleted=None).count()
>= MAX_NON_SUBSCRIBED["collection"]
)
return response
@router.post(
"/",
response={200: CollectionUpdateResponse, 201: CollectionUpdateResponse, 400: NotOk},
summary="Save or delete a collection item",
)
def save_or_delete_bookmark(
request,
url,
delete: bool = Form(None),
name: str = Form(None),
notes: str = Form(None),
):
absolute_url = f"{settings.BOOKMARKS_BASE_URL}{url}/index.json"
try:
documenturl = DocumentURL.objects.get(uri=DocumentURL.normalize_uri(url))
assert not documenturl.invalid
except DocumentURL.DoesNotExist:
response = download_url(absolute_url)
# Because it's so big, only store certain fields that are used.
full_metadata = response.json()["doc"]
metadata = {}
# Should we so day realize that we want to and need to store more
# about the remote Yari documents, we'd simply invoke some background
# processing job that forces a refresh.
for key in ("title", "mdn_url", "parents"):
if key in full_metadata:
metadata[key] = full_metadata[key]
documenturl = DocumentURL.objects.create(
uri=DocumentURL.normalize_uri(url),
absolute_url=absolute_url,
metadata=metadata,
)
bookmark: Optional[Bookmark] = request.user.bookmark_set.filter(
documenturl=documenturl
).first()
profile: UserProfile = request.auth
bookmark_count = request.user.bookmark_set.filter(deleted=None).count()
subscription_limit_reached = False
if delete:
if bookmark and not bookmark.deleted:
bookmark.deleted = timezone.now()
bookmark.save()
# Having deleted it's unlikely that the limit will still be reached but check anyway.
subscription_limit_reached = (bookmark_count - 1) >= MAX_NON_SUBSCRIBED[
"collection"
] and not profile.is_subscriber
return 200, {
"subscription_limit_reached": subscription_limit_reached,
"ok": True,
}
subscription_limit_reached = bookmark_count >= MAX_NON_SUBSCRIBED["collection"]
# Update logic
if bookmark and not bookmark.deleted:
if name is not None:
bookmark.custom_name = name[:500]
if notes is not None:
bookmark.notes = notes[:500]
bookmark.save()
return 201, {
"subscription_limit_reached": subscription_limit_reached
and not profile.is_subscriber,
"ok": True,
}
# Create or undelete. Check limits.
if not profile.is_subscriber and subscription_limit_reached:
return 400, {
"error": "max_subscriptions",
"info": {"max_allowed": MAX_NON_SUBSCRIBED["collection"]},
}
# If found undelete
if bookmark:
bookmark.deleted = None
else:
# Otherwise, create a brand new entry
bookmark = request.user.bookmark_set.create(documenturl=documenturl)
if name is not None:
bookmark.custom_name = name[:500]
if notes is not None:
bookmark.notes = notes[:500]
bookmark.save()
subscription_limit_reached = (
bookmark_count + 1 >= MAX_NON_SUBSCRIBED["collection"]
and not profile.is_subscriber
)
return 201, {"subscription_limit_reached": subscription_limit_reached, "ok": True}
| 7,783
|
Python
|
.py
| 206
| 30.436893
| 97
| 0.659411
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,048
|
landing_page.py
|
mdn_kuma/kuma/api/v1/plus/landing_page.py
|
from uuid import UUID
from django.middleware.csrf import get_token
from django.shortcuts import get_object_or_404
from ninja import Form, Router
from pydantic import Json
from ratelimit.decorators import ratelimit
from kuma.api.v1.plus.notifications import Ok
from kuma.plus.models import LandingPageSurvey
router = Router()
@router.post("/survey/", response=Ok, url_name="plus.landing_page.survey", auth=None)
@ratelimit(group="landing_page_survey", key="user_or_ip", rate="100/m", block=True)
def post_survey(request, uuid: str = Form(...), response: Json = Form(...)):
survey = get_object_or_404(LandingPageSurvey, uuid=uuid)
survey.response = response
survey.save()
return True
@router.get("/survey/", url_name="plus.landing_page.survey", auth=None)
@ratelimit(group="landing_page_survey", key="user_or_ip", rate="100/m", block=True)
def get_survey(request, uuid: UUID = None):
# Inspired by https://github.com/mdn/kuma/pull/7849/files
if uuid:
survey = get_object_or_404(LandingPageSurvey, uuid=uuid)
else:
geo_information = request.META.get("HTTP_CLOUDFRONT_VIEWER_COUNTRY_NAME") or ""
survey = LandingPageSurvey.objects.create(
geo_information=geo_information,
)
return {"uuid": survey.uuid, "csrfmiddlewaretoken": get_token(request)}
| 1,325
|
Python
|
.py
| 28
| 43.357143
| 87
| 0.732558
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,049
|
notifications.py
|
mdn_kuma/kuma/api/v1/plus/notifications.py
|
from __future__ import annotations
import datetime
import json
from typing import Optional
# import requests
import requests
from django.conf import settings
from django.db.models import Q
from django.middleware.csrf import get_token
from ninja import Field, Router
from ninja.pagination import paginate
from sentry_sdk import capture_exception
from kuma.documenturls.models import DocumentURL
from kuma.notifications.models import (
DefaultWatch,
Notification,
NotificationData,
UserWatch,
Watch,
)
from kuma.notifications.utils import process_changes
from kuma.settings.common import MAX_NON_SUBSCRIBED
from kuma.users.models import UserProfile
from ..pagination import LimitOffsetPaginatedResponse, LimitOffsetPaginationWithMeta
from ..smarter_schema import Schema
admin_router = Router(tags=["admin"])
notifications_router = Router(tags=["notifications"])
watch_router = Router(tags=["watch"])
limit_offset_paginate_with_meta = paginate(LimitOffsetPaginationWithMeta)
class Ok(Schema):
ok: bool = True
class WatchUpdateResponse(Schema):
ok: bool = True
subscription_limit_reached: bool = False
class NotOk(Schema):
ok: bool = False
error: str
info: dict = None
class NotificationSchema(Schema):
id: int
title: str = Field(..., alias="notification.title")
text: str = Field(..., alias="notification.text")
url: str = Field(..., alias="notification.page_url")
created: datetime.datetime = Field(..., alias="notification.created")
deleted: bool
read: bool
starred: bool
@notifications_router.get(
"/",
response=LimitOffsetPaginatedResponse[NotificationSchema],
url_name="plus.notifications",
)
@limit_offset_paginate_with_meta
def notifications(
request,
starred: bool = None,
unread: bool = None,
filterType: str = None,
q: str = None,
sort: str = None,
**kwargs,
):
qs = request.user.notification_set.select_related("notification")
if starred is not None:
qs = qs.filter(starred=starred)
if unread is not None:
qs = qs.filter(read=not unread)
if filterType:
qs = qs.filter(notification__type=filterType)
if q:
qs = qs.filter(
Q(notification__title__icontains=q) | Q(notification__text__icontains=q)
)
if sort == "title":
order_by = "notification__title"
else:
order_by = "-notification__created"
qs = qs.order_by(order_by, "id")
qs = qs.filter(deleted=False)
return qs
@notifications_router.post("/all/mark-as-read/", response=Ok)
def mark_all_as_read(request):
request.user.notification_set.filter(read=False).update(read=True)
return True
@notifications_router.post("/{int:pk}/mark-as-read/", response=Ok)
def mark_as_read(request, pk: int):
request.user.notification_set.filter(pk=pk, read=False).update(read=True)
return True
@notifications_router.post("/{int:pk}/toggle-starred/", response={200: Ok, 400: str})
def toggle_starred(request, pk: int):
try:
notification = Notification.objects.get(user=request.user, pk=pk)
except Notification.DoesNotExist:
return 400, "no matching notification"
notification.starred = not notification.starred
notification.save()
return 200, True
class StarMany(Schema):
ids: list[int]
@notifications_router.post(
"/star-ids/", response={200: Ok, 400: str}, url_name="notifications_star_ids"
)
def star_many(request, data: StarMany):
request.user.notification_set.filter(deleted=False).filter(pk__in=data.ids).update(
starred=True
)
return 200, True
@notifications_router.post(
"/unstar-ids/", response={200: Ok, 400: str}, url_name="notifications_unstar_ids"
)
def unstar_many(request, data: StarMany):
request.user.notification_set.filter(deleted=False).filter(pk__in=data.ids).update(
starred=False
)
return 200, True
@notifications_router.post(
"/{int:pk}/delete/", response=Ok, url_name="notifications_delete_id"
)
def delete_notification(request, pk: int):
request.user.notification_set.filter(id=pk).update(deleted=True)
return True
@notifications_router.post("/{int:pk}/undo-deletion/", response=Ok)
def undo_deletion(request, pk: int):
request.user.notification_set.filter(id=pk).update(deleted=False)
return True
class DeleteMany(Schema):
ids: list[int]
@notifications_router.post(
"/delete-ids/", response={200: Ok, 400: NotOk}, url_name="notifications_delete_many"
)
def delete_notifications(request, data: DeleteMany):
request.user.notification_set.filter(deleted=False).filter(pk__in=data.ids).update(
deleted=True
)
return 200, True
class WatchSchema(Schema):
title: str
url: str
path: str
@watch_router.get("/watching/", url_name="watching")
def watched(request, q: str = "", url: str = "", limit: int = 20, offset: int = 0):
qs = request.user.userwatch_set.select_related("watch", "user__defaultwatch")
profile: UserProfile = request.auth
hasDefault = None
try:
hasDefault = request.user.defaultwatch.custom_serialize()
except DefaultWatch.DoesNotExist:
pass
if url:
url = DocumentURL.normalize_uri(url)
qs = qs.filter(watch__url=url)
if q:
qs = qs.filter(watch__title__icontains=q)
qs = qs[offset : offset + limit]
response = {}
results = []
# Default settings at top level if exist
if hasDefault:
response["default"] = hasDefault
response["csrfmiddlewaretoken"] = get_token(request)
for item in qs:
res = {}
res["title"] = item.watch.title
res["url"] = item.watch.url
res["path"] = item.watch.path
# No custom notifications just major updates.
if not item.custom:
res["status"] = "major"
else:
res["status"] = "custom"
# Subscribed to custom
if item.custom_default and hasDefault:
# Subscribed to the defaults
res["custom"] = "default"
else:
# Subscribed to fine-grained options
res["custom"] = item.custom_serialize()
results.append(res)
if url != "" and len(results) == 0:
response["status"] = "unwatched"
elif len(results) == 1 and url != "":
response = response | results[0]
else:
response["items"] = results
if not profile.is_subscriber:
response["subscription_limit_reached"] = (
request.user.userwatch_set.count() >= MAX_NON_SUBSCRIBED["notification"]
)
return response
class UpdateWatchCustom(Schema):
compatibility: list[str]
content: bool
class UpdateWatch(Schema):
unwatch: bool = None
title: str = None
path: str = None
custom: UpdateWatchCustom = None
custom_default: bool = None
update_custom_default: bool = False
@watch_router.post(
"/watching/", response={200: WatchUpdateResponse, 400: NotOk, 400: NotOk}
)
def update_watch(request, url: str, data: UpdateWatch):
url = DocumentURL.normalize_uri(url)
profile: UserProfile = request.auth
watched: Optional[UserWatch] = (
request.user.userwatch_set.select_related("watch", "user__defaultwatch")
.filter(watch__url=url)
.first()
)
user = watched.user if watched else request.user
watched_count = request.user.userwatch_set.count()
subscription_limit_reached = watched_count >= MAX_NON_SUBSCRIBED["notification"]
if data.unwatch:
if watched:
watched.delete()
subscription_limit_reached = (watched_count - 1) >= MAX_NON_SUBSCRIBED[
"notification"
]
return 200, {
"subscription_limit_reached": subscription_limit_reached,
"ok": True,
}
title = data.title
if not title:
return 400, {"error": "missing title"}
path = data.path or ""
watched_data = {"custom": data.custom is not None}
if data.custom:
custom_default = bool(data.custom_default)
watched_data["custom_default"] = custom_default
custom_data = {
"content_updates": data.custom.content,
}
custom_data["browser_compatibility"] = sorted(data.custom.compatibility)
if custom_default:
try:
default_watch = user.defaultwatch
if data.update_custom_default:
for key, value in custom_data.items():
setattr(default_watch, key, value)
default_watch.save()
except DefaultWatch.DoesNotExist:
# Always create custom defaults if they are missing.
DefaultWatch.objects.update_or_create(user=user, defaults=custom_data)
watched_data.update(custom_data)
if watched:
watch: Watch = watched.watch
# Update the title / path if they changed.
if title != watch.title or path != watch.path:
watch.title = title
watch.path = path
watch.save()
else:
# Check on creation if allowed.
if (
watched_count >= MAX_NON_SUBSCRIBED["notification"]
and not profile.is_subscriber
):
return 400, {
"error": "max_subscriptions",
"info": {"max_allowed": MAX_NON_SUBSCRIBED["notification"]},
}
watch = Watch.objects.get_or_create(url=url, title=title, path=path)[0]
subscription_limit_reached = (watched_count + 1) >= MAX_NON_SUBSCRIBED[
"notification"
]
user.userwatch_set.update_or_create(watch=watch, defaults=watched_data)
return 200, {"subscription_limit_reached": subscription_limit_reached, "ok": True}
class UnwatchMany(Schema):
unwatch: list[str]
@watch_router.post(
"/unwatch-many/",
response={200: WatchUpdateResponse, 400: NotOk},
url_name="unwatch_many",
)
def unwatch(request, data: UnwatchMany):
request.user.userwatch_set.select_related("watch", "user__watch").filter(
watch__url__in=data.unwatch
).delete()
profile: UserProfile = request.auth
if profile.is_subscriber:
subscription_limit_reached = False
else:
subscription_limit_reached = (
request.user.userwatch_set.count() >= MAX_NON_SUBSCRIBED["notification"]
)
return 200, {"subscription_limit_reached": subscription_limit_reached, "ok": True}
class CreateNotificationSchema(Schema):
raw_url: str = Field(..., alias="page")
title: str
text: str
@admin_router.post("/create/", response={200: Ok, 400: NotOk})
def create(request, body: CreateNotificationSchema):
url = DocumentURL.normalize_uri(body.raw_url)
watchers = Watch.objects.filter(url=url)
if not watchers:
return 400, {"error": "No watchers found"}
notification_data, _ = NotificationData.objects.get_or_create(
text=body.text, title=body.title, type="content"
)
for watcher in watchers:
# considering the possibility of multiple pages existing for the same path
for user in watcher.users.all():
Notification.objects.create(notification=notification_data, user=user)
return True
class UpdateNotificationSchema(Schema):
filename: str
@admin_router.post("/update/", response={200: Ok, 400: NotOk, 401: NotOk})
def update(request, body: UpdateNotificationSchema):
try:
changes = json.loads(
requests.get(settings.NOTIFICATIONS_CHANGES_URL + body.filename).content
)
except Exception as e:
capture_exception(e)
return 400, {"error": f"Error while processing file: {repr(e)}"}
try:
process_changes(changes)
except Exception as e:
capture_exception(e)
return 400, {"ok": False, "error": f"Error while processing file: {repr(e)}"}
return 200, True
class ContentUpdateNotificationSchema(Schema):
raw_url: str = Field(..., alias="page")
pr_url: str = Field(..., alias="pr")
@admin_router.post(
"/update/content/",
response={200: Ok, 400: NotOk, 401: NotOk},
url_name="admin.update_content",
)
def update_content(request, body: ContentUpdateNotificationSchema):
try:
url = DocumentURL.normalize_uri(body.raw_url)
changes = [
{
"event": "content_updated",
"page_url": url,
"pr_url": body.pr_url,
}
]
process_changes(changes)
except Exception as e:
capture_exception(e)
return 400, {"error": f"Error while processing PR: {repr(e)}"}
return 200, True
| 12,696
|
Python
|
.py
| 346
| 30.231214
| 88
| 0.663515
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,050
|
test_notifications.py
|
mdn_kuma/kuma/api/v1/tests/test_notifications.py
|
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.urls import reverse
from model_bakery import baker
from kuma.notifications import models
def test_notifications_anonymous(client):
response = client.get(reverse("api-v1:plus.notifications"))
assert response.status_code == 401
def test_notifications(user_client, wiki_user):
url = reverse("api-v1:plus.notifications")
response = user_client.get(url)
assert response.status_code == 200
assert json.loads(response.content)["items"] == []
notification = baker.make(models.Notification, user=wiki_user)
response = user_client.get(url)
assert response.status_code == 200
assert json.loads(response.content)["items"] == [
{
"id": notification.pk,
"deleted": False,
"created": json.loads(
DjangoJSONEncoder().encode(notification.notification.created)
),
"title": notification.notification.title,
"text": notification.notification.text,
"read": notification.read,
"url": notification.notification.page_url,
"starred": notification.starred,
"deleted": False,
}
]
def test_notifications_only_yours(user_client, wiki_user):
notification = baker.make(models.Notification)
assert notification.user != wiki_user
url = reverse("api-v1:plus.notifications")
response = user_client.get(url)
assert response.status_code == 200
assert json.loads(response.content)["items"] == []
def test_notifications_paginations(user_client, wiki_user):
url = reverse("api-v1:plus.notifications")
response = user_client.get(url)
assert response.status_code == 200
assert json.loads(response.content)["items"] == []
for i in range(20):
baker.make(models.Notification, user=wiki_user, id=i)
response = user_client.get(url, {"limit": 10})
assert response.status_code == 200
items_json = json.loads(response.content)["items"]
assert len(items_json) == 10
for i, j in zip(range(0, 10), range(19, 10, -1)):
# id's descending by most recent (LIFO)
assert items_json[i]["id"] == j
# Test offset
response = user_client.get(url, {"limit": 10, "offset": 10})
items_json = json.loads(response.content)["items"]
for i, j in zip(range(0, 10), range(9, 0, -1)):
assert items_json[i]["id"] == j
def test_notifications_paginations_deletion(user_client, wiki_user):
url = reverse("api-v1:plus.notifications")
for i in range(15):
baker.make(models.Notification, user=wiki_user, id=i)
response = user_client.get(url, {"limit": 10})
assert response.status_code == 200
items_json = json.loads(response.content)["items"]
assert len(items_json) == 10
for i, j in zip(range(0, 10), range(14, 5, -1)):
# id's descending by most recent (LIFO)
assert items_json[i]["id"] == j
delete_url = reverse("api-v1:notifications_delete_id", kwargs={"pk": 5})
# Given item 5 is deleted.
user_client.post(delete_url)
response = user_client.get(url, {"limit": 10})
items_json = json.loads(response.content)["items"]
# Last item of new fetch should now be '4'
assert len(items_json) == 10
assert items_json[9]["id"] == 4
def test_notifications_delete_many(user_client, wiki_user):
url = reverse("api-v1:plus.notifications")
for i in range(15):
baker.make(models.Notification, user=wiki_user, id=i)
response = user_client.get(url, {"limit": 10})
assert response.status_code == 200
items_json = json.loads(response.content)["items"]
assert len(items_json) == 10
for i, j in zip(range(0, 10), range(14, 5, -1)):
# id's descending by most recent (LIFO)
assert items_json[i]["id"] == j
delete_many_url = reverse("api-v1:notifications_delete_many")
# Given 6 items are deleted.
response = user_client.post(
delete_many_url,
json.dumps({"ids": [14, 13, 12, 11, 10, 9]}),
content_type="application/json",
)
assert response.status_code == 200
# Refetch
response = user_client.get(url, {"limit": 10})
items_json = json.loads(response.content)["items"]
# Ensure ids deleted as expected
assert len(items_json) == 9
for i, j in zip(range(0, 9), range(8, 0, -1)):
# id's descending by most recent (LIFO)
assert items_json[i]["id"] == j
def test_star_many(user_client, wiki_user):
url = reverse("api-v1:plus.notifications")
for i in range(15):
baker.make(models.Notification, user=wiki_user, id=i, starred=False)
response = user_client.get(url, {"limit": 15})
assert response.status_code == 200
items_json = json.loads(response.content)["items"]
assert len(items_json) == 15
for i in range(0, 15):
assert not items_json[i]["starred"]
star_many_url = reverse("api-v1:notifications_star_ids")
# Star ids.
response = user_client.post(
star_many_url,
json.dumps({"ids": [14, 13, 12, 11, 10, 9]}),
content_type="application/json",
)
assert response.status_code == 200
# Refetch
response = user_client.get(url, {"limit": 15})
items_json = json.loads(response.content)["items"]
for i, j in zip(range(0, 5), range(14, 9, -1)):
# Top 6 are starred
assert items_json[i]["id"] == j
assert items_json[i]["starred"]
for i in range(6, 15):
# Bottom 9 are not starred
assert not items_json[i]["starred"]
def test_unstar_many(user_client, wiki_user):
url = reverse("api-v1:plus.notifications")
# Create 15 starred notifications
ids = []
for i in range(15):
ids.append(i)
baker.make(models.Notification, user=wiki_user, id=i, starred=True)
response = user_client.get(url, {"limit": 15})
assert response.status_code == 200
items_json = json.loads(response.content)["items"]
assert len(items_json) == 15
for i in range(0, 15):
assert items_json[i]["starred"]
unstar_many_url = reverse("api-v1:notifications_unstar_ids")
# Unstar all ids
response = user_client.post(
unstar_many_url,
json.dumps({"ids": ids}),
content_type="application/json",
)
assert response.status_code == 200
# Refetch
response = user_client.get(url, {"limit": 15})
items_json = json.loads(response.content)["items"]
for i in range(15):
assert not items_json[i]["starred"]
| 6,560
|
Python
|
.py
| 157
| 35.394904
| 77
| 0.647697
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,051
|
test_search.py
|
mdn_kuma/kuma/api/v1/tests/test_search.py
|
from unittest.mock import patch
import pytest
from elasticmock import FakeElasticsearch
from kuma.core.urlresolvers import reverse
@pytest.mark.django_db
def test_search_validation_problems(user_client, settings):
url = reverse("api.v1.search")
# locale invalid
response = user_client.get(url, {"q": "x", "locale": "xxx"})
assert response.status_code == 400
assert response.json()["errors"]["locale"][0]["code"] == "invalid_choice"
# all non-200 OK responses should NOT have a Cache-Control header set.
assert "cache-control" not in response
# 'q' exceeds max allowed characters
response = user_client.get(url, {"q": "x" * (settings.ES_Q_MAXLENGTH + 1)})
assert response.status_code == 400
assert response.json()["errors"]["q"][0]["code"] == "max_length"
# 'q' is empty or missing
response = user_client.get(url, {"q": ""})
assert response.status_code == 400
assert response.json()["errors"]["q"][0]["code"] == "required"
response = user_client.get(url)
assert response.status_code == 400
assert response.json()["errors"]["q"][0]["code"] == "required"
# 'page' is not a valid number
response = user_client.get(url, {"q": "x", "page": "x"})
assert response.status_code == 400
assert response.json()["errors"]["page"][0]["code"] == "invalid"
response = user_client.get(url, {"q": "x", "page": "-1"})
assert response.status_code == 400
assert response.json()["errors"]["page"][0]["code"] == "min_value"
# 'sort' not a valid value
response = user_client.get(url, {"q": "x", "sort": "neverheardof"})
assert response.status_code == 400
assert response.json()["errors"]["sort"][0]["code"] == "invalid_choice"
# 'slug_prefix' has to be anything but empty
response = user_client.get(url, {"q": "x", "slug_prefix": ""})
assert response.status_code == 400
assert response.json()["errors"]["slug_prefix"][0]["code"] == "invalid_choice"
class FindEverythingFakeElasticsearch(FakeElasticsearch):
def search(self, *args, **kwargs):
# This trick is what makes the mock so basic. It basically removes
# any search query so that it just returns EVERYTHING that's been indexed.
kwargs.pop("body", None)
result = super().search(*args, **kwargs)
# Due to a bug in ElasticMock, instead of returning an object for the
# `response.hits.total`, it returns just an integer. We'll need to fix that.
if isinstance(result["hits"]["total"], int):
result["hits"]["total"] = {
"value": result["hits"]["total"],
"relation": "eq",
}
return result
@pytest.fixture
def mock_elasticsearch():
fake_elasticsearch = FindEverythingFakeElasticsearch()
with patch("elasticsearch_dsl.search.get_connection") as get_connection:
get_connection.return_value = fake_elasticsearch
yield fake_elasticsearch
def test_search_basic_match(user_client, settings, mock_elasticsearch):
mock_elasticsearch.index(
settings.SEARCH_INDEX_NAME,
{
"id": "/en-us/docs/Foo",
"title": "Foo Title",
"summary": "Foo summary",
"locale": "en-us",
"slug": "Foo",
"popularity": 0,
},
id="/en-us/docs/Foo",
)
url = reverse("api.v1.search")
response = user_client.get(url, {"q": "foo bar"})
assert response.status_code == 200
assert "public" in response["Cache-Control"]
assert "max-age=" in response["Cache-Control"]
assert "max-age=0" not in response["Cache-Control"]
assert response["content-type"] == "application/json"
assert response["Access-Control-Allow-Origin"] == "*"
data = response.json()
assert data["metadata"]["page"] == 1
assert data["metadata"]["size"]
assert data["metadata"]["took_ms"]
assert data["metadata"]["total"]["value"] == 1
assert data["metadata"]["total"]["relation"] == "eq"
assert data["suggestions"] == []
assert data["documents"] == [
{
"highlight": {"body": [], "title": []},
"locale": "en-us",
"mdn_url": "/en-us/docs/Foo",
"popularity": 0,
"score": 1.0,
"slug": "Foo",
"title": "Foo Title",
"summary": "Foo summary",
}
]
| 4,372
|
Python
|
.py
| 99
| 37.212121
| 84
| 0.614427
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,052
|
test_watched_items.py
|
mdn_kuma/kuma/api/v1/tests/test_watched_items.py
|
import json
from django.urls import reverse
from model_bakery import baker
from kuma.notifications import models
def test_unwatch_manys(user_client, wiki_user):
url = reverse("api-v1:watching")
user_watched_items = []
for i in range(10):
mock_watch = baker.make(models.Watch, users=[wiki_user])
user_watch = baker.make(
models.UserWatch, user=wiki_user, id=i, watch=mock_watch
)
user_watched_items.append(user_watch)
response = user_client.get(url, {"limit": 10})
assert response.status_code == 200
items_json = json.loads(response.content)["items"]
assert len(items_json) == 10
unwatch_many_url = reverse("api-v1:unwatch_many")
# Given 6 items are deleted.
del1 = user_watched_items[0].watch.url
del2 = user_watched_items[1].watch.url
response = user_client.post(
unwatch_many_url,
json.dumps(
{
"unwatch": [
del1,
del2,
]
}
),
content_type="application/json",
)
assert response.status_code == 200
# Refetch
response = user_client.get(url, {"limit": 10})
items_json = json.loads(response.content)["items"]
filtered = filter(
lambda item: item["url"] == del1 or item["url"] == del2, items_json
)
# Assert deleted no longer there :)
assert len(list(filtered)) == 0
| 1,436
|
Python
|
.py
| 42
| 26.714286
| 75
| 0.61039
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,053
|
test_landing_page.py
|
mdn_kuma/kuma/api/v1/tests/test_landing_page.py
|
import pytest
from kuma.core.urlresolvers import reverse
from kuma.plus.models import LandingPageSurvey
@pytest.mark.django_db
def test_ping_landing_page_survey_bad_request(client):
url = reverse("api-v1:plus.landing_page.survey")
# Not a valid UUID
response = client.get(url, {"uuid": "xxx"})
assert response.status_code == 422
# Not a recognized UUID
response = client.get(url, {"uuid": "88f7a689-454a-4647-99bf-d62fa66da24a"})
assert response.status_code == 404
# No UUID in post
response = client.post(url)
assert response.status_code == 422
response = client.get(url, {"variant": "1"})
assert response.status_code == 200
# Invalid JSON
response = client.post(url, {"uuid": response.json()["uuid"], "response": "{{{{"})
assert response.status_code == 422
@pytest.mark.django_db
def test_ping_landing_page_survey_reuse_uuid(client):
url = reverse("api-v1:plus.landing_page.survey")
response1 = client.get(url, HTTP_CLOUDFRONT_VIEWER_COUNTRY_NAME="Sweden")
assert response1.status_code == 200
assert LandingPageSurvey.objects.all().count() == 1
response2 = client.get(
url,
{"uuid": response1.json()["uuid"]},
HTTP_CLOUDFRONT_VIEWER_COUNTRY_NAME="USA",
)
assert response2.json()["uuid"] == response1.json()["uuid"]
assert LandingPageSurvey.objects.all().count() == 1
| 1,394
|
Python
|
.py
| 33
| 37.454545
| 86
| 0.691568
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,054
|
test_forms.py
|
mdn_kuma/kuma/api/v1/tests/test_forms.py
|
from django.test import RequestFactory
from kuma.api.v1.search.forms import SearchForm
def test_search_form_locale_happy_path():
"""The way the form handles 'locale' is a bit overly complicated.
These unit tests focuses exclusively on that and when the form is valid."""
initial = {"page": 1, "size": 10}
request = RequestFactory().get("/api/v1/search?q=foo")
form = SearchForm(request.GET, initial=initial)
assert form.is_valid()
assert form.cleaned_data["locale"] == []
request = RequestFactory().get("/api/v1/search?q=foo")
initial["locale"] = "ja"
form = SearchForm(request.GET, initial=initial)
assert form.is_valid()
assert form.cleaned_data["locale"] == ["ja"]
request = RequestFactory().get("/api/v1/search?q=foo&locale=Fr")
form = SearchForm(request.GET, initial=initial)
assert form.is_valid()
assert form.cleaned_data["locale"] == ["Fr"]
request = RequestFactory().get("/api/v1/search?q=foo&locale=Fr&locale=de")
form = SearchForm(request.GET, initial=initial)
assert form.is_valid()
assert form.cleaned_data["locale"] == ["Fr", "de"]
# Note, same as the initial default
request = RequestFactory().get("/api/v1/search?q=foo&locale=ja")
form = SearchForm(request.GET, initial=initial)
assert form.is_valid()
assert form.cleaned_data["locale"] == ["ja"]
request = RequestFactory().get("/api/v1/search?q=foo&locale=ja&locale=fr")
form = SearchForm(request.GET, initial=initial)
assert form.is_valid()
assert form.cleaned_data["locale"] == ["ja", "fr"]
def test_search_form_locale_validation_error():
"""The way the form handles 'locale' is a bit overly complicated.
These unit tests focuses exclusively on that and when the form is NOT valid."""
initial = {"page": 1, "size": 10}
request = RequestFactory().get("/api/v1/search?q=foo&locale=xxx")
form = SearchForm(request.GET, initial=initial)
assert not form.is_valid()
assert form.errors["locale"]
request = RequestFactory().get("/api/v1/search?q=foo&locale=")
form = SearchForm(request.GET, initial=initial)
assert not form.is_valid()
assert form.errors["locale"]
| 2,198
|
Python
|
.py
| 44
| 45.022727
| 83
| 0.6922
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,055
|
test_bookmarks.py
|
mdn_kuma/kuma/api/v1/tests/test_bookmarks.py
|
import copy
from urllib.parse import urlencode
import pytest
from kuma.core.urlresolvers import reverse
from kuma.users.models import UserProfile
@pytest.mark.django_db
def test_bookmarked_anonymous(client):
response = client.get(reverse("api-v1:collections"))
assert response.status_code == 401
assert "Unauthorized" in response.content.decode("utf-8")
@pytest.mark.django_db
def test_is_bookmarked_signed_in(user_client, wiki_user):
url = reverse("api-v1:collections")
response = user_client.get(url)
assert response.status_code == 200
UserProfile.objects.create(user=wiki_user)
response = user_client.get(url)
assert response.status_code == 200
@pytest.mark.django_db
def test_is_bookmarked_signed_in_subscriber(subscriber_client):
url = reverse("api-v1:collections")
response = subscriber_client.get(url, {"url": "some junk"})
assert response.status_code == 422
assert "invalid collection item url" in response.content.decode("utf-8")
response = subscriber_client.get(url, {"url": "/not/a/mdny/url"})
assert response.status_code == 422
assert "invalid collection item url" in response.content.decode("utf-8")
response = subscriber_client.get(url, {"url": "/docs/://ftphack"})
assert response.status_code == 422
assert "invalid collection item url" in response.content.decode("utf-8")
response = subscriber_client.get(url, {"url": "/en-US/docs/Web"})
assert response.status_code == 200
# It's NOT been toggled yet
assert response.json()["bookmarked"] is None
assert response.json()["csrfmiddlewaretoken"]
@pytest.mark.django_db
def test_toggle_bookmarked(subscriber_client, mock_requests, settings):
doc_data = {"doc": {"title": "Web", "mdn_url": "/en-US/docs/Web"}}
mock_requests.register_uri(
"GET", settings.BOOKMARKS_BASE_URL + "/en-US/docs/Web/index.json", json=doc_data
)
url = reverse("api-v1:collections")
get_url = f'{url}?{urlencode({"url": "/en-US/docs/Web"})}'
response = subscriber_client.post(get_url)
assert response.status_code == 201
response = subscriber_client.get(get_url)
assert response.status_code == 200
assert response.json()["bookmarked"]["id"]
initial_id = response.json()["bookmarked"]["id"]
assert response.json()["bookmarked"]["created"]
assert response.json()["csrfmiddlewaretoken"]
# Now toggle it off
response = subscriber_client.post(get_url)
assert response.status_code == 201
# Soft deleted
response = subscriber_client.post(get_url, {"delete": True})
assert response.status_code == 200
assert response.json()["ok"]
# Not in response
response = subscriber_client.get(get_url)
assert response.status_code == 200
assert not response.json()["bookmarked"]
# And undo the soft-delete
response = subscriber_client.post(get_url)
assert response.status_code == 201
# Should return with the same ID as before
response = subscriber_client.get(get_url)
assert response.status_code == 200
response = subscriber_client.get(get_url)
assert response.status_code == 200
assert response.json()["bookmarked"]["id"] == initial_id
# Case sensitive too
response = subscriber_client.get(get_url.replace("en-US", "EN-us"))
assert response.status_code == 200
assert response.json()["bookmarked"]
@pytest.mark.django_db
def test_bookmarks_anonymous(client):
response = client.get(reverse("api-v1:collections"))
assert response.status_code == 401
assert "Unauthorized" in response.content.decode("utf-8")
@pytest.mark.django_db
def test_bookmarks_signed_in_subscriber(subscriber_client):
url = reverse("api-v1:collections")
response = subscriber_client.get(url)
assert response.status_code == 200
assert len(response.json()["items"]) == 0
# Try to mess with the `page` and `per_page`
response = subscriber_client.get(url, {"offset": "xxx"})
assert response.status_code == 422
assert "type_error.integer" in response.content.decode("utf-8")
response = subscriber_client.get(url, {"limit": "-1"})
assert response.status_code == 422
assert "value_error.number.not_gt" in response.content.decode("utf-8")
@pytest.mark.django_db
def test_bookmarks_pagination(subscriber_client, mock_requests, settings):
base_doc_data = {
"doc": {
"body": "BIG",
"toc": "BIG",
"sidebarHTML": "BIG",
"other_translations": ["BIG"],
"flaws": {"also": "BIG"},
"mdn_url": "/en-US/docs/Web/Doc0",
"title": "Document 0",
"locale": "en-US",
"parents": [
{"uri": "/en-US/docs/Web", "title": "Web"},
{"uri": "/en-US/docs/Web/Doc0", "title": "Document 0"},
],
}
}
def create_doc_data(mdn_url, title):
clone = copy.deepcopy(base_doc_data)
clone["doc"]["title"] = title
clone["doc"]["mdn_url"] = mdn_url
clone["doc"]["parents"][-1]["title"] = title
clone["doc"]["parents"][-1]["uri"] = mdn_url
return clone
url = reverse("api-v1:collections")
for i in range(1, 21):
mdn_url = f"/en-US/docs/Web/Doc{i}"
doc_absolute_url = settings.BOOKMARKS_BASE_URL + mdn_url + "/index.json"
print(doc_absolute_url)
mock_requests.register_uri(
"GET", doc_absolute_url, json=create_doc_data(mdn_url, f"Doc {i}")
)
get_url = f'{url}?{urlencode({"url": mdn_url})}'
print(get_url)
response = subscriber_client.post(get_url)
print(response)
assert response.status_code == 201, response.json()
# Add one extra but then delete it
i += 1
mdn_url = f"/en-US/docs/Web/Doc{i}"
doc_absolute_url = settings.BOOKMARKS_BASE_URL + mdn_url + "/index.json"
mock_requests.register_uri(
"GET", doc_absolute_url, json=create_doc_data(mdn_url, f"Doc {i}")
)
get_url = f'{url}?{urlencode({"url": mdn_url})}'
response = subscriber_client.post(get_url)
assert response.status_code == 201
response = subscriber_client.post(get_url, {"delete": 1})
assert response.status_code == 200
response = subscriber_client.get(url, {"limit": "5"})
assert response.status_code == 200
assert len(response.json()["items"]) == 5
response = subscriber_client.get(url, {"limit": "5", "offset": "5"})
assert response.status_code == 200
assert len(response.json()["items"]) == 5
def test_undo_bookmark(subscriber_client, mock_requests, settings):
def create_doc_data(mdn_url, title):
base_doc_data = {
"doc": {
"body": "BIG",
"toc": "BIG",
"sidebarHTML": "BIG",
"other_translations": ["BIG"],
"flaws": {"also": "BIG"},
"mdn_url": "/en-US/docs/Web/Doc0",
"title": "Document 0",
"locale": "en-US",
"parents": [
{"uri": "/en-US/docs/Web", "title": "Web"},
{"uri": "/en-US/docs/Web/Doc0", "title": "Document 0"},
],
}
}
clone = copy.deepcopy(base_doc_data)
clone["doc"]["title"] = title
clone["doc"]["mdn_url"] = mdn_url
clone["doc"]["parents"][-1]["title"] = title
clone["doc"]["parents"][-1]["uri"] = mdn_url
return clone
mock_requests.register_uri(
"GET",
settings.BOOKMARKS_BASE_URL + "/en-US/docs/Foo/index.json",
json=create_doc_data("/en-US/docs/Foo", "Foo!"),
)
mock_requests.register_uri(
"GET",
settings.BOOKMARKS_BASE_URL + "/en-US/docs/Bar/index.json",
json=create_doc_data("/en-US/docs/Bar", "Bar!"),
)
mock_requests.register_uri(
"GET",
settings.BOOKMARKS_BASE_URL + "/en-US/docs/Buzz/index.json",
json=create_doc_data("/en-US/docs/Buzz", "Buzz!"),
)
url = reverse("api-v1:collections")
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Foo"})}'
).status_code
== 201
)
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Bar"})}'
).status_code
== 201
)
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Buzz"})}'
).status_code
== 201
)
response = subscriber_client.get(url)
assert response.status_code == 200
items = response.json()["items"]
assert len(items) == 3
assert [x["url"] for x in items] == [
# The one that was bookmarked last
"/en-US/docs/Buzz",
# The one that was bookmarked second
"/en-US/docs/Bar",
# The one that was bookmarked first
"/en-US/docs/Foo",
]
# Suppose you decide to un-bookmark the first one.
response = subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Foo"})}', {"delete": True}
)
assert response.status_code == 200
# Check that it disappears from the listing
response = subscriber_client.get(url)
assert response.status_code == 200
items = response.json()["items"]
assert len(items) == 2
# And let's pretend we change our mind and undo that. Which is basically
# to toggle it again.
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Foo"})}'
).status_code
== 201
)
# Because it became an undo, it should not have moved this untoggle into
# the first spot.
response = subscriber_client.get(url)
assert response.status_code == 200
items = response.json()["items"]
assert len(items) == 3
assert [x["url"] for x in items] == [
"/en-US/docs/Buzz",
"/en-US/docs/Bar",
# Note! Even though this was the latest to be bookmarked, it's still
# in its original (third) place. It's because the bookmarking of it
# was considered an "undo".
"/en-US/docs/Foo",
]
# This time, un-bookmark two but re-bookmark them in the wrong order.
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Buzz"})}', {"delete": True}
).status_code
== 200
)
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Bar"})}', {"delete": True}
).status_code
== 200
)
# The last one to be touched was "Bar", let's now bookmark them back
# but this time, do it in the opposite order.
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Buzz"})}'
).status_code
== 201
)
assert (
subscriber_client.post(
f'{url}?{urlencode({"url": "/en-US/docs/Bar"})}'
).status_code
== 201
)
response = subscriber_client.get(url)
assert response.status_code == 200
items = response.json()["items"]
assert len(items) == 3
assert [x["url"] for x in items] == [
# Note the the order of these two is the same. Because we only care about the creation
# order, not the deletion time.
"/en-US/docs/Buzz",
"/en-US/docs/Bar",
"/en-US/docs/Foo",
]
| 11,384
|
Python
|
.py
| 289
| 32.211073
| 94
| 0.610502
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,056
|
test_views.py
|
mdn_kuma/kuma/api/v1/tests/test_views.py
|
import pytest
from django.contrib.auth.models import User
from kuma.core.tests import assert_no_cache_header
from kuma.core.urlresolvers import reverse
@pytest.mark.parametrize("http_method", ["put", "post", "delete", "options", "head"])
def test_whoami_disallowed_methods(client, http_method):
"""HTTP methods other than GET are not allowed."""
url = reverse("api-v1:whoami")
response = getattr(client, http_method)(url)
assert response.status_code == 405
@pytest.mark.django_db
def test_whoami_anonymous(client):
"""Test response for anonymous users."""
url = reverse("api-v1:whoami")
response = client.get(url)
assert response.status_code == 200
assert response["content-type"] == "application/json; charset=utf-8"
assert response.json() == {}
assert_no_cache_header(response)
@pytest.mark.django_db
def test_whoami_anonymous_cloudfront_geo(client):
"""Test response for anonymous users."""
url = reverse("api-v1:whoami")
response = client.get(url, HTTP_CLOUDFRONT_VIEWER_COUNTRY_NAME="US of A")
assert response.status_code == 200
assert response["content-type"] == "application/json; charset=utf-8"
assert response.json()["geo"] == {"country": "US of A"}
@pytest.mark.django_db
@pytest.mark.parametrize(
"is_staff,is_superuser",
[(False, False), (True, True)],
ids=("muggle", "wizard"),
)
def test_whoami(
user_client,
wiki_user,
is_staff,
is_superuser,
):
"""Test responses for logged-in users."""
wiki_user.is_staff = is_staff
wiki_user.is_superuser = is_superuser
wiki_user.is_staff = is_staff
wiki_user.save()
url = reverse("api-v1:whoami")
response = user_client.get(url)
assert response.status_code == 200
assert response["content-type"] == "application/json; charset=utf-8"
expect = {
"username": wiki_user.username,
"is_authenticated": True,
"email": "wiki_user@example.com",
}
if is_staff:
expect["is_staff"] = True
if is_superuser:
expect["is_superuser"] = True
assert response.json() == expect
assert_no_cache_header(response)
@pytest.mark.django_db
def test_account_settings_auth(client):
url = reverse("api-v1:settings")
response = client.get(url)
assert response.status_code == 401
response = client.delete(url)
assert response.status_code == 401
response = client.post(url, {})
assert response.status_code == 401
def test_account_settings_delete(user_client, wiki_user):
username = wiki_user.username
response = user_client.delete(reverse("api-v1:settings"))
assert response.status_code == 200
assert not User.objects.filter(username=username).exists()
def test_get_and_set_settings_happy_path(user_client):
url = reverse("api-v1:settings")
response = user_client.get(url)
assert response.status_code == 200
assert_no_cache_header(response)
assert response.json()["locale"] is None
response = user_client.post(url, {"locale": "zh-CN"})
assert response.status_code == 200
response = user_client.post(url, {"locale": "fr"})
assert response.status_code == 200
response = user_client.get(url)
assert response.status_code == 200
assert response.json()["locale"] == "fr"
# You can also omit certain things and things won't be set
response = user_client.post(url, {})
assert response.status_code == 200
response = user_client.get(url)
assert response.status_code == 200
assert response.json()["locale"] == "fr"
def test_set_settings_validation_errors(user_client):
url = reverse("api-v1:settings")
response = user_client.post(url, {"locale": "never heard of"})
assert response.status_code == 400
assert response.json()["errors"]["locale"][0]["code"] == "invalid_choice"
assert response.json()["errors"]["locale"][0]["message"]
| 3,893
|
Python
|
.py
| 98
| 35.112245
| 85
| 0.688842
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,057
|
test_subscriptions.py
|
mdn_kuma/kuma/api/v1/tests/test_subscriptions.py
|
import json
import pytest
from django.urls import reverse
from kuma.users import models
@pytest.mark.django_db
def test_subscriptions(subscriber_client, wiki_user):
response = subscriber_client.get(reverse("api-v1:whoami"))
assert response.status_code == 200
assert json.loads(response.content) == {
"username": wiki_user.username,
"is_authenticated": True,
"email": wiki_user.email,
"is_subscriber": True,
"subscription_type": "",
"avatar_url": "",
}
# Add Subscription and save model back to db
profile = models.UserProfile.objects.get(user=wiki_user)
profile.subscription_type = models.UserProfile.SubscriptionType.MDN_PLUS_10Y
profile.is_subscriber = True
profile.save()
# Assert subscription type present in response
response = subscriber_client.get(reverse("api-v1:whoami"))
assert response.status_code == 200
assert json.loads(response.content) == {
"username": wiki_user.username,
"is_authenticated": True,
"email": wiki_user.email,
"is_subscriber": True,
"subscription_type": models.UserProfile.SubscriptionType.MDN_PLUS_10Y.value,
"avatar_url": "",
}
| 1,219
|
Python
|
.py
| 32
| 32.15625
| 84
| 0.687553
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,058
|
__init__.py
|
mdn_kuma/kuma/api/v1/search/__init__.py
|
from django import http
from django.conf import settings
from django.utils.cache import patch_cache_control
from elasticsearch import exceptions
from elasticsearch_dsl import Q, Search, query
from redo import retrying
from kuma.api.v1.decorators import allow_CORS_GET
from .forms import SearchForm
# This is the number of seconds to be put into the Cache-Control max-age header
# if the search is successful.
# We can increase the number as we feel more and more comfortable with how
# the `/api/v1/search` works.
SEARCH_CACHE_CONTROL_MAX_AGE = 60 * 60 * 12
class JsonResponse(http.JsonResponse):
"""The only reason this exists is so that other Django views can call
views that return instances of this and then get to the data before it
gets JSON serialized.
This is something that rest_framework's JsonResponse supports.
Ultimately, the only view that cares is the (old) Kuma search view page
that calls the view function here in this file. Now it can do something like:
response = kuma.api.v1.search.search(request)
found = response.data
"""
def __init__(self, data, *args, **kwargs):
self.data = data
super().__init__(data, *args, **kwargs)
@allow_CORS_GET
def search(request, locale=None):
initial = {"size": 10, "page": 1}
if locale:
initial["locale"] = locale
form = SearchForm(request.GET, initial=initial)
if not form.is_valid():
return JsonResponse({"errors": form.errors.get_json_data()}, status=400)
locales = form.cleaned_data["locale"] or [settings.LANGUAGE_CODE]
assert isinstance(locales, list)
params = {
"locales": [x.lower() for x in locales],
"query": form.cleaned_data["q"],
"size": form.cleaned_data["size"],
"page": form.cleaned_data["page"],
"sort": form.cleaned_data["sort"],
# The `slug` is always stored, as a Keyword index, in lowercase.
"slug_prefixes": [x.lower() for x in form.cleaned_data["slug_prefix"]],
}
# By default, assume that we will try to make suggestions.
make_suggestions = True
if len(params["query"]) > 100 or max(len(x) for x in params["query"].split()) > 30:
# For example, if it's a really long query, or a specific word is just too
# long, you can get those tricky
# TransportError(500, 'search_phase_execution_exception', 'Term too complex:
# errors which are hard to prevent against.
make_suggestions = False
results = _find(
params,
make_suggestions=make_suggestions,
)
response = JsonResponse(results)
# The reason for caching is that most of the time, the searches people make
# are short and often stand a high chance of being reused by other users
# in the CDN.
# The worst that can happen is that we fill up the CDN with cached responses
# that end up being stored there and never reused by another user.
# We could consider only bothering with this based on looking at the parameters.
# For example, if someone made a search with "complex parameters" we could skip
# cache-control because it'll just be a waste to store it (CDN and client).
# The reason for not using a "shared" cache-control, i.e. `s-max-age` is
# because the cache-control seconds we intend to set are appropriate for both
# the client and the CDN. If the value set is 3600 seconds, that means that
# clients might potentially re-use their own browser cache if they trigger
# a repeated search. And it's an appropriate number for the CDN too.
# For more info about how our search patterns behave,
# see https://github.com/mdn/kuma/issues/7799
patch_cache_control(response, public=True, max_age=SEARCH_CACHE_CONTROL_MAX_AGE)
return response
def _find(params, total_only=False, make_suggestions=False, min_suggestion_score=0.8):
search_query = Search(
index=settings.SEARCH_INDEX_NAME,
)
if make_suggestions:
# XXX research if it it's better to use phrase suggesters and if
# that works
# https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html#phrase-suggester
search_query = search_query.suggest(
"title_suggestions", params["query"], term={"field": "title"}
)
search_query = search_query.suggest(
"body_suggestions", params["query"], term={"field": "body"}
)
# The business logic here that we search for things different ways,
# and each different way as a different boost which dictates its importance.
# The importance order is as follows:
#
# 1. Title match-phrase
# 2. Title match
# 3. Body match-phrase
# 4. Body match
#
# The order is determined by the `boost` number in the code below.
# Remember that sort order is a combination of "match" and popularity, but
# ideally the popularity should complement. Try to get a pretty good
# sort by pure relevance first, and let popularity just make it better.
#
sub_queries = []
sub_queries.append(Q("match", title={"query": params["query"], "boost": 5.0}))
sub_queries.append(Q("match", body={"query": params["query"], "boost": 1.0}))
if " " in params["query"]:
sub_queries.append(
Q("match_phrase", title={"query": params["query"], "boost": 10.0})
)
sub_queries.append(
Q("match_phrase", body={"query": params["query"], "boost": 2.0})
)
sub_query = query.Bool(should=sub_queries)
if params["locales"]:
search_query = search_query.filter("terms", locale=params["locales"])
if params["slug_prefixes"]:
sub_queries = [Q("prefix", slug=x) for x in params["slug_prefixes"]]
search_query = search_query.query(query.Bool(should=sub_queries))
search_query = search_query.highlight_options(
pre_tags=["<mark>"],
post_tags=["</mark>"],
number_of_fragments=3,
fragment_size=120,
encoder="html",
)
search_query = search_query.highlight("title", "body")
if params["sort"] == "relevance":
search_query = search_query.sort("_score", "-popularity")
search_query = search_query.query(sub_query)
elif params["sort"] == "popularity":
search_query = search_query.sort("-popularity", "_score")
search_query = search_query.query(sub_query)
else:
popularity_factor = 10.0
boost_mode = "sum"
score_mode = "max"
search_query = search_query.query(
"function_score",
query=sub_query,
functions=[
query.SF(
"field_value_factor",
field="popularity",
factor=popularity_factor,
missing=0.0,
)
],
boost_mode=boost_mode,
score_mode=score_mode,
)
search_query = search_query.source(excludes=["body"])
search_query = search_query[
params["size"] * (params["page"] - 1) : params["size"] * params["page"]
]
retry_options = {
"retry_exceptions": (
# This is the standard operational exception.
exceptions.ConnectionError,
# This can happen if the search happened right as the index had
# just been deleted due to a fresh re-indexing happening in Yari.
exceptions.NotFoundError,
# This can happen when the index simply isn't ready yet.
exceptions.TransportError,
),
# The default in redo is 60 seconds. Let's tone that down.
"sleeptime": settings.ES_RETRY_SLEEPTIME,
"attempts": settings.ES_RETRY_ATTEMPTS,
"jitter": settings.ES_RETRY_JITTER,
}
with retrying(search_query.execute, **retry_options) as retrying_function:
response = retrying_function()
if total_only:
return response.hits.total
metadata = {
"took_ms": response.took,
"total": {
# The `response.hits.total` is a `elasticsearch_dsl.utils.AttrDict`
# instance. Pluck only the exact data needed.
"value": response.hits.total.value,
"relation": response.hits.total.relation,
},
"size": params["size"],
"page": params["page"],
}
documents = []
for hit in response:
try:
body_highlight = list(hit.meta.highlight.body)
except AttributeError:
body_highlight = []
try:
title_highlight = list(hit.meta.highlight.title)
except AttributeError:
title_highlight = []
d = {
"mdn_url": hit.meta.id,
"score": hit.meta.score,
"title": hit.title,
"locale": hit.locale,
"slug": hit.slug,
"popularity": hit.popularity,
"summary": hit.summary,
"highlight": {
"body": body_highlight,
"title": title_highlight,
},
}
documents.append(d)
try:
suggest = getattr(response, "suggest")
except AttributeError:
suggest = None
suggestions = []
if suggest:
suggestion_strings = _unpack_suggestions(
params["query"],
response.suggest,
("body_suggestions", "title_suggestions"),
)
for score, string in suggestion_strings:
if score > min_suggestion_score or 1:
# Sure, this is different way to spell, but what will it yield
# if you actually search it?
total = _find(dict(params, query=string), total_only=True)
if total["value"] > 0:
suggestions.append(
{
"text": string,
"total": {
# This 'total' is an `AttrDict` instance.
"value": total.value,
"relation": total.relation,
},
}
)
# Since they're sorted by score, it's usually never useful
# to suggestion more than exactly 1 good suggestion.
break
return {
"documents": documents,
"metadata": metadata,
"suggestions": suggestions,
}
def _unpack_suggestions(query, suggest, keys):
alternatives = []
for key in keys:
for suggestion in getattr(suggest, key, []):
for option in suggestion.options:
alternatives.append(
(
option.score,
query[0 : suggestion.offset]
+ option.text
+ query[suggestion.offset + suggestion.length :],
)
)
alternatives.sort(reverse=True) # highest score first
return alternatives
| 11,058
|
Python
|
.py
| 259
| 33.204633
| 113
| 0.607023
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,059
|
forms.py
|
mdn_kuma/kuma/api/v1/search/forms.py
|
from django import forms
from django.conf import settings
from django.utils.datastructures import MultiValueDict
class TypedMultipleValueField(forms.TypedMultipleChoiceField):
"""Unlike TypedMultipleChoiceField we don't care what the individual values
are as long as they're not empty."""
def valid_value(self, value):
# Basically, as long as it's not empty, it's fine
return bool(value)
class MultipleChoiceFieldICase(forms.MultipleChoiceField):
"""Just like forms.MultipleChoiceField but everything's case insentive.
For simplicity, this field assumes that each choice is a tuple where
the first element is always a string.
"""
def valid_value(self, value):
return str(value).lower() in [x[0].lower() for x in self.choices]
class SearchForm(forms.Form):
q = forms.CharField(max_length=settings.ES_Q_MAXLENGTH)
locale = MultipleChoiceFieldICase(
required=False,
# The `settings.LANGUAGES` looks like this:
# [('en-US', 'English (US)'), ...]
# But all locales are stored in lowercase in Elasticsearch, so
# force everything to lowercase.
choices=[(code, name) for code, name in settings.LANGUAGES],
)
SORT_CHOICES = ("best", "relevance", "popularity")
sort = forms.ChoiceField(required=False, choices=[(x, x) for x in SORT_CHOICES])
size = forms.IntegerField(required=True, min_value=1, max_value=100)
page = forms.IntegerField(required=True, min_value=1, max_value=10)
slug_prefix = TypedMultipleValueField(required=False)
def __init__(self, data, **kwargs):
initial = kwargs.get("initial", {})
# This makes it possible to supply `initial={some dict}` to the form
# and have its values become part of the default. Normally, in Django,
# the `SomeForm(data, initial={...})` is just used to prepopulate the
# HTML generated form widgets.
# See https://www.peterbe.com/plog/initial-values-bound-django-form-rendered
data = MultiValueDict({**{k: [v] for k, v in initial.items()}, **data})
# If, for keys we have an initial value for, it was passed an empty string,
# then swap it for the initial value.
# For example `?q=searching&page=` you probably meant to omit it
# but "allowing" it to be an empty string makes it convenient for the client.
for key, values in data.items():
if key in initial and values == "":
data[key] = initial[key]
super().__init__(data, **kwargs)
| 2,559
|
Python
|
.py
| 47
| 47.340426
| 85
| 0.680817
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,060
|
test_admin.py
|
mdn_kuma/kuma/api/tests/test_admin.py
|
import json
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from kuma.notifications import models
def test_admin_update_content(user_client, wiki_user):
# Prepare: Watch page.
page_title = "<dialog>: The Dialog element"
page_url = "/en-us/docs/web/html/element/dialog"
baker.make(models.Watch, users=[wiki_user], title=page_title, url=page_url)
# Test: Trigger content update.
url = reverse("admin_api:admin.update_content")
auth_headers = {
"HTTP_AUTHORIZATION": f"Bearer {settings.NOTIFICATIONS_ADMIN_TOKEN}",
}
response = user_client.post(
url,
json.dumps(
{
"page": "/en-US/docs/Web/HTML/Element/dialog",
"pr": "https://github.com/mdn/content/pull/14607",
}
),
content_type="application/json",
**auth_headers,
)
assert response.status_code == 200
# Verify: Notification was created.
url = reverse("api-v1:plus.notifications")
response = user_client.get(url)
assert response.status_code == 200
notifications = json.loads(response.content)["items"]
assert len(notifications) == 1
notification = notifications[0]
assert notification["title"] == page_title
assert notification["url"] == page_url
assert notification["text"] == "Page updated (see PR!mdn/content!14607!!)"
| 1,416
|
Python
|
.py
| 37
| 31.945946
| 79
| 0.665693
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,061
|
urls.py
|
mdn_kuma/kuma/version/urls.py
|
from django.urls import re_path
from . import views
urlpatterns = [
# Serve the revision hashes.
re_path(r"^media/revision.txt$", views.revision_hash, name="version.kuma"),
]
| 185
|
Python
|
.py
| 6
| 28.166667
| 79
| 0.728814
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,062
|
views.py
|
mdn_kuma/kuma/version/views.py
|
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_safe
@never_cache
@require_safe
def revision_hash(request):
"""
Return the kuma revision hash.
"""
return HttpResponse(
settings.REVISION_HASH, content_type="text/plain; charset=utf-8"
)
| 390
|
Python
|
.py
| 13
| 26.692308
| 72
| 0.770667
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,063
|
test_views.py
|
mdn_kuma/kuma/version/tests/test_views.py
|
import pytest
from kuma.core.tests import assert_no_cache_header
from kuma.core.urlresolvers import reverse
@pytest.mark.parametrize("method", ["get", "head"])
def test_revision_hash(client, db, method, settings):
settings.REVISION_HASH = "the_revision_hash"
response = getattr(client, method)(reverse("version.kuma"))
assert response.status_code == 200
assert response["Content-Type"] == "text/plain; charset=utf-8"
assert_no_cache_header(response)
if method == "get":
assert response.content.decode() == "the_revision_hash"
@pytest.mark.parametrize("method", ["post", "put", "delete", "options", "patch"])
def test_revision_hash_405s(client, db, method):
response = getattr(client, method)(reverse("version.kuma"))
assert response.status_code == 405
assert_no_cache_header(response)
| 834
|
Python
|
.py
| 17
| 45.176471
| 81
| 0.721675
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,064
|
urlresolvers.py
|
mdn_kuma/kuma/core/urlresolvers.py
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.urls import LocalePrefixPattern, URLResolver
from django.urls import reverse as django_reverse
from django.utils import translation
from .i18n import get_language
class KumaLocalePrefixPattern(LocalePrefixPattern):
"""
A prefix pattern for localized URLs that uses Kuma's case-sensitive locale
codes instead of Django's, which are all lowercase.
We do this via a customized get_language function in kuma/core/i18n.py.
NOTE: See upstream LocalePrefixPattern for Django 2.2 / 3.0:
https://github.com/django/django/blob/3.0/django/urls/resolvers.py#L288-L319
"""
@property
def language_prefix(self):
language_code = get_language() or settings.LANGUAGE_CODE
return "%s/" % language_code
def i18n_patterns(*urls):
"""
Add the language code prefix to every URL pattern within this function.
This may only be used in the root URLconf, not in an included URLconf.
NOTE: Modified from i18n_patterns in Django 2.2 / 3.0, see:
https://github.com/django/django/blob/3.0/django/conf/urls/i18n.py#L8-L20
Modifications:
- Raises ImproperlyConfigured if settings.USE_I18N is False
- Forces prefix_default_language to True, so urls always include the locale
- Does not accept prefix_default_language as a kwarg, due to the above
- Uses our custom URL prefix pattern, to support our locale codes
"""
if not settings.USE_I18N:
raise ImproperlyConfigured("Kuma requires settings.USE_I18N to be True.")
return [URLResolver(KumaLocalePrefixPattern(), list(urls))]
def reverse(
viewname, urlconf=None, args=None, kwargs=None, current_app=None, locale=None
):
"""Wraps Django's reverse to prepend the requested locale.
Keyword Arguments:
* locale - Use this locale prefix rather than the current active locale.
Keyword Arguments passed to Django's reverse:
* viewname
* urlconf
* args
* kwargs
* current_app
"""
if locale:
with translation.override(locale):
return django_reverse(
viewname,
urlconf=urlconf,
args=args,
kwargs=kwargs,
current_app=current_app,
)
else:
return django_reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
| 2,462
|
Python
|
.py
| 59
| 35.372881
| 88
| 0.708072
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,065
|
tasks.py
|
mdn_kuma/kuma/core/tasks.py
|
from datetime import datetime, timedelta
from celery.task import task
from django.contrib.sessions.models import Session
from ..notifications.models import Notification, NotificationData
from .decorators import skip_in_maintenance_mode
LOCK_ID = "clean-sessions-lock"
LOCK_EXPIRE = 60 * 5
def get_expired_sessions(now):
return Session.objects.filter(expire_date__lt=now).order_by("expire_date")
@task
@skip_in_maintenance_mode
def clean_sessions():
"""
Queue deleting expired session items without breaking poor MySQL
"""
import warnings
warnings.warn(
"clean_sessions() is disabled at the moment because depends "
"doing raw SQL queries which might not make sense if you start "
"with a completely empty database."
)
# now = timezone.now()
# logger = clean_sessions.get_logger()
# chunk_size = settings.SESSION_CLEANUP_CHUNK_SIZE
# if cache.add(LOCK_ID, now.strftime("%c"), LOCK_EXPIRE):
# total_count = get_expired_sessions(now).count()
# delete_count = 0
# logger.info(
# "Deleting the %s of %s oldest expired sessions" % (chunk_size, total_count)
# )
# try:
# cursor = connection.cursor()
# delete_count = cursor.execute(
# """
# DELETE
# FROM django_session
# WHERE expire_date < NOW()
# ORDER BY expire_date ASC
# LIMIT %s;
# """,
# [chunk_size],
# )
# finally:
# logger.info("Deleted %s expired sessions" % delete_count)
# cache.delete(LOCK_ID)
# expired_sessions = get_expired_sessions(now)
# if expired_sessions.exists():
# clean_sessions.apply_async()
# else:
# logger.error(
# "The clean_sessions task is already running since %s" % cache.get(LOCK_ID)
# )
@task
@skip_in_maintenance_mode
def clear_old_notifications():
"""
Delete old notifications from the database
"""
NotificationData.objects.filter(
created__lt=datetime.now() - timedelta(days=6 * 30)
).delete()
Notification.objects.filter(deleted=True).delete()
| 2,259
|
Python
|
.py
| 62
| 31.903226
| 89
| 0.615737
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,066
|
apps.py
|
mdn_kuma/kuma/core/apps.py
|
from django.apps import AppConfig
from django.conf import settings
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from kuma.celery import app
class CoreConfig(AppConfig):
"""
The Django App Config class to store information about the core app
and do startup time things.
"""
name = "kuma.core"
verbose_name = _("Core")
def ready(self):
"""Configure kuma.core after models are loaded."""
self.add_periodc_tasks()
def add_periodc_tasks(self):
from kuma.core.tasks import clean_sessions, clear_old_notifications
# Clean up expired sessions every 60 minutes
app.add_periodic_task(60 * 60, clean_sessions.s())
# Delete old notifications every month
app.add_periodic_task(60 * 60 * 24 * 30, clear_old_notifications.s())
@cached_property
def language_mapping(self):
"""
a static mapping of lower case language names and their native names
"""
# LANGUAGES settings return a list of tuple with language code and their native name
# Make the language code lower and convert the tuple to dictionary
return {lang[0].lower(): lang[1] for lang in settings.LANGUAGES}
| 1,265
|
Python
|
.py
| 29
| 37.37931
| 92
| 0.70114
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,067
|
i18n.py
|
mdn_kuma/kuma/core/i18n.py
|
"""
Customizations of Django i18n functions for Kuma.
Django language code is lower case, like 'en-us'.
Kuma language code is mixed case, like 'en-US'.
"""
from functools import lru_cache
from django.apps import apps
from django.conf import settings
from django.conf.locale import LANG_INFO
from django.utils import translation
from django.utils.translation.trans_real import check_for_language
from django.utils.translation.trans_real import get_languages as _django_get_languages
from django.utils.translation.trans_real import (
language_code_prefix_re,
language_code_re,
parse_accept_lang_header,
)
def django_language_code_to_kuma(lang_code):
"""
Convert Django language code to Kuma language code.
Django uses lower-case codes like en-us.
Mozilla uses mixed-case codes like en-US.
"""
return settings.LANGUAGE_URL_MAP.get(lang_code, lang_code)
def kuma_language_code_to_django(lang_code):
"""
Convert Kuma language code to Django.
Django uses lower-case codes like en-us.
Mozilla uses mixed-case codes like en-US.
"""
return lang_code.lower()
def get_language():
"""Returns the currently selected language as a Kuma language code."""
return django_language_code_to_kuma(translation.get_language())
@lru_cache()
def get_django_languages():
"""
Cache of settings.LANGUAGES, with Django keys, for easy lookups by key.
This would be the same as Django's get_languages, if we were using Django
language codes.
"""
return {
kuma_language_code_to_django(locale): name
for locale, name in settings.LANGUAGES
}
def get_kuma_languages():
"""
Cache of settings.LANGUAGES, with Kuma keys, for easy lookups by key.
This is identical to Django's get_languages, but the name makes it
clearer that Kuma language codes are used.
"""
return _django_get_languages()
@lru_cache(maxsize=1000)
def get_supported_language_variant(raw_lang_code):
"""
Returns the language-code that's listed in supported languages, possibly
selecting a more generic variant. Raises LookupError if nothing found.
The function will look for an alternative country-specific variant when the
currently checked language code is not found. In Django, this behaviour can
be avoided with the strict=True parameter, removed in this code.
lru_cache should have a maxsize to prevent from memory exhaustion attacks,
as the provided language codes are taken from the HTTP request. See also
<https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
Based on Django 1.11.16's get_supported_language_variant from
django/utils/translation/trans_real.py, with changes:
* Language code can also be a Kuma language code
* Return Kuma languge codes
* Force strict=False to always allow fuzzy matching (zh-CHS gets zh-CN)
"""
if raw_lang_code:
# Kuma: Convert Kuma to Django language code
lang_code = kuma_language_code_to_django(raw_lang_code)
# Kuma: Check for known override
if lang_code in settings.LOCALE_ALIASES:
return settings.LOCALE_ALIASES[lang_code]
# If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
possible_lang_codes = [lang_code]
try:
possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"])
except KeyError:
pass
generic_lang_code = lang_code.split("-")[0]
possible_lang_codes.append(generic_lang_code)
supported_lang_codes = get_django_languages()
# Look for exact match
for code in possible_lang_codes:
if code in supported_lang_codes and check_for_language(code):
# Kuma: Convert to Kuma language code
return django_language_code_to_kuma(code)
# If fr-fr is not supported, try fr-ca.
for supported_code in supported_lang_codes:
if supported_code.startswith(generic_lang_code + "-"):
# Kuma: Convert to Kuma language code
return django_language_code_to_kuma(supported_code)
raise LookupError(raw_lang_code)
def get_language_from_path(path):
"""
Returns the language-code if there is a valid language-code
found in the `path`.
Based on Django 1.11.16's get_language_from_path from
django/utils/translation/trans_real.py, with changes:
* Don't accept or pass strict parameter (assume strict=False).
* Use our customized get_supported_language_variant().
"""
regex_match = language_code_prefix_re.match(path)
if not regex_match:
return None
lang_code = regex_match.group(1)
try:
return get_supported_language_variant(lang_code)
except LookupError:
return None
def get_language_from_request(request):
"""
Analyzes the request to find what language the user wants the system to
show. Only languages listed in settings.LANGUAGES are taken into account.
If the user requests a sublanguage where we have a main language, we send
out the main language.
If there is a language code in the URL path prefix, then it is selected as
the request language and other methods (language cookie, Accept-Language
header) are skipped. In Django, the URL path prefix can be skipped with the
check_path=False parameter, removed in this code.
Based on Django 1.11.16's get_language_from_request from
django/utils/translation/trans_real.py, with changes:
* Always check the path.
* Don't check session language.
* Use LANGUAGE_CODE as the fallback language code, instead of passing it
through get_supported_language_variant first.
"""
# Kuma: Always use the URL's language (force check_path=True)
lang_code = get_language_from_path(request.path_info)
if lang_code is not None:
return lang_code
# Kuma: Skip checking the session-stored language via LANGUAGE_SESSION_KEY
# Use the (valid) language cookie override
lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
try:
return get_supported_language_variant(lang_code)
except LookupError:
pass
# Pick the closest langauge based on the Accept Language header
accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "")
for accept_lang, unused in parse_accept_lang_header(accept):
if accept_lang == "*":
break
# Kuma: Assert accept_lang fits the language code pattern
# The regex check was added with a security fix:
# https://www.djangoproject.com/weblog/2007/oct/26/security-fix/
# In the Django version, non-matching accept_lang codes are skipped.
# However, it doesn't seem possible for parse_accept_lang_header to
# return codes that would fail this check.
# The assertion keeps the security aspect, and gives us an opportunity
# to add a test case to Kuma and Django.
assert language_code_re.search(accept_lang)
try:
return get_supported_language_variant(accept_lang)
except LookupError:
continue
# Kuma: Fallback to default settings.LANGUAGE_CODE.
# Django supports a case when LANGUAGE_CODE is not in LANGUAGES
# (see https://github.com/django/django/pull/824). but our LANGUAGE_CODE is
# always the first entry in LANGUAGES.
return settings.LANGUAGE_CODE
def get_language_mapping():
return apps.get_app_config("core").language_mapping
def activate_language_from_request(request):
"""
Activate the language, based on the request.
Based on Django 1.11.16's LocaleMiddleware.process_request from
django/middleware/locale, with these changes:
* Assume language prefix patterns are used, with no implied default
language (prefix_default_language=True)
* Use Kuma's language selection via our get_language_from_request.
* Skip get_language_from_path, since used to determine if implied
default language is used.
* Set request.LANGUAGE_CODE to Kuma language code via get_language.
This is in its own function so it can be called from the
kuma.search tests to set the request language.
"""
language = get_language_from_request(request)
translation.activate(language)
request.LANGUAGE_CODE = get_language()
| 8,362
|
Python
|
.py
| 182
| 39.82967
| 86
| 0.715164
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,068
|
utils.py
|
mdn_kuma/kuma/core/utils.py
|
import logging
from smtplib import SMTPConnectError, SMTPServerDisconnected
from urllib.parse import ParseResult, parse_qsl, urlparse, urlsplit, urlunsplit
import requests
from django.conf import settings
from django.core.mail import EmailMultiAlternatives, get_connection
from django.http import QueryDict
from django.utils.cache import patch_cache_control
from django.utils.encoding import smart_bytes
from django.utils.http import urlencode
from redo import retrying
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
log = logging.getLogger("kuma.core.utils")
def urlparams(url_, fragment=None, query_dict=None, **query):
"""
Add a fragment and/or query parameters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced.
"""
url_ = urlparse(url_)
fragment = fragment if fragment is not None else url_.fragment
q = url_.query
new_query_dict = (
QueryDict(smart_bytes(q), mutable=True) if q else QueryDict("", mutable=True)
)
if query_dict:
for k, l in query_dict.lists():
new_query_dict[k] = None # Replace, don't append.
for v in l:
new_query_dict.appendlist(k, v)
for k, v in query.items():
# Replace, don't append.
if isinstance(v, list):
new_query_dict.setlist(k, v)
else:
new_query_dict[k] = v
query_string = urlencode(
[(k, v) for k, l in new_query_dict.lists() for v in l if v is not None]
)
new = ParseResult(
url_.scheme, url_.netloc, url_.path, url_.params, query_string, fragment
)
return new.geturl()
def add_shared_cache_control(response, **kwargs):
"""
Adds a Cache-Control header for shared caches, like CDNs, to the
provided response.
Default settings (which can be overridden or extended):
- max-age=0 - Don't use browser cache without asking if still valid
- s-maxage=CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE - Cache in the shared
cache for the default perioid of time
- public - Allow intermediate proxies to cache response
"""
nocache = response.has_header("Cache-Control") and (
"no-cache" in response["Cache-Control"]
or "no-store" in response["Cache-Control"]
)
if nocache:
return
# Set the default values.
cc_kwargs = {
"public": True,
"max_age": 0,
"s_maxage": settings.CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE,
}
# Override the default values and/or add new ones.
cc_kwargs.update(kwargs)
patch_cache_control(response, **cc_kwargs)
def order_params(original_url):
"""Standardize order of query parameters."""
bits = urlsplit(original_url)
qs = sorted(parse_qsl(bits.query, keep_blank_values=True))
new_qs = urlencode(qs)
new_url = urlunsplit((bits.scheme, bits.netloc, bits.path, new_qs, bits.fragment))
return new_url
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
):
"""Opinionated wrapper that creates a requests session with a
HTTPAdapter that sets up a Retry policy that includes connection
retries.
If you do the more naive retry by simply setting a number. E.g.::
adapter = HTTPAdapter(max_retries=3)
then it will raise immediately on any connection errors.
Retrying on connection errors guards better on unpredictable networks.
From http://docs.python-requests.org/en/master/api/?highlight=retries#requests.adapters.HTTPAdapter
it says: "By default, Requests does not retry failed connections."
The backoff_factor is documented here:
https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry
A default of retries=3 and backoff_factor=0.3 means it will sleep like::
[0.3, 0.6, 1.2]
""" # noqa
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def send_mail_retrying(
subject,
message,
from_email,
recipient_list,
fail_silently=False,
auth_user=None,
auth_password=None,
connection=None,
html_message=None,
attachment=None,
**kwargs,
):
"""Copied verbatim from django.core.mail.send_mail but with the override
that we're using our EmailMultiAlternativesRetrying class instead.
See its doc string for its full documentation.
The only difference is that this function allows for setting your
own custom 'retrying' keyword argument.
"""
connection = connection or get_connection(
username=auth_user,
password=auth_password,
fail_silently=fail_silently,
)
mail = EmailMultiAlternativesRetrying(
subject, message, from_email, recipient_list, connection=connection
)
if html_message:
mail.attach_alternative(html_message, "text/html")
if attachment:
mail.attach(attachment["name"], attachment["bytes"], attachment["mime"])
return mail.send(**kwargs)
class EmailMultiAlternativesRetrying(EmailMultiAlternatives):
"""
Thin wrapper on django.core.mail.EmailMultiAlternatives that adds
a retrying functionality. By default, the only override is that
we're very explicit about the of exceptions we treat as retry'able.
The list of exceptions we use to trigger a retry are:
* smtplib.SMTPConnectError
* smtplib.SMTPServerDisconnected
Only list exceptions that have been known to happen and are safe.
"""
def send(self, *args, retry_options=None, **kwargs):
# See https://github.com/mozilla-releng/redo
# for a list of the default options to the redo.retry function
# which the redo.retrying context manager wraps.
retry_options = retry_options or {
"retry_exceptions": (SMTPConnectError, SMTPServerDisconnected),
# The default in redo is 60 seconds. Let's tone that down.
"sleeptime": 3,
"attempts": 10,
}
parent_method = super(EmailMultiAlternativesRetrying, self).send
with retrying(parent_method, **retry_options) as method:
return method(*args, **kwargs)
| 6,497
|
Python
|
.py
| 162
| 34.049383
| 103
| 0.696128
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,069
|
admin.py
|
mdn_kuma/kuma/core/admin.py
|
# from django.contrib import admin
# from rest_framework.authtoken.admin import TokenAdmin
# from kuma.core.models import IPBan
class DisabledDeleteActionMixin(object):
def get_actions(self, request):
"""
Remove the built-in delete action, since it bypasses the model
delete() method (bad) and we want people using the non-admin
deletion UI anyway.
"""
actions = super(DisabledDeleteActionMixin, self).get_actions(request)
if "delete_selected" in actions:
del actions["delete_selected"]
return actions
class DisabledDeletionMixin(DisabledDeleteActionMixin):
def has_delete_permission(self, request, obj=None):
"""
Disable deletion of individual Documents, by always returning
False for the permission check.
"""
return False
# @admin.register(IPBan)
# class IPBanAdmin(admin.ModelAdmin):
# # Remove list delete action to enforce model soft delete in admin site
# actions = None
# readonly_fields = ("deleted",)
# list_display = ("ip", "created", "deleted")
# TokenAdmin.raw_id_fields = ["user"]
| 1,145
|
Python
|
.py
| 28
| 35.107143
| 77
| 0.692864
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,070
|
validators.py
|
mdn_kuma/kuma/core/validators.py
|
# see also: http://github.com/tav/scripts/raw/master/validate_jsonp.py
# Placed into the Public Domain by tav <tav@espians.com>
"""Validate Javascript Identifiers for use as JSON-P callback parameters."""
import re
from unicodedata import category
# ------------------------------------------------------------------------------
# javascript identifier unicode categories and "exceptional" chars
# ------------------------------------------------------------------------------
valid_jsid_categories_start = frozenset(["Lu", "Ll", "Lt", "Lm", "Lo", "Nl"])
valid_jsid_categories = frozenset(
["Lu", "Ll", "Lt", "Lm", "Lo", "Nl", "Mn", "Mc", "Nd", "Pc"]
)
valid_jsid_chars = ("$", "_")
# ------------------------------------------------------------------------------
# regex to find array[index] patterns
# ------------------------------------------------------------------------------
array_index_regex = re.compile(r"\[[0-9]+\]$")
has_valid_array_index = array_index_regex.search
replace_array_index = array_index_regex.sub
# ------------------------------------------------------------------------------
# javascript reserved words -- including keywords and null/boolean literals
# ------------------------------------------------------------------------------
is_reserved_js_word = frozenset(
[
"abstract",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"double",
"else",
"enum",
"export",
"extends",
"false",
"final",
"finally",
"float",
"for",
"function",
"goto",
"if",
"implements",
"import",
"in",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"true",
"try",
"typeof",
"var",
"void",
"volatile",
"while",
"with",
# potentially reserved in a future version of the ES5 standard
# 'let', 'yield'
]
).__contains__
# ------------------------------------------------------------------------------
# the core validation functions
# ------------------------------------------------------------------------------
def valid_javascript_identifier(identifier, escape="\\u", ucd_cat=category):
"""Return whether the given ``id`` is a valid Javascript identifier."""
if not identifier:
return False
if not isinstance(identifier, str):
try:
identifier = str(identifier, "utf-8")
except UnicodeDecodeError:
return False
if escape in identifier:
new = []
add_char = new.append
split_id = identifier.split(escape)
add_char(split_id.pop(0))
for segment in split_id:
if len(segment) < 4:
return False
try:
add_char(chr(int("0x" + segment[:4], 16)))
except Exception:
return False
add_char(segment[4:])
identifier = "".join(new)
if is_reserved_js_word(identifier):
return False
first_char = identifier[0]
if not (
(first_char in valid_jsid_chars)
or (ucd_cat(first_char) in valid_jsid_categories_start)
):
return False
for char in identifier[1:]:
if not ((char in valid_jsid_chars) or (ucd_cat(char) in valid_jsid_categories)):
return False
return True
def valid_jsonp_callback_value(value):
"""Return whether the given ``value`` can be used as a JSON-P callback."""
for identifier in value.split("."):
while "[" in identifier:
if not has_valid_array_index(identifier):
return False
identifier = replace_array_index("", identifier)
if not valid_javascript_identifier(identifier):
return False
return True
| 4,328
|
Python
|
.py
| 135
| 24.437037
| 88
| 0.468172
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,071
|
exceptions.py
|
mdn_kuma/kuma/core/exceptions.py
|
class ProgrammingError(Exception):
"""Somebody made a mistake in the code."""
class DateTimeFormatError(Exception):
"""Called by the datetimeformat function when receiving invalid format."""
pass
class FixtureMissingError(Exception):
"""Raise this if a fixture is missing"""
| 296
|
Python
|
.py
| 7
| 38.285714
| 78
| 0.760563
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,072
|
decorators.py
|
mdn_kuma/kuma/core/decorators.py
|
from functools import partial, wraps
from django.conf import settings
from django.shortcuts import redirect
from .utils import add_shared_cache_control
def shared_cache_control(func=None, **kwargs):
"""
Decorator to set Cache-Control header for shared caches like CDNs.
This duplicates Django's cache-control decorators, but avoids changing the
header if a "no-cache" header has already been applied. The cache-control
decorator changes in Django 2.0 to remove Python 2 workarounds.
Default settings (which can be overridden or extended):
- max-age=0 - Don't use browser cache without asking if still valid
- s-maxage=CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE - Cache in the shared
cache for the default perioid of time
- public - Allow intermediate proxies to cache response
"""
def _shared_cache_controller(viewfunc):
@wraps(viewfunc)
def _cache_controlled(request, *args, **kw):
response = viewfunc(request, *args, **kw)
add_shared_cache_control(response, **kwargs)
return response
return _cache_controlled
if func:
return _shared_cache_controller(func)
return _shared_cache_controller
def skip_in_maintenance_mode(func):
"""
Decorator for Celery task functions. If we're in MAINTENANCE_MODE, skip
the call to the decorated function. Otherwise, call the decorated function
as usual.
"""
@wraps(func)
def wrapped(*args, **kwargs):
if settings.MAINTENANCE_MODE:
return
return func(*args, **kwargs)
return wrapped
def redirect_in_maintenance_mode(func=None, methods=None):
"""
Decorator for view functions. If we're in MAINTENANCE_MODE, redirect
to the home page on requests using the given HTTP "methods" (or all
HTTP methods if "methods" is None). Otherwise, call the wrapped view
function as usual.
"""
if not func:
return partial(redirect_in_maintenance_mode, methods=methods)
@wraps(func)
def wrapped(request, *args, **kwargs):
if settings.MAINTENANCE_MODE and (
(methods is None) or (request.method in methods)
):
locale = getattr(request, "LANGUAGE_CODE", None)
return redirect(f"/{locale}/" if locale else "/")
return func(request, *args, **kwargs)
return wrapped
| 2,378
|
Python
|
.py
| 56
| 35.910714
| 78
| 0.693275
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,073
|
views.py
|
mdn_kuma/kuma/core/views.py
|
from django.http import HttpResponse
from kuma.core.decorators import shared_cache_control
@shared_cache_control(s_maxage=60 * 60 * 24 * 30)
def humans_txt(request):
"""We no longer maintain an actual /humans.txt endpoint but to avoid the
sad 404 we instead now just encourage people to go and use the GitHub
UI to see the contributors."""
return HttpResponse("See https://github.com/mdn/kuma/graphs/contributors\n")
| 436
|
Python
|
.py
| 8
| 51.125
| 80
| 0.764706
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,074
|
test_utils.py
|
mdn_kuma/kuma/core/tests/test_utils.py
|
import pytest
from django.core import mail
from django.core.mail.backends.locmem import EmailBackend
from requests.exceptions import ConnectionError
from kuma.core.utils import (
EmailMultiAlternativesRetrying,
order_params,
requests_retry_session,
send_mail_retrying,
)
@pytest.mark.parametrize(
"original,expected",
(
("https://example.com", "https://example.com"),
("http://example.com?foo=bar&foo=", "http://example.com?foo=&foo=bar"),
("http://example.com?foo=bar&bar=baz", "http://example.com?bar=baz&foo=bar"),
),
)
def test_order_params(original, expected):
assert order_params(original) == expected
def test_requests_retry_session(mock_requests):
def absolute_url(uri):
return "http://example.com" + uri
mock_requests.get(absolute_url("/a/ok"), text="hi")
mock_requests.get(absolute_url("/oh/noes"), text="bad!", status_code=504)
mock_requests.get(absolute_url("/oh/crap"), exc=ConnectionError)
session = requests_retry_session(status_forcelist=(504,))
response_ok = session.get(absolute_url("/a/ok"))
assert response_ok.status_code == 200
response_bad = session.get(absolute_url("/oh/noes"))
assert response_bad.status_code == 504
with pytest.raises(ConnectionError):
session.get(absolute_url("/oh/crap"))
class SomeException(Exception):
"""Just a custom exception class."""
class SMTPFlakyEmailBackend(EmailBackend):
"""doc string"""
def send_messages(self, messages):
self._attempts = getattr(self, "_attempts", 0) + 1
if self._attempts < 2:
raise SomeException("Oh noes!")
return super(SMTPFlakyEmailBackend, self).send_messages(messages)
def test_send_mail_retrying(settings):
settings.EMAIL_BACKEND = "kuma.core.tests.test_utils.SMTPFlakyEmailBackend"
send_mail_retrying(
"Subject",
"Message",
"from@example.com",
["to@example.com"],
retry_options={
"retry_exceptions": (SomeException,),
# Overriding defaults to avoid the test being slow.
"sleeptime": 0.02,
"jitter": 0.01,
},
)
sent = mail.outbox[-1]
# sanity check
assert sent.subject == "Subject"
def test_EmailMultiAlternativesRetrying(settings):
settings.EMAIL_BACKEND = "kuma.core.tests.test_utils.SMTPFlakyEmailBackend"
email = EmailMultiAlternativesRetrying(
"Multi Subject",
"Content",
"from@example.com",
["to@example.com"],
)
email.attach_alternative("<p>Content</p>", "text/html")
email.send(
retry_options={
"retry_exceptions": (SomeException,),
# Overriding defaults to avoid the test being slow.
"sleeptime": 0.02,
"jitter": 0.01,
}
)
sent = mail.outbox[-1]
# sanity check
assert sent.subject == "Multi Subject"
| 2,925
|
Python
|
.py
| 79
| 30.556962
| 85
| 0.658174
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,075
|
logging_urls.py
|
mdn_kuma/kuma/core/tests/logging_urls.py
|
from django.core.exceptions import SuspiciousOperation
from django.urls import re_path
from kuma.core.urlresolvers import i18n_patterns
def suspicious(request):
raise SuspiciousOperation("Raising exception to test logging.")
urlpatterns = i18n_patterns(re_path(r"^suspicious/$", suspicious, name="suspicious"))
| 320
|
Python
|
.py
| 6
| 50.833333
| 85
| 0.822006
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,076
|
__init__.py
|
mdn_kuma/kuma/core/tests/__init__.py
|
import os
from functools import wraps
from unittest import mock
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.test import TestCase
from django.utils.translation import trans_real
def assert_no_cache_header(response):
assert "max-age=0" in response["Cache-Control"]
assert "no-cache" in response["Cache-Control"]
assert "no-store" in response["Cache-Control"]
assert "must-revalidate" in response["Cache-Control"]
assert "s-maxage" not in response["Cache-Control"]
def assert_shared_cache_header(response):
assert "public" in response["Cache-Control"]
assert "s-maxage" in response["Cache-Control"]
def get_user(username="testuser"):
"""Return a django user or raise FixtureMissingError"""
User = get_user_model()
return User.objects.get(username=username)
JINJA_INSTRUMENTED = False
class KumaTestMixin(object):
skipme = False
def _pre_setup(self):
super(KumaTestMixin, self)._pre_setup()
# Clean the slate.
cache.clear()
trans_real.deactivate()
trans_real._translations = {} # Django fails to clear this cache.
trans_real.activate(settings.LANGUAGE_CODE)
def assertFileExists(self, path):
self.assertTrue(os.path.exists(path), "Path %r does not exist" % path)
def assertFileNotExists(self, path):
self.assertFalse(os.path.exists(path), "Path %r does exist" % path)
class KumaTestCase(KumaTestMixin, TestCase):
pass
def call_on_commit_immediately(test_method):
"""Useful for TestCase test methods, that ultimately depends on
`transaction.on_commit()` being called somewhere in the stack. These
would normally be not executed when TestCase rolls back.
But if the test wants to assert that something inside a
`transaction.on_commit()` is called, you're out of luck.
That's why this decorator exists. For example:
# In views.py
@transaction.atomic
def do_something(request):
transaction.on_commit(do_other_thing)
return http.HttpResponse('yay!')
# In test_something.py
class MyTests(TestCase):
@call_on_commit_immediately
def test_something(self):
self.client.get('/do/something')
In this example, without the decorator, the `do_other_thing` function
would simply never be called. This decorator fixes that but it doesn't
guarantee, in tests, that it gets called correctly last after
the transaction would have committed.
"""
def run_immediately(some_callable):
some_callable()
@wraps(test_method)
def inner(*args, **kwargs):
with mock.patch("django.db.transaction.on_commit") as mocker:
mocker.side_effect = run_immediately
return test_method(*args, **kwargs)
return inner
| 2,912
|
Python
|
.py
| 67
| 37.119403
| 78
| 0.706217
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,077
|
test_validators.py
|
mdn_kuma/kuma/core/tests/test_validators.py
|
from django.test import TestCase
from ..validators import valid_javascript_identifier, valid_jsonp_callback_value
class ValidatorTest(TestCase):
def test_valid_javascript_identifier(self):
"""
The function ``valid_javascript_identifier`` validates a given identifier
according to the latest draft of the ECMAScript 5 Specification
"""
self.assertTrue(valid_javascript_identifier(b"hello"))
self.assertFalse(valid_javascript_identifier(b"alert()"))
self.assertFalse(valid_javascript_identifier(b"a-b"))
self.assertFalse(valid_javascript_identifier(b"23foo"))
self.assertTrue(valid_javascript_identifier(b"foo23"))
self.assertTrue(valid_javascript_identifier(b"$210"))
self.assertTrue(valid_javascript_identifier("Stra\u00dfe"))
self.assertTrue(valid_javascript_identifier(rb"\u0062")) # 'b'
self.assertFalse(valid_javascript_identifier(rb"\u62"))
self.assertFalse(valid_javascript_identifier(rb"\u0020"))
self.assertTrue(valid_javascript_identifier(b"_bar"))
self.assertTrue(valid_javascript_identifier(b"some_var"))
self.assertTrue(valid_javascript_identifier(b"$"))
def test_valid_jsonp_callback_value(self):
"""
But ``valid_jsonp_callback_value`` is the function you want to use for
validating JSON-P callback parameter values:
"""
self.assertTrue(valid_jsonp_callback_value("somevar"))
self.assertFalse(valid_jsonp_callback_value("function"))
self.assertFalse(valid_jsonp_callback_value(" somevar"))
# It supports the possibility of '.' being present in the callback name, e.g.
self.assertTrue(valid_jsonp_callback_value("$.ajaxHandler"))
self.assertFalse(valid_jsonp_callback_value("$.23"))
# As well as the pattern of providing an array index lookup, e.g.
self.assertTrue(valid_jsonp_callback_value("array_of_functions[42]"))
self.assertTrue(valid_jsonp_callback_value("array_of_functions[42][1]"))
self.assertTrue(valid_jsonp_callback_value("$.ajaxHandler[42][1].foo"))
self.assertFalse(valid_jsonp_callback_value("array_of_functions[42]foo[1]"))
self.assertFalse(valid_jsonp_callback_value("array_of_functions[]"))
self.assertFalse(valid_jsonp_callback_value('array_of_functions["key"]'))
| 2,406
|
Python
|
.py
| 39
| 52.769231
| 85
| 0.705731
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,078
|
test_settings.py
|
mdn_kuma/kuma/core/tests/test_settings.py
|
"""Check that settings are consistent."""
import pytest
from django.conf import settings
def test_accepted_locales():
"""Check for a consistent ACCEPTED_LOCALES."""
assert len(settings.ACCEPTED_LOCALES) == len(set(settings.ACCEPTED_LOCALES))
assert settings.ACCEPTED_LOCALES[0] == settings.LANGUAGE_CODE
@pytest.mark.parametrize(
"primary,secondary",
(("zh-CN", "zh-TW"),),
)
def test_preferred_locale_codes(primary, secondary):
assert settings.ACCEPTED_LOCALES.index(primary) < settings.ACCEPTED_LOCALES.index(
secondary
)
@pytest.mark.parametrize("alias,locale", settings.LOCALE_ALIASES.items())
def test_locale_aliases(alias, locale):
"""Check that each locale alias matches a supported locale."""
assert alias not in settings.ACCEPTED_LOCALES
assert alias == alias.lower()
assert locale in settings.ACCEPTED_LOCALES
| 880
|
Python
|
.py
| 21
| 38.047619
| 86
| 0.747356
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,079
|
test_views.py
|
mdn_kuma/kuma/core/tests/test_views.py
|
import logging
from django.core import mail
from django.test import override_settings
from django.utils.log import AdminEmailHandler
from . import KumaTestCase
@override_settings(
DEBUG=False,
DEBUG_PROPAGATE_EXCEPTIONS=False,
ADMINS=(("admin", "admin@example.com"),),
ROOT_URLCONF="kuma.core.tests.logging_urls",
)
class LoggingTests(KumaTestCase):
logger = logging.getLogger("django.security")
suspicous_path = "/en-US/suspicious/"
def setUp(self):
super(LoggingTests, self).setUp()
self.old_handlers = self.logger.handlers[:]
def tearDown(self):
super(LoggingTests, self).tearDown()
self.logger.handlers = self.old_handlers
def test_no_mail_handler(self):
self.logger.handlers = [logging.NullHandler()]
response = self.client.get(self.suspicous_path)
assert 400 == response.status_code
assert 0 == len(mail.outbox)
def test_mail_handler(self):
self.logger.handlers = [AdminEmailHandler()]
response = self.client.get(self.suspicous_path)
assert 400 == response.status_code
assert 1 == len(mail.outbox)
assert "admin@example.com" in mail.outbox[0].to
assert self.suspicous_path in mail.outbox[0].body
| 1,263
|
Python
|
.py
| 32
| 33.4375
| 57
| 0.699673
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,080
|
test_decorators.py
|
mdn_kuma/kuma/core/tests/test_decorators.py
|
import pytest
from django.http import HttpResponse
from django.views.decorators.cache import never_cache
from ..decorators import (
redirect_in_maintenance_mode,
shared_cache_control,
skip_in_maintenance_mode,
)
from . import assert_no_cache_header
def simple_view(request):
return HttpResponse()
@pytest.mark.parametrize("maintenance_mode", [False, True])
def test_skip_in_maintenance_mode(settings, maintenance_mode):
@skip_in_maintenance_mode
def func(*args, **kwargs):
return (args, sorted(kwargs.items()))
settings.MAINTENANCE_MODE = maintenance_mode
if maintenance_mode:
assert func(1, 2, x=3, y=4) is None
else:
assert func(1, 2, x=3, y=4) == ((1, 2), [("x", 3), ("y", 4)])
@pytest.mark.parametrize(
"maintenance_mode, request_method, methods, expected_status_code",
[
(True, "get", None, 302),
(True, "post", None, 302),
(False, "get", None, 200),
(False, "post", None, 200),
(True, "get", ("PUT", "POST"), 200),
(True, "put", ("PUT", "POST"), 302),
(True, "post", ("PUT", "POST"), 302),
(False, "get", ("PUT", "POST"), 200),
(False, "put", ("PUT", "POST"), 200),
(False, "post", ("PUT", "POST"), 200),
(False, "post", ("PUT", "POST"), 200),
],
)
def test_redirect_in_maintenance_mode_decorator(
rf, settings, maintenance_mode, request_method, methods, expected_status_code
):
request = getattr(rf, request_method)("/foo")
settings.MAINTENANCE_MODE = maintenance_mode
if methods is None:
deco = redirect_in_maintenance_mode
else:
deco = redirect_in_maintenance_mode(methods=methods)
resp = deco(simple_view)(request)
assert resp.status_code == expected_status_code
def test_shared_cache_control_decorator_with_defaults(rf, settings):
settings.CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE = 777
request = rf.get("/foo")
response = shared_cache_control(simple_view)(request)
assert response.status_code == 200
assert "public" in response["Cache-Control"]
assert "max-age=0" in response["Cache-Control"]
assert "s-maxage=777" in response["Cache-Control"]
def test_shared_cache_control_decorator_with_overrides(rf, settings):
settings.CACHE_CONTROL_DEFAULT_SHARED_MAX_AGE = 777
request = rf.get("/foo")
deco = shared_cache_control(max_age=999, s_maxage=0)
response = deco(simple_view)(request)
assert response.status_code == 200
assert "public" in response["Cache-Control"]
assert "max-age=999" in response["Cache-Control"]
assert "s-maxage=0" in response["Cache-Control"]
def test_shared_cache_control_decorator_keeps_no_cache(rf, settings):
request = rf.get("/foo")
response = shared_cache_control(never_cache(simple_view))(request)
assert response.status_code == 200
assert "public" not in response["Cache-Control"]
assert "s-maxage" not in response["Cache-Control"]
assert_no_cache_header(response)
| 3,002
|
Python
|
.py
| 72
| 36.486111
| 81
| 0.66964
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,081
|
models.py
|
mdn_kuma/kuma/documenturls/models.py
|
import requests
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from redo import retrying
def download_url(url, retry_options=None):
retry_options = retry_options or {
"retry_exceptions": (requests.exceptions.Timeout,),
"sleeptime": 2,
"attempts": 5,
}
with retrying(requests.get, **retry_options) as retrying_get:
response = retrying_get(url, allow_redirects=False)
response.raise_for_status()
return response
class DocumentURL(models.Model):
"""There are documents we look up for things like bookmarks and notes.
These are not legacy Wiki documents but rather remote URLs.
"""
# E.g. /en-us/docs/web/javascript (note that it's lowercased!)
# (the longest URI in all our of content as of mid-2021 is 121 characters)
uri = models.CharField(max_length=250, unique=True, verbose_name="URI")
# E.g. https://developer.allizom.org/en-us/docs/web/javascript/index.json
absolute_url = models.URLField(verbose_name="Absolute URL")
# If it's applicable, it's a download of the `index.json` for that URL.
metadata = models.JSONField(null=True)
# If the URI for some reason becomes invalid, rather than deleting it
# or storing a boolean, note *when* it became invalid.
invalid = models.DateTimeField(null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Document URL"
def __str__(self):
return self.uri
@classmethod
def normalize_uri(cls, uri):
return uri.lower().strip()
@receiver(pre_save, sender=DocumentURL)
def assert_lowercase_uri(sender, instance, **kwargs):
# Because it's so important that the `uri` is lowercased, this makes
# absolutely sure it's always so.
# Ideally, the client should check this at upsert, but if it's missed,
# this last resort will make sure it doesn't get in in
instance.uri = DocumentURL.normalize_uri(instance.uri)
class DocumentURLCheck(models.Model):
document_url = models.ForeignKey(
DocumentURL, on_delete=models.CASCADE, verbose_name="Document URL"
)
http_error = models.IntegerField(verbose_name="HTTP error")
headers = models.JSONField(default=dict)
created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = "Document URL Check"
def __str__(self):
return f"{self.http_error} on {self.document_url.absolute_url}"
@classmethod
def check_uri(cls, uri, cleanup_old=False, retry_options=None):
document_url = DocumentURL.objects.get(uri=DocumentURL.normalize_uri(uri))
response = download_url(document_url.absolute_url, retry_options=retry_options)
headers = dict(response.headers)
checked = cls.objects.create(
document_url=document_url,
http_error=response.status_code,
headers=headers,
)
if cleanup_old:
cls.objects.filter(document_url=document_url).exclude(
id=checked.id
).delete()
return checked
| 3,184
|
Python
|
.py
| 71
| 38.352113
| 87
| 0.696284
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,082
|
apps.py
|
mdn_kuma/kuma/documenturls/apps.py
|
from django.apps import AppConfig
class DocumentURLsConfig(AppConfig):
name = "kuma.documenturls"
verbose_name = "Document URLs"
| 139
|
Python
|
.py
| 4
| 31.25
| 36
| 0.781955
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,083
|
admin.py
|
mdn_kuma/kuma/documenturls/admin.py
|
from django.contrib import admin
from .models import DocumentURL, DocumentURLCheck
@admin.register(DocumentURL)
class DocumentURLAdmin(admin.ModelAdmin):
list_display = (
"uri",
"absolute_url",
"is_valid",
"modified",
)
readonly_fields = (
"metadata",
"invalid",
"created",
"modified",
)
list_filter = ("invalid",)
search_fields = ("uri",)
ordering = ("-created",)
list_per_page = 10
def is_valid(self, obj):
return not obj.invalid
@admin.register(DocumentURLCheck)
class DocumentURLCheckAdmin(admin.ModelAdmin):
list_display = (
"_document_url",
"http_error",
"created",
)
readonly_fields = (
"document_url",
"http_error",
"headers",
"created",
)
list_filter = ("http_error",)
search_fields = ("document_url__uri", "document_url__absolute_url")
ordering = ("-created",)
list_per_page = 10
def _document_url(self, obj):
return obj.document_url.absolute_url
| 1,074
|
Python
|
.py
| 41
| 19.902439
| 71
| 0.599609
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,084
|
0001_initial.py
|
mdn_kuma/kuma/documenturls/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-07-12 19:04
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="DocumentURL",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"uri",
models.CharField(max_length=250, unique=True, verbose_name="URI"),
),
("absolute_url", models.URLField(verbose_name="Absolute URL")),
("metadata", models.JSONField(null=True)),
("invalid", models.DateTimeField(null=True)),
("created", models.DateTimeField(auto_now_add=True)),
("modified", models.DateTimeField(auto_now=True)),
],
options={
"verbose_name": "Document URL",
},
),
migrations.CreateModel(
name="DocumentURLCheck",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("http_error", models.IntegerField(verbose_name="HTTP error")),
("headers", models.JSONField(default=dict)),
("created", models.DateTimeField(auto_now_add=True)),
(
"document_url",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="documenturls.documenturl",
verbose_name="Document URL",
),
),
],
options={
"verbose_name": "Document URL Check",
},
),
]
| 2,240
|
Python
|
.py
| 62
| 19.870968
| 86
| 0.433241
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,085
|
models.py
|
mdn_kuma/kuma/notifications/models.py
|
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class NotificationData(models.Model):
title = models.CharField(max_length=256)
text = models.CharField(max_length=256)
type = models.CharField(
max_length=32,
choices=(("content", "content"), ("compat", "compat")),
default="compat",
)
# Storing the page url in the notification because the watch object might be deleted if the user
# unsubscribes
page_url = models.TextField()
data = models.JSONField(default=dict)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Notification(models.Model):
notification = models.ForeignKey(NotificationData, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
starred = models.BooleanField(default=False)
read = models.BooleanField(default=False)
deleted = models.BooleanField(default=False)
def serialize(self):
return {
"id": self.id,
"title": self.notification.title,
"text": self.notification.text,
"created": self.notification.created,
"read": self.read,
"starred": self.starred,
"url": self.notification.page_url,
}
def __str__(self):
return self.notification.title
class Watch(models.Model):
users = models.ManyToManyField(User, through="UserWatch")
title = models.CharField(max_length=2048)
url = models.TextField()
path = models.CharField(max_length=4096)
def __str__(self):
return f"<Watchers for: {self.url}, {self.path}>"
class CustomBaseModel(models.Model):
content_updates = models.BooleanField(default=True)
browser_compatibility = models.JSONField(default=list)
class Meta:
abstract = True
def custom_serialize(self):
return {
"content": self.content_updates,
"compatibility": self.browser_compatibility,
}
class UserWatch(CustomBaseModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
watch = models.ForeignKey(Watch, on_delete=models.CASCADE)
custom = models.BooleanField(default=False)
custom_default = models.BooleanField(default=False)
class Meta:
db_table = "notifications_watch_users"
def serialize(self):
return {
"title": self.watch.title,
"url": self.watch.url,
"path": self.watch.path,
"custom": self.watch.custom,
"custom_default": self.watch.custom_default,
}
def __str__(self):
return f"User {self.user_id} watching {self.watch_id}"
class DefaultWatch(CustomBaseModel):
user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
| 2,927
|
Python
|
.py
| 73
| 32.945205
| 100
| 0.674903
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,086
|
browsers.py
|
mdn_kuma/kuma/notifications/browsers.py
|
browsers = {
"chrome": {
"name": "Chrome",
"preview_name": "Canary",
},
"chrome_android": {
"name": "Chrome Android",
},
"deno": {
"name": "Deno",
},
"edge": {
"name": "Edge",
},
"firefox": {
"name": "Firefox",
"preview_name": "Nightly",
},
"firefox_android": {
"name": "Firefox for Android",
"pref_url": "about:config",
},
"ie": {
"name": "Internet Explorer",
},
"nodejs": {
"name": "Node.js",
},
"opera": {
"name": "Opera",
},
"opera_android": {
"name": "Opera Android",
},
"safari": {
"name": "Safari",
"preview_name": "TP",
},
"safari_ios": {
"name": "Safari on iOS",
},
"samsunginternet_android": {
"name": "Samsung Internet",
},
"webview_android": {
"name": "WebView Android",
},
}
| 944
|
Python
|
.py
| 48
| 13.333333
| 38
| 0.435268
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,087
|
apps.py
|
mdn_kuma/kuma/notifications/apps.py
|
from django.apps import AppConfig
class NotificationsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "kuma.notifications"
| 163
|
Python
|
.py
| 4
| 37.25
| 56
| 0.796178
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,088
|
utils.py
|
mdn_kuma/kuma/notifications/utils.py
|
import re
from collections import defaultdict
from kuma.documenturls.models import DocumentURL
from kuma.notifications.browsers import browsers
from kuma.notifications.models import Notification, NotificationData, Watch
def publish_bcd_notification(path, text, data=None):
# This traverses down the path to see if there's top level watchers
parts = path.split(".")
suffix = []
while len(parts) > 0:
subpath = ".".join(parts)
watcher = Watch.objects.filter(path=subpath).first()
suffix.append(parts.pop())
if not watcher:
continue
# Add the suffix based on the path to the title.
# Since suffix contains the current title (which should be an exact match)
# we use the suffix as title (after reversing the order).
title = reversed(suffix)
title = ".".join(title)
notification_data, _ = NotificationData.objects.get_or_create(
title=title,
text=text,
data=data,
type="compat",
page_url=watcher.url,
)
for user in watcher.users.all():
Notification.objects.create(notification=notification_data, user=user)
def get_browser_info(browser, preview=False):
name = browsers.get(browser, {"name": browser}).get("name", "")
if preview:
return browsers.get(browser, {"preview_name": browser, "name": browser}).get(
"preview_name", name
)
return name
def pluralize(browser_list):
if len(browser_list) == 1:
return browser_list[0]
else:
return ", ".join(browser_list[:-1]) + f", and {browser_list[-1]}"
BROWSER_GROUP = {
"firefox": "firefox",
"firefox_android": "firefox",
"chrome": "chrome",
"chrome_android": "chrome",
"edge": "chrome",
"webview_android": "chrome",
"deno": "deno",
"safari": "safari",
"safari_ios": "safari",
"ie": "ie",
"nodejs": "nodejs",
"opera": "opera",
"opera_android": "opera",
"samsunginternet_android": "samsunginternet_android",
}
COPY = {
"added_stable": "Supported in ",
"removed_stable": "Removed from ",
"added_preview": "In development in ",
}
def publish_content_notification(url, text):
watchers = Watch.objects.filter(url=url)
if not watchers:
return
notification_data, _ = NotificationData.objects.get_or_create(
text=text, title=watchers[0].title, type="content", page_url=url
)
for watcher in watchers:
# considering the possibility of multiple pages existing for the same path
for user in watcher.users.all():
Notification.objects.create(notification=notification_data, user=user)
def process_changes(changes):
bcd_notifications = []
content_notifications = []
for change in changes:
if change["event"] in ["added_stable", "removed_stable", "added_preview"]:
groups = defaultdict(list)
for browser_data in change["browsers"]:
browser = get_browser_info(
browser_data["browser"],
change["event"] == "added_preview",
)
groups[BROWSER_GROUP.get(browser_data["browser"], browser)].append(
{
"browser": f"{browser} {browser_data['version']}",
"data": change,
}
)
for group in groups.values():
browser_list = pluralize([i["browser"] for i in group])
bcd_notifications.append(
{
"path": change["path"],
"text": COPY[change["event"]] + browser_list,
"data": [i["data"] for i in group],
}
)
elif change["event"] == "added_subfeatures":
n = len(change["subfeatures"])
bcd_notifications.append(
{
"path": change["path"],
"text": f"{n} compatibility subfeature{'s'[:n ^ 1]} added",
"data": change,
}
)
elif change["event"] == "added_nonnull":
browser_list = [
get_browser_info(i["browser"]) for i in change["support_changes"]
]
text = pluralize(browser_list)
bcd_notifications.append(
{
"path": change["path"],
"text": f"More complete compatibility data added for {text}",
"data": change,
}
)
elif change["event"] == "content_updated":
url = DocumentURL.normalize_uri(change["page_url"])
m = re.match(r"^https://github.com/(.+)/pull/(\d+)$", change["pr_url"])
content_notifications.append(
{
"url": url,
"text": f"Page updated (see PR!{m.group(1)}!{m.group(2)}!!)",
}
)
for notification in bcd_notifications:
publish_bcd_notification(**notification)
for notification in content_notifications:
publish_content_notification(**notification)
| 5,243
|
Python
|
.py
| 133
| 28.714286
| 85
| 0.558332
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,089
|
admin.py
|
mdn_kuma/kuma/notifications/admin.py
|
from django.contrib import admin
from kuma.notifications.models import Notification, NotificationData, Watch
@admin.register(Notification)
class NotificationAdmin(admin.ModelAdmin):
...
@admin.register(NotificationData)
class NotificationDataAdmin(admin.ModelAdmin):
...
@admin.register(Watch)
class WatchAdmin(admin.ModelAdmin):
...
| 353
|
Python
|
.py
| 11
| 29.363636
| 75
| 0.81791
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,090
|
0002_auto_20211105_1529.py
|
mdn_kuma/kuma/notifications/migrations/0002_auto_20211105_1529.py
|
# Generated by Django 3.2.7 on 2021-11-05 15:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="watch",
field=models.SlugField(blank=True),
name="slug",
preserve_default=False,
),
migrations.RemoveField(
model_name="watch",
name="slug",
),
migrations.AddField(
model_name="watch",
name="url",
field=models.TextField(default=""),
preserve_default=False,
),
]
| 691
|
Python
|
.py
| 24
| 19.583333
| 47
| 0.554381
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,091
|
0004_notificationdata_data.py
|
mdn_kuma/kuma/notifications/migrations/0004_notificationdata_data.py
|
# Generated by Django 3.2.7 on 2021-12-13 15:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0003_watch_title"),
]
operations = [
migrations.AddField(
model_name="notificationdata",
name="data",
field=models.JSONField(default="{}"),
),
]
| 390
|
Python
|
.py
| 13
| 22.769231
| 49
| 0.612903
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,092
|
0008_default_watch.py
|
mdn_kuma/kuma/notifications/migrations/0008_default_watch.py
|
# Generated by Django 3.2.7 on 2022-01-06 03:06
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("notifications", "0007_watch_users"),
]
operations = [
migrations.AddField(
model_name="userwatch",
name="custom_default",
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name="DefaultWatch",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("content_updates", models.BooleanField(default=True)),
("browser_compatibility", models.JSONField(default=list)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
]
| 1,409
|
Python
|
.py
| 42
| 19.666667
| 74
| 0.48091
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,093
|
0001_initial.py
|
mdn_kuma/kuma/notifications/migrations/0001_initial.py
|
# Generated by Django 3.2.7 on 2021-11-05 15:19
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="CompatibilityData",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("bcd", models.JSONField()),
("created", models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name="NotificationData",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=256)),
("text", models.CharField(max_length=256)),
("created", models.DateTimeField(auto_now_add=True)),
("modified", models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name="Watch",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("slug", models.SlugField()),
("path", models.CharField(max_length=4096)),
],
),
migrations.CreateModel(
name="UserWatch",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
(
"watch",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="notifications.watch",
),
),
],
options={"db_table": "notifications_watch_users"},
),
migrations.CreateModel(
name="Notification",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("read", models.BooleanField(default=False)),
(
"notification",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="notifications.notificationdata",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| 3,992
|
Python
|
.py
| 119
| 16.159664
| 69
| 0.385053
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,094
|
0005_auto_20211215_2004.py
|
mdn_kuma/kuma/notifications/migrations/0005_auto_20211215_2004.py
|
# Generated by Django 3.2.7 on 2021-12-15 20:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0004_notificationdata_data"),
]
operations = [
migrations.DeleteModel(
name="CompatibilityData",
),
migrations.AddField(
model_name="notification",
name="starred",
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name="notificationdata",
name="type",
field=models.CharField(
choices=[("content", "content"), ("compat", "compat")],
default="compat",
max_length=32,
),
),
migrations.AlterField(
model_name="notificationdata",
name="data",
field=models.JSONField(default=dict),
),
]
| 940
|
Python
|
.py
| 30
| 21.233333
| 71
| 0.551381
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,095
|
0006_auto_20220105_0138.py
|
mdn_kuma/kuma/notifications/migrations/0006_auto_20220105_0138.py
|
# Generated by Django 3.2.7 on 2022-01-05 01:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0005_auto_20211215_2004"),
]
operations = [
migrations.AddField(
model_name="userwatch",
name="browser_compatibility",
field=models.JSONField(default=list),
),
migrations.AddField(
model_name="userwatch",
name="content_updates",
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name="userwatch",
name="custom",
field=models.BooleanField(default=False),
),
]
| 729
|
Python
|
.py
| 23
| 22.652174
| 53
| 0.593438
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,096
|
0010_notification_deleted.py
|
mdn_kuma/kuma/notifications/migrations/0010_notification_deleted.py
|
# Generated by Django 3.2.10 on 2022-01-27 14:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0009_notificationdata_page_url"),
]
operations = [
migrations.AddField(
model_name="notification",
name="deleted",
field=models.BooleanField(default=False),
),
]
| 408
|
Python
|
.py
| 13
| 24.153846
| 60
| 0.638462
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,097
|
0003_watch_title.py
|
mdn_kuma/kuma/notifications/migrations/0003_watch_title.py
|
# Generated by Django 3.2.7 on 2021-11-06 13:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0002_auto_20211105_1529"),
]
operations = [
migrations.AddField(
model_name="watch",
name="title",
field=models.CharField(default="", max_length=2048),
preserve_default=False,
),
]
| 438
|
Python
|
.py
| 14
| 23.642857
| 64
| 0.613365
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,098
|
0007_watch_users.py
|
mdn_kuma/kuma/notifications/migrations/0007_watch_users.py
|
# Generated by Django 3.2.7 on 2022-01-05 19:37
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("notifications", "0006_auto_20220105_0138"),
]
operations = [
migrations.AddField(
model_name="watch",
name="users",
field=models.ManyToManyField(
through="notifications.UserWatch", to=settings.AUTH_USER_MODEL
),
),
]
| 573
|
Python
|
.py
| 17
| 25.823529
| 78
| 0.640653
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|
8,099
|
0009_notificationdata_page_url.py
|
mdn_kuma/kuma/notifications/migrations/0009_notificationdata_page_url.py
|
# Generated by Django 3.2.7 on 2022-01-18 12:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("notifications", "0008_default_watch"),
]
operations = [
migrations.AddField(
model_name="notificationdata",
name="page_url",
field=models.TextField(default="/"),
preserve_default=False,
),
]
| 431
|
Python
|
.py
| 14
| 23.142857
| 48
| 0.614078
|
mdn/kuma
| 1,929
| 679
| 0
|
MPL-2.0
|
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
|