| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.socialaccount.providers.base import AuthAction, ProviderAccount |
| 6 |
from allauth.socialaccount.providers.microsoft.views import MicrosoftGraphOAuth2Adapter |
| 7 |
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider |
| 8 |
|
| 9 |
|
| 10 |
class MicrosoftGraphAccount(ProviderAccount): |
| 11 |
def get_avatar_url(self): |
| 12 |
return self.account.extra_data.get("photo") |
| 13 |
|
| 14 |
|
| 15 |
class MicrosoftGraphProvider(OAuth2Provider): |
| 16 |
id = "microsoft" |
| 17 |
name = "Microsoft" |
| 18 |
account_class = MicrosoftGraphAccount |
| 19 |
oauth2_adapter_class = MicrosoftGraphOAuth2Adapter |
| 20 |
|
| 21 |
def get_default_scope(self): |
| 22 |
""" |
| 23 |
Docs on Scopes and Permissions: |
| 24 |
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#scopes-and-permissions |
| 25 |
""" |
| 26 |
return ["User.Read"] |
| 27 |
|
| 28 |
def get_auth_params_from_request(self, request: HttpRequest, action): |
| 29 |
ret = super().get_auth_params_from_request(request, action) |
| 30 |
if action == AuthAction.REAUTHENTICATE: |
| 31 |
ret["prompt"] = "select_account" |
| 32 |
return ret |
| 33 |
|
| 34 |
def extract_uid(self, data): |
| 35 |
return str(data["id"]) |
| 36 |
|
| 37 |
def extract_common_fields(self, data): |
| 38 |
return dict( |
| 39 |
email=data.get("mail") or data.get("userPrincipalName"), |
| 40 |
username=data.get("mailNickname"), |
| 41 |
last_name=data.get("surname"), |
| 42 |
first_name=data.get("givenName"), |
| 43 |
) |
| 44 |
|
| 45 |
|
| 46 |
provider_classes = [MicrosoftGraphProvider] |