Skip to content

Instantly share code, notes, and snippets.

@leoluk
Created January 24, 2019 19:46
Show Gist options
  • Save leoluk/16d91ec22d833945c7ac7ed2b3b05a27 to your computer and use it in GitHub Desktop.
Save leoluk/16d91ec22d833945c7ac7ed2b3b05a27 to your computer and use it in GitHub Desktop.
Netbox OAuth Login
"""
Custom LOGIN_REQUIRED middleware which allows OAuth URLs.
"""
import utilities.middleware
from django.conf import settings
class CustomLoginRequiredMiddleware(utilities.middleware.LoginRequiredMiddleware):
def __call__(self, request):
if settings.LOGIN_REQUIRED and not request.user.is_authenticated:
if request.path_info.startswith('/oauth/'):
return self.get_response(request)
return super(CustomLoginRequiredMiddleware, self).__call__(request)
"""
Override upstream urls.py for OAuth login
"""
from netbox.urls import *
urlpatterns = urlpatterns + [
url(r'^oauth/', include('social_django.urls', namespace='social')),
]
"""
Override the Netbox settings.py for customizations outside of configuration.py.
"""
import os
from netbox.upstream_settings import *
# OAuth monkey patching
MIDDLEWARE = [
'netbox.custom_middleware.CustomLoginRequiredMiddleware' if
x == 'utilities.middleware.LoginRequiredMiddleware' else x
for x in MIDDLEWARE]
AUTHENTICATION_BACKENDS = (
'foo.CustomOAuthProvider',
)
SOCIAL_AUTH_FOO_ADMIN_KEY = os.getenv('FOO_OAUTH_CLIENT', '')
SOCIAL_AUTH_FOO_ADMIN_SECRET = os.getenv('FOO_OAUTH_SECRET', '')
LOGIN_URL = '/oauth/login/foo-admin/'
ROOT_URLCONF = 'netbox.custom_urls'
INSTALLED_APPS = INSTALLED_APPS + [
'social_django',
]
SOCIAL_AUTH_POSTGRES_JSONFIELD = True
# Custom Netbox modifications
mv netbox/netbox/settings.py netbox/netbox/upstream_settings.py
cp /opt/app-root/etc/settings.py netbox/netbox/settings.py
cp /opt/app-root/etc/custom_urls.py netbox/netbox/custom_urls.py
cp /opt/app-root/etc/custom_middleware.py netbox/netbox/custom_middleware.py
@dwrusse
Copy link

dwrusse commented May 21, 2020

Thanks for this! Any idea if and how we can set a default group for new users with this method?

@leoluk
Copy link
Author

leoluk commented May 21, 2020

That depends on the auth backend you're using. For django-social-auth, you'd want to listen for the new user signal and assign a group: https://stackoverflow.com/questions/23482652/add-users-logged-in-through-python-social-auth-to-a-group

@dwrusse
Copy link

dwrusse commented May 22, 2020

Thanks again! I'm using mozilla-django-oidc, but this led me the in the right direction!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment