How to use django-oauth-toolkit to protect a package's API - python

I'm developing a web API using "django-scim2" package.
As a development requirement, bearer token authentication is required when accessing the django-scim2 API via http.
The django-scim2 documentation (https://django-scim2.readthedocs.io/en/latest/) says "This app does not implement authorization and authentication. Such tasks are left for other apps such as Django OAuth Toolkit to implement."
And as I check the django-oauth-toolkit docs, I can see how to protect it when you create a function or class,
https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/function_based.html
https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/class_based.html
but django-scim2 is loaded from config/urls.py as it is (like below), so I have nothing to do and I don't know how to implement it.
[config/urls.py]
urlpatterns = [
path('admin/', admin.site.urls),
path('scim/v2/', include('django_scim.urls', namespace='scim')),
...
I would be grateful if you could give me some good advice.

Related

how to use django 3 with django-otp to send token sms using SMS service provider for user verification and redirecting to password reset form?

I have only been able to make the following changes in django code:
settings.py:
added along with other apps added in
INSTALLED_APPS = [
.....
'django_otp',
'django_otp.plugins.otp_totp',
]
In additions to other middleware configurations, added:
MIDDLEWARE = [
'django_otp.middleware.OTPMiddleware',
]
urls.py:
from django_otp.admin import OTPAdminSite
from django_otp.plugins.otp_totp.models import TOTPDevice
admin_site = OTPAdmin(name='OTPAdmin')
admin_site.register(User)
admin_site.register(TOTPDevice)
urlpatterns = [
path('admin/', admin_site.urls), #otp app
path('dadmin/', admin.site.urls),
]
Then I ran: $ python3 manage.py migrate otp_totp --fake
and runserver. Created a user and totp device. Scanned the qr code in google authenticator. Then tried logging in using the admin url to login for this new user. It asks for the token generated which I input, it says invalid token though user is authenticated. Seen other posts where the secret code needs to be converted to 32basecode etc, but don't know exactly and where to implement. What more code needs to be added to get this working? I will require detailed code and steps for my use case where i need to change the time for generating the code and send via sms using my service provider api and redirect to password reset form.
Using django 3.1, django-otp 1.0.2
My google authenticator works with my gmail account, so there is no clock time difference either.

How to restrict the login google api with specific domain name only?

I'm creating a web application which I'm using Google API for authentication. Also, the library that I've applied was social-auth-app-django. Then, my goal is to allow only specific domain name like user#example.com with a domain of example.com.
Upon reading its documentation this line of code should be added to settings.py SOCIAL_AUTH__WHITELISTED_DOMAINS = ['foo.com', 'bar.com'] however, it is not working to me.
settings.py configuration
AUTHENTICATION_BACKENDS = (
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['example.com.hk']
How can I restrict the google api to only allow the specified whitelisted domains?
You have to add and specify the authorize domains to your google API credentials.

Django rest - Custom authentication backend with browsable api

I am using Django 1.11 and Django rest framework 3.6.2
I created a custom authentication backend:
MyAuthBackend(rest_framework.authentication.BasicAuthentication):
# ...
and added it to the settings.py file:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES' : ('path.to.MyAuthBackend',)
}
I also tried to extend SessionAuthentication without success
My issue is that users are trying to log in via the browsable api and it looks like the authentication backend that the browsable api is using is not the default one.
Where can I change that? I have to use my own auth backend in the browsable api,
Thank you.
I don't think it's possible to use BasicAuthentication in the browseable api (without changing a whole bunch of its internals).
Consider keeping the SessionAuthentication alongside your new one, you can use basic authentication in your app and session authentication in the browsable api:
'DEFAULT_AUTHENTICATION_CLASSES': (
'path.to.MyAuthBackend',
'rest_framework.authentication.SessionAuthentication',
),

django-allauth, how can I only allow signup/login through social?

I only want to allow people to sign up or log in with their social account. I have the social sign up and log in working, but I cant figure out how to disable the local sign up.
I've read the docs and this sounds close to what I want
ACCOUNT_FORMS (={})
Used to override forms, for example: {‘login’: ‘myapp.forms.LoginForm’}
It seems like I can make a new sign up form and only include the social log in link, but I was hoping there is any easier way that I'm overlooking. I'm still new to this all so I tend to miss the obvious a lot still.
I also tried changing the code below to False, but that disabled social sign up as well.
allauth.account.adapter.py
def is_open_for_signup(self, request):
"""
Checks whether or not the site is open for signups.
Next to simply returning True/False you can also intervene the
regular flow by raising an ImmediateHttpResponse
"""
return True
Change templates and urlpatterns
You would have to change both the templates (login, signup, etc.) and urlpatterns provided by allauth by default, which relate to the classic signup/login flow using email.
Changing/reducing the available routes via the urlpatterns ensures that only the routes are available that should be there. HTTP error 404 is then shown for any attempt to hack into existing allauth default functionality (related to email) if you do it right.
Changing the templates can ensure that the user interface does not provide what is related to email-based authentication.
No easy option available
Unfortunately, as of today there is no easy switch or setting to simply disable email-based signup and authentication with django-allauth. More details may be on GitHub in future, see:
Issue #1227 ("Social only: disable all local account handling by means of a simple setting")
Issue #345 ("How to disable form login/signup?")
Sample: urls.py
An urls.py like this will work with the current django-allauth (v0.30.0) on Django 1.10:
from django.conf.urls import include, url
from allauth.account.views import confirm_email, login, logout
from allauth.compat import importlib
from allauth.socialaccount import providers
providers_urlpatterns = []
for provider in providers.registry.get_list():
prov_mod = importlib.import_module(provider.get_package() + '.urls')
providers_urlpatterns += getattr(prov_mod, 'urlpatterns', [])
urlpatterns = [
url(r'^auth/', include(providers_urlpatterns)),
url(r'^confirm-email/(?P<key>[-:\w]+)/$', confirm_email, name='account_confirm_email'),
url(r'^login/$', login, name='account_login'),
url(r'^logout/$', logout, name='account_logout'),
url(r'^signup/$', login, name='account_signup'), # disable email signup
]
The solution wasn't what I originally thought. The much easier way to do this, instead of changing the forms, was to change the template and just remove any other options in that template.
My page now correctly only shows social auth and I am happy.
If anyone has a better or more secure answer I'd be open to it. Being new still, I don't know if this is the best solution, but for now it seems great and will mark as answered.
Ok, here is the thing. If you are not using any social account to link to your users, then it's very simple to finish the task you described by simply only include urls you need. However, if you need to use social account to link your users, then you have to include all urls because most third party application will not certify the request from your app. they only accept request from allauth.
from django.urls import path, re_path
from allauth.account import views as accountviews
urlpatterns = [
path('admin/', admin.site.urls),
# remember to comment out the following line since it will
# include all urls from allauth lib
# path('accounts/', include('allauth.urls'))
]
# assume you only want singup page and login page from allauth
urlpatterns += [path("acc/signup/", accountviews.signup, name="account_signup"),
path("acc/login/", accountviews.login, name="account_login")
]

Python Django 1.6 execute function for every request before getting to view

I'm writing some API functionality for my project using Python 3.4 and Django 1.6.
All functionality works fine, but I want execute one function for all that kind of requests.
For Example: I have following urls.py file in my API application in Django project
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^getposts', 'Postigs.views.get_posts', name='getPosts'),
url(r'^addpost', 'Postigs.views.add_post', name='addPost'),
url(r'^addcomment', 'Postigs.views.add_comment', name='addComment'),
)
And views.py for that URL requests handling.
So is it possible to execute some function for Example:
def pre_execute(request):
do_something_before_view_function()
I've worked before with many PHP frameworks , there are always some pre_execute() function ... also I've worked with ASP.NET MVC , Node.js Express.js , and all have that function which is firing before request action.
I don't believe that Django didn't have it , but I can't find how implement that functionality.
Thanks.
Middlewares are what you want: https://docs.djangoproject.com/en/dev/topics/http/middleware/
example middleware: https://github.com/django/django/blob/master/django/middleware/common.py
Like iskorum mentioned above, Middlewares is the answer. Or there is also a chance that you are looking for View Decorators. Here is the link https://docs.djangoproject.com/en/dev/topics/http/decorators/

Categories