edx-oauth2-wordpress-backend/wp_oauth_backend/wp_oauth.py

77 lines
2.4 KiB
Python
Raw Normal View History

2022-10-03 19:46:35 +03:00
import json
from urllib.parse import urlencode
from urllib.request import urlopen
from social_core.backends.oauth import BaseOAuth2
from django.conf import settings
from logging import getLogger
logger = getLogger(__name__)
class WPOAuth2(BaseOAuth2):
"""WP OAuth authentication backend"""
2022-10-03 20:53:02 +03:00
name = 'wp-oauth'
2022-10-03 19:46:35 +03:00
SOCIAL_AUTH_SANITIZE_REDIRECTS = False
ACCESS_TOKEN_METHOD = 'POST'
EXTRA_DATA = []
SCOPE_SEPARATOR = ','
BASE_URL = "https://stepwisemath.ai"
2022-10-03 19:46:35 +03:00
@property
def base_url(self):
return self.BASE_URL
2022-10-03 19:46:35 +03:00
@property
def AUTHORIZATION_URL(self) -> str:
return f"{self.base_url}/oauth/authorize"
@property
def ACCESS_TOKEN_URL(self) -> str:
return f"{self.base_url}/oauth/token"
@property
def USER_QUERY(self) -> str:
return f"{self.base_url}/oauth/me"
def get_user_details(self, response):
"""Return user details from the WP account"""
user_details = {
'id': int(response.get('ID')),
'username': response.get('user_login'),
'email': response.get('user_email'),
'first_name': response.get("first_name", ""),
'last_name': response.get("last_name", ""),
2022-10-03 19:46:35 +03:00
'fullname': response.get('display_name'),
}
logger.info('get_user_details() - response: {response} user_details: {user_details}'.format(
response=json.dumps(response, sort_keys=True, indent=4),
user_details=json.dumps(user_details, sort_keys=True, indent=4)
))
2022-10-03 19:46:35 +03:00
return user_details
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
url = f'{self.USER_QUERY}?' + urlencode({
'access_token': access_token
})
try:
response = json.loads(self.urlopen(url))
logger.info('user_data() - response: {response}'.format(
response=json.dumps(response, sort_keys=True, indent=4)
))
return response
except ValueError as e:
logger.error('user_data() did not work: {err}'.format(err=e))
2022-10-03 19:46:35 +03:00
return None
def urlopen(self, url):
return urlopen(url).read().decode("utf-8")
# def get_user_id(self, details, response):
# return details['id']
2022-10-03 19:46:35 +03:00
# def get_username(self, strategy, details, backend, user=None, *args, **kwargs):
# return details['username']