Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • djangoldp-packages/djangoldp
  • decentral1se/djangoldp
  • femmefaytale/djangoldp
  • jvtrudel/djangoldp
4 results
Show changes
Showing
with 476 additions and 0 deletions
# {{ app_name }}
__version__ = '0.0.0'
from django.contrib import admin
from django.apps import AppConfig
class {{ camel_case_app_name }}Config(AppConfig):
name = '{{ app_name }}'
"""This module is loaded by DjangoLDP core during setup."""
# define an extra variable (should be prefix with package name)
MYPACKAGE_VAR = 'MY_DEFAULT_VAR'
# register an extra middleware
MIDDLEWARE = []
# register an extra installed app
INSTALLED_APPS = []
from django.urls import path
from .models import Dummy
from .views import DummyViewset
urlpatterns = [
path('dummy/', DummyViewset.urls(model_prefix="dummy", model=Dummy))
]
from django.db import models
from djangoldp.models import Model
class Dummy(Model):
name = models.CharField(max_length=255, blank=True)
class Meta(Model.Meta):
rdf_type = 'hd:dummy'
def __str__(self):
return self.name
from django.test import TestCase
# Create your tests here.
from djangoldp.views import LDPViewSet
from djangoldp.models import Model
from .models import Dummy
class DummyViewset(LDPViewSet):
pass
[metadata]
name = {{ app_name }}
version = attr: {{ app_name }}.__version__
description = {{ description }}
long_description = file: README.md
license = MIT
classifiers =
Programming Language :: Python :: 3
[options]
packages = find:
[semantic_release]
version_source = tag
version_variable = {{ app_name }}/__init__.py:__version__
commit_parser = commit_parser.parse
#!/usr/bin/env python
"""Setup script."""
from setuptools import setup
setup()
#!/usr/bin/env python
import os
import sys
from djangoldp.conf import ldpsettings
if __name__ == "__main__":
ldpsettings.configure('settings.yml')
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
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?"
)
raise
execute_from_command_line(sys.argv)
"""{{ project_name }} URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.urls import include, path
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('djangoldp.urls')),
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"""
WSGI config for SIB 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
from django.conf import settings as django_settings
from djangoldp.conf import ldpsettings
if not django_settings.configured:
ldpsettings.configure()
application = get_wsgi_application()
try:
from djangoldp.activities.services import ActivityQueueService
ActivityQueueService.start()
except:
pass
dependencies:
ldppackages:
server:
# DjangoLDP required settings
DEBUG: true
ALLOWED_HOSTS:
- '*'
SECRET_KEY: '{{secret_key}}'
DATABASES:
default:
ENGINE: django.db.backends.sqlite3
NAME: db.sqlite3
LDP_RDF_CONTEXT: https://cdn.startinblox.com/owl/context.jsonld
ROOT_URLCONF: server.urls
STATIC_ROOT: static
MEDIA_ROOT: media
import re
from importlib import import_module
from django.conf import settings
class WebFinger(object):
def uri(self, name, *args):
domain = settings.BASE_URL
return "{domain}{name}".format(domain=domain, name=name)
def response(self, response_dict, rel, acct):
return response_dict
for package in settings.DJANGOLDP_PACKAGES:
try:
import_module('{}.endpoints.webfinger'.format(package))
except ModuleNotFoundError:
pass
model_classes = {cls.__name__: cls for cls in WebFinger.__subclasses__()}
ACCT_RE = re.compile(
r'(?:acct:)?(?P<userinfo>[\w.!#$%&\'*+-/=?^_`{|}~]+)@(?P<host>[\w.:-]+)')
class Acct(object):
def __init__(self, acct):
m = ACCT_RE.match(acct)
if not m:
raise ValueError('invalid acct format')
(userinfo, host) = m.groups()
self.userinfo = userinfo
self.host = host
class WebFingerEndpoint(object):
"""
WebFinger endpoint
See https://tools.ietf.org/html/rfc7033
"""
def __init__(self, request):
self.request = request
self.params = {}
self.acct = None
self._extract_params()
def _extract_params(self):
# Because in this endpoint we handle both GET
# and POST request.
query_dict = (self.request.POST if self.request.method == 'POST'
else self.request.GET)
self.params['resource'] = query_dict.get('resource', None)
self.params['rel'] = query_dict.get('rel', None)
def validate_params(self):
"""
A resource must be set.
"""
if self.params['resource'] is None:
raise WebFingerError('invalid_request')
try:
self.acct = Acct(self.params['resource'])
except ValueError:
raise WebFingerError('invalid_acct_format')
def response(self):
"""
This endpoint only reply to rel="http://openid.net/specs/connect/1.0/issuer"
:return: a dict representing the Json response
"""
dict = {
'subject': self.params['resource'],
'aliases': [],
'links': []
}
for class_name in model_classes:
model_class = model_classes[class_name]
webfinger = model_class()
dict = webfinger.response(dict, self.params['rel'], self.acct)
return dict
class WebFingerError(Exception):
_errors = {
'invalid_request': "The request provider parameter must contains an url or an email",
'invalid_acct_format': "Invalid acct format"
}
def __init__(self, error=None, dict=None):
if dict is None:
self.error = error
self.description = self._errors.get(error)
else:
self.error = dict['error']
self.description = dict['error_description']
def create_dict(self):
dic = {
'error': self.error,
'error_description': self.description,
}
return dic
from django.conf import settings
from django.db.models import Q
from rest_framework.filters import BaseFilterBackend
from djangoldp.utils import check_client_ip
class OwnerFilterBackend(BaseFilterBackend):
"""Adds the objects owned by the user"""
def filter_queryset(self, request, queryset, view):
if request.user.is_superuser:
return queryset
if request.user.is_anonymous:
return queryset.none()
if getattr(view.model._meta, 'owner_field', None):
return queryset.filter(**{view.model._meta.owner_field: request.user})
if getattr(view.model._meta, 'owner_urlid_field', None):
return queryset.filter(**{view.model._meta.owner_urlid_field: request.user.urlid})
if getattr(view.model._meta, 'auto_author', None):
return queryset.filter(**{view.model._meta.auto_author: request.user})
return queryset
class PublicFilterBackend(BaseFilterBackend):
"""
Public filter applied.
This class can be applied on models which bears a is_public boolean field, to filter objects that are public.
"""
def filter_queryset(self, request, queryset, view):
public_field = queryset.model._meta.public_field
return queryset.filter(**{public_field: True})
class ActiveFilterBackend(BaseFilterBackend):
"""
Filter which removes inactive objects from the queryset, useful for user for instance and configurable using the active_field meta
"""
def filter_queryset(self, request, queryset, view):
if (hasattr(queryset.model._meta, 'active_field')):
is_active_field = queryset.model._meta.active_field
return queryset.filter(**{is_active_field :True})
return queryset
class NoFilterBackend(BaseFilterBackend):
"""
No filter applied.
This class is useful for permission classes that don't filter objects, so that they can be chained with other
"""
def filter_queryset(self, request, queryset, view):
return queryset
class LocalObjectFilterBackend(BaseFilterBackend):
"""
Filter which removes external objects (federated backlinks) from the queryset
For querysets which should only include local objects
"""
def filter_queryset(self, request, queryset, view):
return queryset.filter(urlid__startswith=settings.SITE_URL)
class LocalObjectOnContainerPathBackend(LocalObjectFilterBackend):
"""
Override of LocalObjectFilterBackend which removes external objects when the view requested
is the model container path
"""
def filter_queryset(self, request, queryset, view):
from djangoldp.models import Model
if issubclass(view.model, Model) and request.path_info == view.model.get_container_path():
return super(LocalObjectOnContainerPathBackend, self).filter_queryset(request, queryset, view)
return queryset
class SearchByQueryParamFilterBackend(BaseFilterBackend):
"""
Applies search fields in the request query params to the queryset
"""
def filter_queryset(self, request, queryset, view):
# the model fields on which to perform the search
search_fields = request.GET.get('search-fields', None)
# the terms to search the fields for
search_terms = request.GET.get('search-terms', None)
# the method of search to apply to the model fields
search_method = request.GET.get('search-method', "basic")
# union or intersection
search_policy = request.GET.get('search-policy', 'union')
# check if there is indeed a search requested
if search_fields is None or search_terms is None:
return queryset
def _construct_search_query(search):
'''Utility function pipes many Django Query objects'''
search_query = []
for idx, s in enumerate(search):
if idx > 0:
# the user has indicated to make a union of all query results
if search_policy == "union":
search_query = search_query | Q(**s)
# the user has indicated to make an intersection of all query results
else:
search_query = search_query & Q(**s)
continue
search_query = Q(**s)
return search_query
search_fields = search_fields.split(',')
if search_method == "basic":
search = []
for s in search_fields:
query = {}
query["{}__contains".format(s)] = search_terms
search.append(query)
queryset = queryset.filter(_construct_search_query(search))
elif search_method == "ibasic":
# NOTE: to use, see https://stackoverflow.com/questions/54071944/fielderror-unsupported-lookup-unaccent-for-charfield-or-join-on-the-field-not
unaccent_extension = getattr(settings, 'SEARCH_UNACCENT_EXTENSION', False) and 'django.contrib.postgres' in settings.INSTALLED_APPS
middle_term = '__unaccent' if unaccent_extension else ''
search = []
for s in search_fields:
query = {}
query["{}{}__icontains".format(s, middle_term)] = search_terms
search.append(query)
queryset = queryset.filter(_construct_search_query(search))
elif search_method == "exact":
search = []
for s in search_fields:
query = {}
query["{}__exact".format(s)] = search_terms
search.append(query)
queryset = queryset.filter(_construct_search_query(search))
return queryset
class IPFilterBackend(BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
if check_client_ip(request):
return queryset
else:
return queryset.none()
\ No newline at end of file
'''
DjangoLDP Check Integrity Command & Importer
Usage `./manage.py check_integrity --help`
This command does import every `check_integrity.py` of every DJANGOLDP_PACKAGES
Allowed methods:
`add_arguments(parser)`: Allows to create new arguments to this command
`check_integrity(options)`: Do your own checks on the integrity
Examples on `djangoldp/check_integrity.py`
'''
from django.core.management.base import BaseCommand
from django.conf import settings
from importlib import import_module
import requests
class Command(BaseCommand):
help = "Check the datas integrity"
def add_arguments(self, parser):
import_module('djangoldp.check_integrity').add_arguments(parser)
for package in settings.DJANGOLDP_PACKAGES:
try:
import_module('{}.check_integrity'.format(package)).add_arguments(parser)
except:
pass
def handle(self, *args, **options):
import_module('djangoldp.check_integrity').check_integrity(options)
for package in settings.DJANGOLDP_PACKAGES:
try:
import_module('{}.check_integrity'.format(package)).check_integrity(options)
except:
pass
exit(0)