0

I'm trying to limit the access to a page only to logged users. I used the google authentication, but it let every account to log in; instead i want to avoid every domains different from 'fermi.mo.it'. A google account like luca@gmail.com shouldn't be able to login, while an account like luca@fermi.mo.it should be able to.

I noticed this code to make it, but it doesnt work. It says: "No module named 'social_core'" but i installed it.

AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['fermi.mo.it']

These are all the modules that i installed:

Jony_23
  • 322
  • 4
  • 12
Luca
  • 11
  • 1

2 Answers2

0

If django is not able to find the module, make sure that you have added the 'social_django' ro installed apps.

Other soution is that you can create a validator at level Serializer or model according you. Which of them choose? That's other topic.

  1. Django Model field validation vs DRF Serializer field validation
  2. How to validate against full model data in DjangoREST Framework

You only have to check if the email contains the string 'fermi.mo.it'. If don't, raise and exception.

The documentation of each one: Django Validators and Validators DRF.

Jony_23
  • 322
  • 4
  • 12
  • Oh, i didn't add social_django. Anyway now it doesn't throw an exception even if the domain is different from fermi.mo.it, everyone can login :( I haven't tried the second solution yet because the first one seems to be easier to implement – Luca May 01 '22 at 14:15
0

I can see that OP has already installed the app

pip install social-auth-app-django

So, now OP needs to

1 Ensure one has added the application to INSTALLED_APPS setting

INSTALLED_APPS = (
    ...
    'social_django',
    ...
)

2 After that, sync the database to create needed models

./manage.py migrate

3 Then, one wants to limit the emails that Google shows in the list

SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {
        'hd': 'fermi.mo.it'
    }

4 Finally, one wants to limit the emails that can sign in

SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['fermi.mo.it']
Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83