*(minor): stdlib logging to structlog

This commit is contained in:
Langhammer, Jens 2019-10-01 10:24:10 +02:00
parent b3aede5bba
commit f4499a5459
56 changed files with 111 additions and 259 deletions

View File

@ -1,114 +0,0 @@
# The default ``config.py``
# flake8: noqa
def set_prefs(prefs):
"""This function is called before opening the project"""
# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_files()`.
# Note that ``?`` and ``*`` match all characters but slashes.
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
# '.svn': matches 'pkg/.svn' and all of its children
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
'.hg', '.svn', '_svn', '.git', '.tox']
# Specifies which files should be considered python files. It is
# useful when you have scripts inside your project. Only files
# ending with ``.py`` are considered to be python files by
# default.
# prefs['python_files'] = ['*.py']
# Custom source folders: By default rope searches the project
# for finding source folders (folders that should be searched
# for finding modules). You can add paths to that list. Note
# that rope guesses project source folders correctly most of the
# time; use this if you have any problems.
# The folders should be relative to project root and use '/' for
# separating folders regardless of the platform rope is running on.
# 'src/my_source_folder' for instance.
# prefs.add('source_folders', 'src')
# You can extend python path for looking up modules
# prefs.add('python_path', '~/python/')
# Should rope save object information or not.
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False
# If `True`, rope analyzes each module when it is being saved.
prefs['automatic_soa'] = True
# The depth of calls to follow in static object analysis
prefs['soa_followed_calls'] = 0
# If `False` when running modules or unit tests "dynamic object
# analysis" is turned off. This makes them much faster.
prefs['perform_doa'] = True
# Rope can check the validity of its object DB when running.
prefs['validate_objectdb'] = True
# How many undos to hold?
prefs['max_history_items'] = 32
# Shows whether to save history across sessions.
prefs['save_history'] = True
prefs['compress_history'] = False
# Set the number spaces used for indenting. According to
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
# unit-tests use 4 spaces it is more reliable, too.
prefs['indent_size'] = 4
# Builtin and c-extension modules that are allowed to be imported
# and inspected by rope.
prefs['extension_modules'] = []
# Add all standard c-extensions to extension_modules list.
prefs['import_dynload_stdmods'] = True
# If `True` modules with syntax errors are considered to be empty.
# The default value is `False`; When `False` syntax errors raise
# `rope.base.exceptions.ModuleSyntaxError` exception.
prefs['ignore_syntax_errors'] = False
# If `True`, rope ignores unresolvable imports. Otherwise, they
# appear in the importing namespace.
prefs['ignore_bad_imports'] = False
# If `True`, rope will insert new module imports as
# `from <package> import <module>` by default.
prefs['prefer_module_from_imports'] = False
# If `True`, rope will transform a comma list of imports into
# multiple separate import statements when organizing
# imports.
prefs['split_imports'] = False
# If `True`, rope will remove all top-level import statements and
# reinsert them at the top of the module when making changes.
prefs['pull_imports_to_top'] = True
# If `True`, rope will sort imports alphabetically by module name instead
# of alphabetically by import statement, with from imports after normal
# imports.
prefs['sort_imports_alphabetically'] = False
# Location of implementation of
# rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general
# case, you don't have to change this value, unless you're an rope expert.
# Change this value to inject you own implementations of interfaces
# listed in module rope.base.oi.type_hinting.providers.interfaces
# For example, you can add you own providers for Django Models, or disable
# the search type-hinting in a class hierarchy, etc.
prefs['type_hinting_factory'] = (
'rope.base.oi.type_hinting.factory.default_type_hinting_factory')
def project_opened(project):
"""This function is called after opening the project"""
# Do whatever you like here!

Binary file not shown.

14
.vscode/settings.json vendored
View File

@ -1,14 +0,0 @@
{
"python.pythonPath": "env/bin/python",
"editor.tabSize": 4,
"[html]": {
"editor.tabSize": 2
},
"[yml]": {
"editor.tabSize": 2
},
"cSpell.words": [
"SAML",
"passbook"
]
}

View File

@ -1,14 +1,14 @@
"""passbook admin templatetags""" """passbook admin templatetags"""
import inspect import inspect
from logging import getLogger
from django import template from django import template
from django.db.models import Model from django.db.models import Model
from structlog import get_logger
from passbook.lib.utils.template import render_to_string from passbook.lib.utils.template import render_to_string
register = template.Library() register = template.Library()
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
@register.simple_tag() @register.simple_tag()
def get_links(model_instance): def get_links(model_instance):

View File

@ -1,14 +1,13 @@
"""passbook app_gw webserver management command""" """passbook app_gw webserver management command"""
from logging import getLogger
from daphne.cli import CommandLineInterface from daphne.cli import CommandLineInterface
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.utils import autoreload from django.utils import autoreload
from structlog import get_logger
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class Command(BaseCommand): class Command(BaseCommand):

View File

@ -1,6 +1,5 @@
"""passbook app_gw request handler""" """passbook app_gw request handler"""
import mimetypes import mimetypes
from logging import getLogger
from random import SystemRandom from random import SystemRandom
from urllib.parse import urlparse from urllib.parse import urlparse
@ -8,6 +7,7 @@ import certifi
import urllib3 import urllib3
from django.core.cache import cache from django.core.cache import cache
from django.utils.http import urlencode from django.utils.http import urlencode
from structlog import get_logger
from passbook.app_gw.models import ApplicationGatewayProvider from passbook.app_gw.models import ApplicationGatewayProvider
from passbook.app_gw.proxy.exceptions import InvalidUpstream from passbook.app_gw.proxy.exceptions import InvalidUpstream
@ -19,7 +19,7 @@ from passbook.policy.engine import PolicyEngine
SESSION_UPSTREAM_KEY = 'passbook_app_gw_upstream' SESSION_UPSTREAM_KEY = 'passbook_app_gw_upstream'
IGNORED_HOSTNAMES_KEY = 'passbook_app_gw_ignored' IGNORED_HOSTNAMES_KEY = 'passbook_app_gw_ignored'
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
QUOTE_SAFE = r'<.;>\(}*+|~=-$/_:^@)[{]&\'!,"`' QUOTE_SAFE = r'<.;>\(}*+|~=-$/_:^@)[{]&\'!,"`'
ERRORS_MESSAGES = { ERRORS_MESSAGES = {
'upstream-no-scheme': ("Upstream URL scheme must be either " 'upstream-no-scheme': ("Upstream URL scheme must be either "

View File

@ -1,7 +1,6 @@
"""response functions from django-revproxy""" """response functions from django-revproxy"""
import logging
from django.http import HttpResponse, StreamingHttpResponse from django.http import HttpResponse, StreamingHttpResponse
from structlog import get_logger
from passbook.app_gw.proxy.utils import (cookie_from_string, from passbook.app_gw.proxy.utils import (cookie_from_string,
set_response_headers, should_stream) set_response_headers, should_stream)
@ -9,7 +8,7 @@ from passbook.app_gw.proxy.utils import (cookie_from_string,
#: Default number of bytes that are going to be read in a file lecture #: Default number of bytes that are going to be read in a file lecture
DEFAULT_AMT = 2 ** 16 DEFAULT_AMT = 2 ** 16
logger = logging.getLogger(__name__) logger = get_logger(__name__)
def get_django_response(proxy_response, strict_cookies=False): def get_django_response(proxy_response, strict_cookies=False):

View File

@ -1,8 +1,9 @@
"""Utils from django-revproxy, slightly adjusted""" """Utils from django-revproxy, slightly adjusted"""
import logging
import re import re
from wsgiref.util import is_hop_by_hop from wsgiref.util import is_hop_by_hop
from structlog import get_logger
try: try:
from http.cookies import SimpleCookie from http.cookies import SimpleCookie
COOKIE_PREFIX = '' COOKIE_PREFIX = ''
@ -155,7 +156,7 @@ def encode_items(items):
return encoded return encoded
logger = logging.getLogger('revproxy.cookies') logger = get_logger()
def cookie_from_string(cookie_string, strict_cookies=False): def cookie_from_string(cookie_string, strict_cookies=False):

View File

@ -1,15 +1,14 @@
"""passbook app_gw cache clean signals""" """passbook app_gw cache clean signals"""
from logging import getLogger
from django.core.cache import cache from django.core.cache import cache
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.dispatch import receiver from django.dispatch import receiver
from structlog import get_logger
from passbook.app_gw.models import ApplicationGatewayProvider from passbook.app_gw.models import ApplicationGatewayProvider
from passbook.app_gw.proxy.handler import IGNORED_HOSTNAMES_KEY from passbook.app_gw.proxy.handler import IGNORED_HOSTNAMES_KEY
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
@receiver(post_save) @receiver(post_save)
# pylint: disable=unused-argument # pylint: disable=unused-argument

View File

@ -1,14 +1,14 @@
"""websocket proxy consumer""" """websocket proxy consumer"""
import threading import threading
from logging import getLogger
from ssl import CERT_NONE from ssl import CERT_NONE
import websocket import websocket
from channels.generic.websocket import WebsocketConsumer from channels.generic.websocket import WebsocketConsumer
from structlog import get_logger
from passbook.app_gw.models import ApplicationGatewayProvider from passbook.app_gw.models import ApplicationGatewayProvider
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class ProxyConsumer(WebsocketConsumer): class ProxyConsumer(WebsocketConsumer):
"""Proxy websocket connection to upstream""" """Proxy websocket connection to upstream"""

View File

@ -1,6 +1,4 @@
"""passbook audit models""" """passbook audit models"""
from logging import getLogger
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import AnonymousUser from django.contrib.auth.models import AnonymousUser
from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields import JSONField
@ -8,10 +6,11 @@ from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from ipware import get_client_ip from ipware import get_client_ip
from structlog import get_logger
from passbook.lib.models import UUIDModel from passbook.lib.models import UUIDModel
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class AuditEntry(UUIDModel): class AuditEntry(UUIDModel):
"""An individual audit log entry""" """An individual audit log entry"""

View File

@ -1,12 +1,12 @@
"""passbook core app config""" """passbook core app config"""
from importlib import import_module from importlib import import_module
from logging import getLogger
from django.apps import AppConfig from django.apps import AppConfig
from structlog import get_logger
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class PassbookCoreConfig(AppConfig): class PassbookCoreConfig(AppConfig):
"""passbook core app config""" """passbook core app config"""

View File

@ -1,9 +1,9 @@
"""passbook multi-factor authentication engine""" """passbook multi-factor authentication engine"""
from logging import getLogger from structlog import get_logger
from passbook.core.auth.factor import AuthenticationFactor from passbook.core.auth.factor import AuthenticationFactor
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class DummyFactor(AuthenticationFactor): class DummyFactor(AuthenticationFactor):

View File

@ -1,6 +1,5 @@
"""passbook multi-factor authentication engine""" """passbook multi-factor authentication engine"""
from inspect import Signature from inspect import Signature
from logging import getLogger
from django.contrib import messages from django.contrib import messages
from django.contrib.auth import _clean_credentials from django.contrib.auth import _clean_credentials
@ -10,6 +9,7 @@ from django.forms.utils import ErrorList
from django.shortcuts import redirect, reverse from django.shortcuts import redirect, reverse
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from django.views.generic import FormView from django.views.generic import FormView
from structlog import get_logger
from passbook.core.auth.factor import AuthenticationFactor from passbook.core.auth.factor import AuthenticationFactor
from passbook.core.auth.view import AuthenticationView from passbook.core.auth.view import AuthenticationView
@ -19,7 +19,7 @@ from passbook.core.tasks import send_email
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
from passbook.lib.utils.reflection import path_to_class from passbook.lib.utils.reflection import path_to_class
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def authenticate(request, backends, **credentials): def authenticate(request, backends, **credentials):

View File

@ -1,5 +1,4 @@
"""passbook multi-factor authentication engine""" """passbook multi-factor authentication engine"""
from logging import getLogger
from typing import List, Tuple from typing import List, Tuple
from django.contrib.auth import login from django.contrib.auth import login
@ -7,6 +6,7 @@ from django.contrib.auth.mixins import UserPassesTestMixin
from django.shortcuts import get_object_or_404, redirect, reverse from django.shortcuts import get_object_or_404, redirect, reverse
from django.utils.http import urlencode from django.utils.http import urlencode
from django.views.generic import View from django.views.generic import View
from structlog import get_logger
from passbook.core.models import Factor, User from passbook.core.models import Factor, User
from passbook.core.views.utils import PermissionDeniedView from passbook.core.views.utils import PermissionDeniedView
@ -14,7 +14,7 @@ from passbook.lib.utils.reflection import class_to_path, path_to_class
from passbook.lib.utils.urls import is_url_absolute from passbook.lib.utils.urls import is_url_absolute
from passbook.policy.engine import PolicyEngine from passbook.policy.engine import PolicyEngine
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def _redirect_with_qs(view, get_query_set=None): def _redirect_with_qs(view, get_query_set=None):
"""Wrapper to redirect whilst keeping GET Parameters""" """Wrapper to redirect whilst keeping GET Parameters"""

View File

@ -1,16 +1,15 @@
"""passbook core authentication forms""" """passbook core authentication forms"""
from logging import getLogger
from django import forms from django import forms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.validators import validate_email from django.core.validators import validate_email
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from structlog import get_logger
from passbook.core.models import User from passbook.core.models import User
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
from passbook.lib.utils.ui import human_list from passbook.lib.utils.ui import human_list
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class LoginForm(forms.Form): class LoginForm(forms.Form):
"""Allow users to login""" """Allow users to login"""

View File

@ -1,13 +1,13 @@
"""passbook import_users management command""" """passbook import_users management command"""
from csv import DictReader from csv import DictReader
from logging import getLogger
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.core.validators import EmailValidator, ValidationError from django.core.validators import EmailValidator, ValidationError
from structlog import get_logger
from passbook.core.models import User from passbook.core.models import User
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class Command(BaseCommand): class Command(BaseCommand):
"""Import users from CSV file""" """Import users from CSV file"""

View File

@ -1,15 +1,14 @@
"""passbook Webserver management command""" """passbook Webserver management command"""
from logging import getLogger
import cherrypy import cherrypy
from django.conf import settings from django.conf import settings
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from structlog import get_logger
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
from passbook.root.wsgi import application from passbook.root.wsgi import application
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class Command(BaseCommand): class Command(BaseCommand):

View File

@ -1,13 +1,12 @@
"""passbook Worker management command""" """passbook Worker management command"""
from logging import getLogger
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.utils import autoreload from django.utils import autoreload
from structlog import get_logger
from passbook.root.celery import CELERY_APP from passbook.root.celery import CELERY_APP
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class Command(BaseCommand): class Command(BaseCommand):

View File

@ -1,7 +1,6 @@
"""passbook core models""" """passbook core models"""
import re import re
from datetime import timedelta from datetime import timedelta
from logging import getLogger
from random import SystemRandom from random import SystemRandom
from time import sleep from time import sleep
from typing import List from typing import List
@ -14,11 +13,12 @@ from django.urls import reverse_lazy
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from model_utils.managers import InheritanceManager from model_utils.managers import InheritanceManager
from structlog import get_logger
from passbook.core.signals import password_changed from passbook.core.signals import password_changed
from passbook.lib.models import CreatedUpdatedModel, UUIDModel from passbook.lib.models import CreatedUpdatedModel, UUIDModel
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def default_nonce_duration(): def default_nonce_duration():

View File

@ -1,14 +1,13 @@
"""passbook core signals""" """passbook core signals"""
from logging import getLogger
from django.core.cache import cache from django.core.cache import cache
from django.core.signals import Signal from django.core.signals import Signal
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.dispatch import receiver from django.dispatch import receiver
from structlog import get_logger
from passbook.core.exceptions import PasswordPolicyInvalid from passbook.core.exceptions import PasswordPolicyInvalid
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
user_signed_up = Signal(providing_args=['request', 'user']) user_signed_up = Signal(providing_args=['request', 'user'])
invitation_created = Signal(providing_args=['request', 'invitation']) invitation_created = Signal(providing_args=['request', 'invitation'])

View File

@ -1,16 +1,16 @@
"""passbook core tasks""" """passbook core tasks"""
from datetime import datetime from datetime import datetime
from logging import getLogger
from django.core.mail import EmailMultiAlternatives from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.utils.html import strip_tags from django.utils.html import strip_tags
from structlog import get_logger
from passbook.core.models import Nonce from passbook.core.models import Nonce
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
from passbook.root.celery import CELERY_APP from passbook.root.celery import CELERY_APP
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
@CELERY_APP.task() @CELERY_APP.task()
def send_email(to_address, subject, template, context): def send_email(to_address, subject, template, context):

View File

@ -1,12 +1,11 @@
"""passbook URL Configuration""" """passbook URL Configuration"""
from logging import getLogger
from django.urls import path from django.urls import path
from structlog import get_logger
from passbook.core.auth import view from passbook.core.auth import view
from passbook.core.views import authentication, overview, user from passbook.core.views import authentication, overview, user
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
urlpatterns = [ urlpatterns = [
# Authentication views # Authentication views

View File

@ -1,13 +1,12 @@
"""passbook access helper classes""" """passbook access helper classes"""
from logging import getLogger
from django.contrib import messages from django.contrib import messages
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from structlog import get_logger
from passbook.core.models import Application from passbook.core.models import Application
from passbook.policy.engine import PolicyEngine from passbook.policy.engine import PolicyEngine
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class AccessMixin: class AccessMixin:
"""Mixin class for usage in Authorization views. """Mixin class for usage in Authorization views.

View File

@ -1,5 +1,4 @@
"""passbook core authentication views""" """passbook core authentication views"""
from logging import getLogger
from typing import Dict from typing import Dict
from django.contrib import messages from django.contrib import messages
@ -11,6 +10,7 @@ from django.shortcuts import get_object_or_404, redirect, reverse
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.views import View from django.views import View
from django.views.generic import FormView from django.views.generic import FormView
from structlog import get_logger
from passbook.core.auth.view import AuthenticationView, _redirect_with_qs from passbook.core.auth.view import AuthenticationView, _redirect_with_qs
from passbook.core.exceptions import PasswordPolicyInvalid from passbook.core.exceptions import PasswordPolicyInvalid
@ -20,7 +20,7 @@ from passbook.core.signals import invitation_used, user_signed_up
from passbook.core.tasks import send_email from passbook.core.tasks import send_email
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class LoginView(UserPassesTestMixin, FormView): class LoginView(UserPassesTestMixin, FormView):

View File

@ -1,14 +1,14 @@
"""passbook HIBP Models""" """passbook HIBP Models"""
from hashlib import sha1 from hashlib import sha1
from logging import getLogger
from django.db import models from django.db import models
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from requests import get from requests import get
from structlog import get_logger
from passbook.core.models import Policy, PolicyResult, User from passbook.core.models import Policy, PolicyResult, User
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class HaveIBeenPwendPolicy(Policy): class HaveIBeenPwendPolicy(Policy):
"""Check if password is on HaveIBeenPwned's list by upload the first """Check if password is on HaveIBeenPwned's list by upload the first

View File

@ -1,12 +1,11 @@
"""passbook LDAP Authentication Backend""" """passbook LDAP Authentication Backend"""
from logging import getLogger
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.backends import ModelBackend
from structlog import get_logger
from passbook.ldap.ldap_connector import LDAPConnector from passbook.ldap.ldap_connector import LDAPConnector
from passbook.ldap.models import LDAPSource from passbook.ldap.models import LDAPSource
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class LDAPBackend(ModelBackend): class LDAPBackend(ModelBackend):

View File

@ -1,15 +1,15 @@
"""Wrapper for ldap3 to easily manage user""" """Wrapper for ldap3 to easily manage user"""
from logging import getLogger
from time import time from time import time
import ldap3 import ldap3
import ldap3.core.exceptions import ldap3.core.exceptions
from structlog import get_logger
from passbook.core.models import User from passbook.core.models import User
from passbook.ldap.models import LDAPSource from passbook.ldap.models import LDAPSource
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
USERNAME_FIELD = CONFIG.y('ldap.username_field', 'sAMAccountName') USERNAME_FIELD = CONFIG.y('ldap.username_field', 'sAMAccountName')
LOGIN_FIELD = CONFIG.y('ldap.login_field', 'userPrincipalName') LOGIN_FIELD = CONFIG.y('ldap.login_field', 'userPrincipalName')

View File

@ -1,7 +1,7 @@
"""passbook sentry integration""" """passbook sentry integration"""
from logging import getLogger from structlog import get_logger
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def before_send(event, hint): def before_send(event, hint):

View File

@ -1,12 +1,11 @@
"""passbook lib navbar Templatetag""" """passbook lib navbar Templatetag"""
from logging import getLogger
from django import template from django import template
from django.urls import reverse from django.urls import reverse
from structlog import get_logger
register = template.Library() register = template.Library()
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
@register.simple_tag(takes_context=True) @register.simple_tag(takes_context=True)

View File

@ -1,10 +1,9 @@
"""passbook Core Reflection templatetags Templatetag""" """passbook Core Reflection templatetags Templatetag"""
from logging import getLogger
from django import template from django import template
from structlog import get_logger
register = template.Library() register = template.Library()
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def get_key_unique(context): def get_key_unique(context):

View File

@ -1,12 +1,12 @@
"""passbook oauth_client config""" """passbook oauth_client config"""
from importlib import import_module from importlib import import_module
from logging import getLogger
from django.apps import AppConfig from django.apps import AppConfig
from structlog import get_logger
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class PassbookOAuthClientConfig(AppConfig): class PassbookOAuthClientConfig(AppConfig):
"""passbook oauth_client config""" """passbook oauth_client config"""

View File

@ -1,7 +1,6 @@
"""OAuth Clients""" """OAuth Clients"""
import json import json
from logging import getLogger
from urllib.parse import parse_qs, urlencode from urllib.parse import parse_qs, urlencode
from django.conf import settings from django.conf import settings
@ -10,8 +9,9 @@ from django.utils.encoding import force_text
from requests import Session from requests import Session
from requests.exceptions import RequestException from requests.exceptions import RequestException
from requests_oauthlib import OAuth1 from requests_oauthlib import OAuth1
from structlog import get_logger
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class BaseOAuthClient: class BaseOAuthClient:

View File

@ -1,16 +1,16 @@
"""AzureAD OAuth2 Views""" """AzureAD OAuth2 Views"""
import json import json
import uuid import uuid
from logging import getLogger
from requests.exceptions import RequestException from requests.exceptions import RequestException
from structlog import get_logger
from passbook.oauth_client.clients import OAuth2Client from passbook.oauth_client.clients import OAuth2Client
from passbook.oauth_client.source_types.manager import MANAGER, RequestKind from passbook.oauth_client.source_types.manager import MANAGER, RequestKind
from passbook.oauth_client.utils import user_get_or_create from passbook.oauth_client.utils import user_get_or_create
from passbook.oauth_client.views.core import OAuthCallback from passbook.oauth_client.views.core import OAuthCallback
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class AzureADOAuth2Client(OAuth2Client): class AzureADOAuth2Client(OAuth2Client):

View File

@ -1,15 +1,15 @@
"""Discord OAuth Views""" """Discord OAuth Views"""
import json import json
from logging import getLogger
from requests.exceptions import RequestException from requests.exceptions import RequestException
from structlog import get_logger
from passbook.oauth_client.clients import OAuth2Client from passbook.oauth_client.clients import OAuth2Client
from passbook.oauth_client.source_types.manager import MANAGER, RequestKind from passbook.oauth_client.source_types.manager import MANAGER, RequestKind
from passbook.oauth_client.utils import user_get_or_create from passbook.oauth_client.utils import user_get_or_create
from passbook.oauth_client.views.core import OAuthCallback, OAuthRedirect from passbook.oauth_client.views.core import OAuthCallback, OAuthRedirect
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
@MANAGER.source(kind=RequestKind.redirect, name='Discord') @MANAGER.source(kind=RequestKind.redirect, name='Discord')

View File

@ -1,10 +1,11 @@
"""Source type manager""" """Source type manager"""
from enum import Enum from enum import Enum
from logging import getLogger
from structlog import get_logger
from passbook.oauth_client.views.core import OAuthCallback, OAuthRedirect from passbook.oauth_client.views.core import OAuthCallback, OAuthRedirect
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class RequestKind(Enum): class RequestKind(Enum):
"""Enum of OAuth Request types""" """Enum of OAuth Request types"""

View File

@ -1,16 +1,16 @@
"""Reddit OAuth Views""" """Reddit OAuth Views"""
import json import json
from logging import getLogger
from requests.auth import HTTPBasicAuth from requests.auth import HTTPBasicAuth
from requests.exceptions import RequestException from requests.exceptions import RequestException
from structlog import get_logger
from passbook.oauth_client.clients import OAuth2Client from passbook.oauth_client.clients import OAuth2Client
from passbook.oauth_client.source_types.manager import MANAGER, RequestKind from passbook.oauth_client.source_types.manager import MANAGER, RequestKind
from passbook.oauth_client.utils import user_get_or_create from passbook.oauth_client.utils import user_get_or_create
from passbook.oauth_client.views.core import OAuthCallback, OAuthRedirect from passbook.oauth_client.views.core import OAuthCallback, OAuthRedirect
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
@MANAGER.source(kind=RequestKind.redirect, name='reddit') @MANAGER.source(kind=RequestKind.redirect, name='reddit')

View File

@ -1,16 +1,16 @@
"""Supervisr OAuth2 Views""" """Supervisr OAuth2 Views"""
import json import json
from logging import getLogger
from requests.exceptions import RequestException from requests.exceptions import RequestException
from structlog import get_logger
from passbook.oauth_client.clients import OAuth2Client from passbook.oauth_client.clients import OAuth2Client
from passbook.oauth_client.source_types.manager import MANAGER, RequestKind from passbook.oauth_client.source_types.manager import MANAGER, RequestKind
from passbook.oauth_client.utils import user_get_or_create from passbook.oauth_client.utils import user_get_or_create
from passbook.oauth_client.views.core import OAuthCallback from passbook.oauth_client.views.core import OAuthCallback
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class SupervisrOAuth2Client(OAuth2Client): class SupervisrOAuth2Client(OAuth2Client):

View File

@ -1,15 +1,14 @@
"""Twitter OAuth Views""" """Twitter OAuth Views"""
from logging import getLogger
from requests.exceptions import RequestException from requests.exceptions import RequestException
from structlog import get_logger
from passbook.oauth_client.clients import OAuthClient from passbook.oauth_client.clients import OAuthClient
from passbook.oauth_client.source_types.manager import MANAGER, RequestKind from passbook.oauth_client.source_types.manager import MANAGER, RequestKind
from passbook.oauth_client.utils import user_get_or_create from passbook.oauth_client.utils import user_get_or_create
from passbook.oauth_client.views.core import OAuthCallback from passbook.oauth_client.views.core import OAuthCallback
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class TwitterOAuthClient(OAuthClient): class TwitterOAuthClient(OAuthClient):

View File

@ -1,7 +1,5 @@
"""Core OAauth Views""" """Core OAauth Views"""
from logging import getLogger
from django.conf import settings from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.contrib.auth import authenticate from django.contrib.auth import authenticate
@ -11,13 +9,14 @@ from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse from django.urls import reverse
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.views.generic import RedirectView, View from django.views.generic import RedirectView, View
from structlog import get_logger
from passbook.core.auth.view import AuthenticationView, _redirect_with_qs from passbook.core.auth.view import AuthenticationView, _redirect_with_qs
from passbook.lib.utils.reflection import app from passbook.lib.utils.reflection import app
from passbook.oauth_client.clients import get_client from passbook.oauth_client.clients import get_client
from passbook.oauth_client.models import OAuthSource, UserOAuthSourceConnection from passbook.oauth_client.models import OAuthSource, UserOAuthSourceConnection
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods

View File

@ -1,5 +1,4 @@
"""passbook OAuth2 Views""" """passbook OAuth2 Views"""
from logging import getLogger
from urllib.parse import urlencode from urllib.parse import urlencode
from django.contrib import messages from django.contrib import messages
@ -7,6 +6,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404, redirect, reverse from django.shortcuts import get_object_or_404, redirect, reverse
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from oauth2_provider.views.base import AuthorizationView from oauth2_provider.views.base import AuthorizationView
from structlog import get_logger
from passbook.audit.models import AuditEntry from passbook.audit.models import AuditEntry
from passbook.core.models import Application from passbook.core.models import Application
@ -14,7 +14,7 @@ from passbook.core.views.access import AccessMixin
from passbook.core.views.utils import LoadingView, PermissionDeniedView from passbook.core.views.utils import LoadingView, PermissionDeniedView
from passbook.oauth_provider.models import OAuth2Provider from passbook.oauth_provider.models import OAuth2Provider
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class PassbookAuthorizationLoadingView(LoginRequiredMixin, LoadingView): class PassbookAuthorizationLoadingView(LoginRequiredMixin, LoadingView):

View File

@ -1,11 +1,10 @@
"""passbook auth oidc provider app config""" """passbook auth oidc provider app config"""
from logging import getLogger
from django.apps import AppConfig from django.apps import AppConfig
from django.db.utils import InternalError, OperationalError, ProgrammingError from django.db.utils import InternalError, OperationalError, ProgrammingError
from django.urls import include, path from django.urls import include, path
from structlog import get_logger
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class PassbookOIDCProviderConfig(AppConfig): class PassbookOIDCProviderConfig(AppConfig):
"""passbook auth oidc provider app config""" """passbook auth oidc provider app config"""

View File

@ -1,13 +1,12 @@
"""OIDC Permission checking""" """OIDC Permission checking"""
from logging import getLogger
from django.contrib import messages from django.contrib import messages
from django.shortcuts import redirect from django.shortcuts import redirect
from structlog import get_logger
from passbook.core.models import Application from passbook.core.models import Application
from passbook.policy.engine import PolicyEngine from passbook.policy.engine import PolicyEngine
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def check_permissions(request, user, client): def check_permissions(request, user, client):
"""Check permissions, used for """Check permissions, used for

View File

@ -1,16 +1,15 @@
"""OTP Factor logic""" """OTP Factor logic"""
from logging import getLogger
from django.contrib import messages from django.contrib import messages
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from django.views.generic import FormView from django.views.generic import FormView
from django_otp import match_token, user_has_device from django_otp import match_token, user_has_device
from structlog import get_logger
from passbook.core.auth.factor import AuthenticationFactor from passbook.core.auth.factor import AuthenticationFactor
from passbook.otp.forms import OTPVerifyForm from passbook.otp.forms import OTPVerifyForm
from passbook.otp.views import OTP_SETTING_UP_KEY, EnableView from passbook.otp.views import OTP_SETTING_UP_KEY, EnableView
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class OTPFactor(FormView, AuthenticationFactor): class OTPFactor(FormView, AuthenticationFactor):
"""OTP Factor View""" """OTP Factor View"""

View File

@ -1,7 +1,6 @@
"""passbook OTP Views""" """passbook OTP Views"""
from base64 import b32encode from base64 import b32encode
from binascii import unhexlify from binascii import unhexlify
from logging import getLogger
from django.contrib import messages from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import LoginRequiredMixin
@ -15,6 +14,7 @@ from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.models import TOTPDevice
from qrcode import make from qrcode import make
from qrcode.image.svg import SvgPathImage from qrcode.image.svg import SvgPathImage
from structlog import get_logger
from passbook.lib.boilerplate import NeverCacheMixin from passbook.lib.boilerplate import NeverCacheMixin
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
@ -23,7 +23,7 @@ from passbook.otp.utils import otpauth_url
OTP_SESSION_KEY = 'passbook_otp_key' OTP_SESSION_KEY = 'passbook_otp_key'
OTP_SETTING_UP_KEY = 'passbook_otp_setup' OTP_SETTING_UP_KEY = 'passbook_otp_setup'
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class UserSettingsView(LoginRequiredMixin, TemplateView): class UserSettingsView(LoginRequiredMixin, TemplateView):
"""View for user settings to control OTP""" """View for user settings to control OTP"""

View File

@ -1,14 +1,14 @@
"""passbook password_expiry_policy Models""" """passbook password_expiry_policy Models"""
from datetime import timedelta from datetime import timedelta
from logging import getLogger
from django.db import models from django.db import models
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from structlog import get_logger
from passbook.core.models import Policy, PolicyResult, User from passbook.core.models import Policy, PolicyResult, User
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class PasswordExpiryPolicy(Policy): class PasswordExpiryPolicy(Policy):

View File

@ -1,12 +1,13 @@
"""passbook policy task""" """passbook policy task"""
from logging import getLogger
from multiprocessing import Process from multiprocessing import Process
from multiprocessing.connection import Connection from multiprocessing.connection import Connection
from typing import Any, Dict from typing import Any, Dict
from structlog import get_logger
from passbook.core.models import Policy, User from passbook.core.models import Policy, User
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def _cache_key(policy, user): def _cache_key(policy, user):

View File

@ -1,15 +1,15 @@
"""passbook core celery""" """passbook core celery"""
import logging
import os import os
from logging.config import dictConfig
from celery import Celery, signals from celery import Celery, signals
from django.conf import settings from django.conf import settings
from structlog import get_logger
# set the default Django settings module for the 'celery' program. # set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "passbook.root.settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "passbook.root.settings")
LOGGER = logging.getLogger(__name__) LOGGER = get_logger(__name__)
CELERY_APP = Celery('passbook') CELERY_APP = Celery('passbook')
@ -19,7 +19,7 @@ CELERY_APP = Celery('passbook')
@signals.setup_logging.connect @signals.setup_logging.connect
def config_loggers(*args, **kwags): def config_loggers(*args, **kwags):
"""Apply logging settings from settings.py to celery""" """Apply logging settings from settings.py to celery"""
logging.config.dictConfig(settings.LOGGING) dictConfig(settings.LOGGING)
# pylint: disable=unused-argument # pylint: disable=unused-argument

View File

@ -1,15 +1,14 @@
"""passbook URL Configuration""" """passbook URL Configuration"""
from logging import getLogger
from django.conf import settings from django.conf import settings
from django.contrib import admin from django.contrib import admin
from django.urls import include, path from django.urls import include, path
from django.views.generic import RedirectView from django.views.generic import RedirectView
from structlog import get_logger
from passbook.core.views import error from passbook.core.views import error
from passbook.lib.utils.reflection import get_apps from passbook.lib.utils.reflection import get_apps
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
admin.autodiscover() admin.autodiscover()
admin.site.login = RedirectView.as_view(pattern_name='passbook_core:auth-login') admin.site.login = RedirectView.as_view(pattern_name='passbook_core:auth-login')

View File

@ -1,12 +1,12 @@
"""passbook mod saml_idp app config""" """passbook mod saml_idp app config"""
from importlib import import_module from importlib import import_module
from logging import getLogger
from django.apps import AppConfig from django.apps import AppConfig
from structlog import get_logger
from passbook.lib.config import CONFIG from passbook.lib.config import CONFIG
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class PassbookSAMLIDPConfig(AppConfig): class PassbookSAMLIDPConfig(AppConfig):
"""passbook saml_idp app config""" """passbook saml_idp app config"""

View File

@ -2,9 +2,9 @@
import time import time
import uuid import uuid
from logging import getLogger
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from structlog import get_logger
from passbook.saml_idp import exceptions, utils, xml_render from passbook.saml_idp import exceptions, utils, xml_render
@ -65,7 +65,7 @@ class Processor:
def __init__(self, remote): def __init__(self, remote):
self.name = remote.name self.name = remote.name
self._remote = remote self._remote = remote
self._logger = getLogger(__name__) self._logger = get_logger(__name__)
self._system_params['ISSUER'] = self._remote.issuer self._system_params['ISSUER'] = self._remote.issuer
self._logger.debug('processor configured') self._logger.debug('processor configured')

View File

@ -1,16 +1,15 @@
"""passbook saml_idp Models""" """passbook saml_idp Models"""
from logging import getLogger
from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields import ArrayField
from django.db import models from django.db import models
from django.shortcuts import reverse from django.shortcuts import reverse
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from structlog import get_logger
from passbook.core.models import PropertyMapping, Provider from passbook.core.models import PropertyMapping, Provider
from passbook.lib.utils.reflection import class_to_path, path_to_class from passbook.lib.utils.reflection import class_to_path, path_to_class
from passbook.saml_idp.base import Processor from passbook.saml_idp.base import Processor
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
class SAMLProvider(Provider): class SAMLProvider(Provider):

View File

@ -1,6 +1,4 @@
"""passbook SAML IDP Views""" """passbook SAML IDP Views"""
from logging import getLogger
from django.contrib.auth import logout from django.contrib.auth import logout
from django.contrib.auth.mixins import AccessMixin from django.contrib.auth.mixins import AccessMixin
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
@ -13,6 +11,7 @@ from django.utils.translation import gettext as _
from django.views import View from django.views import View
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from signxml.util import strip_pem_header from signxml.util import strip_pem_header
from structlog import get_logger
from passbook.audit.models import AuditEntry from passbook.audit.models import AuditEntry
from passbook.core.models import Application from passbook.core.models import Application
@ -22,7 +21,7 @@ from passbook.policy.engine import PolicyEngine
from passbook.saml_idp import exceptions from passbook.saml_idp import exceptions
from passbook.saml_idp.models import SAMLProvider from passbook.saml_idp.models import SAMLProvider
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
URL_VALIDATOR = URLValidator(schemes=('http', 'https')) URL_VALIDATOR = URLValidator(schemes=('http', 'https'))

View File

@ -1,11 +1,11 @@
"""Functions for creating XML output.""" """Functions for creating XML output."""
from logging import getLogger from structlog import get_logger
from passbook.lib.utils.template import render_to_string from passbook.lib.utils.template import render_to_string
from passbook.saml_idp.xml_signing import get_signature_xml, sign_with_signxml from passbook.saml_idp.xml_signing import get_signature_xml, sign_with_signxml
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def _get_attribute_statement(params): def _get_attribute_statement(params):

View File

@ -1,14 +1,13 @@
"""Signing code goes here.""" """Signing code goes here."""
from logging import getLogger
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import serialization
from lxml import etree # nosec from lxml import etree # nosec
from signxml import XMLSigner, XMLVerifier from signxml import XMLSigner, XMLVerifier
from structlog import get_logger
from passbook.lib.utils.template import render_to_string from passbook.lib.utils.template import render_to_string
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def sign_with_signxml(private_key, data, cert, reference_uri=None): def sign_with_signxml(private_key, data, cert, reference_uri=None):

View File

@ -1,14 +1,13 @@
"""passbook suspicious request signals""" """passbook suspicious request signals"""
from logging import getLogger
from django.contrib.auth.signals import user_logged_in, user_login_failed from django.contrib.auth.signals import user_logged_in, user_login_failed
from django.dispatch import receiver from django.dispatch import receiver
from ipware import get_client_ip from ipware import get_client_ip
from structlog import get_logger
from passbook.core.models import User from passbook.core.models import User
from passbook.suspicious_policy.models import IPScore, UserScore from passbook.suspicious_policy.models import IPScore, UserScore
LOGGER = getLogger(__name__) LOGGER = get_logger(__name__)
def get_remote_ip(request): def get_remote_ip(request):