54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
import random
|
|
from time import time
|
|
from oauth2_provider.oauth2_validators import OAuth2Validator
|
|
|
|
from django.contrib.auth import get_user_model
|
|
|
|
USER_MODEL = get_user_model()
|
|
|
|
|
|
def random_code(pre_len=5, post_len=5):
|
|
code = str(time())[:pre_len] + ''.join(random.choice('0123456789') for _ in range(post_len))
|
|
return code
|
|
|
|
|
|
class MultiGatewayOAuth2Validator(OAuth2Validator): # pylint: disable=w0223
|
|
""" Primarily extend the functionality of token generation """
|
|
|
|
def validate_user(self, username, password, client, request, *args, **kwargs):
|
|
""" Here, you would be able to access the MOBILE/ OTP fields
|
|
which you will be sending in the request.post body. """
|
|
# otp = request.otp
|
|
# mobile = request.mobile
|
|
# user = AppropriateModel.objects.get(otp=otp, mobile=mobile)
|
|
auth_gateway = getattr(request, 'auth_gateway', 'username:password').split(':')
|
|
user_gateway = auth_gateway[0]
|
|
pass_gateway = auth_gateway[1]
|
|
|
|
user = None
|
|
if user_gateway == 'phone_number':
|
|
user = USER_MODEL.objects.get(
|
|
phone_number=username
|
|
)
|
|
|
|
elif auth_gateway == 'username':
|
|
user = USER_MODEL.objects.get(
|
|
username=username
|
|
)
|
|
|
|
elif user_gateway == 'email':
|
|
user = USER_MODEL.objects.get(
|
|
email=username
|
|
)
|
|
|
|
if user is None:
|
|
return False
|
|
|
|
if not user.check_auth(pass_gateway, password):
|
|
return False
|
|
|
|
if user.is_active:
|
|
request.user = user
|
|
return True
|
|
|
|
return False
|