Skip to content

Instantly share code, notes, and snippets.

@simo97
Last active January 28, 2022 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simo97/cb9ddcf706d68cff8df1d0a17ef91c43 to your computer and use it in GitHub Desktop.
Save simo97/cb9ddcf706d68cff8df1d0a17ef91c43 to your computer and use it in GitHub Desktop.
from fusionauth.fusionauth_client import FusionAuthClient
class FusionAuthBackend:
def authenticate(username: str, password: str, *args, **kwargs):
# fusionauth_client.
client = FusionAuthClient(settings.FUSION_AUTH_API_KEY, settings.FUSION_AUTH_BASE_URL)
_tenant_id = settings.FUSION_AUTH_MAIN_TENANT_ID
if _tenant_id != "":
client.set_tenant_id(settings.FUSION_AUTH_MAIN_TENANT_ID)
login_data = {
"loginId": username,
"password": password,
"applicationId": settings.FUSION_AUTH_APP_ID,
"noJWT": True,
}
response = client.login(login_data)
_status = response.status
if 200 >= _status <= 299:
return get_or_create_user(response.success_response["user"]["email"])
if _status > 299 :
return None
def get_or_create_user(user_id, first_name='', last_name='', middle_name='', *args, **kwargs):
"""
Get or create a local user from fusionauth's information. Mostly used for local user federation.
You can actually add more code here to support and make various authentication actions, for example
to implement a work around the fact that FA don't support yet users having more than one email address.
:param user_id:
:param first_name:
:param last_name:
:param middle_name:
:return:
"""
from django.db.models import Q
User = get_user_model()
user_qs = User.objects.filter(
Q(email=user_id)
)
if user_qs.exists():
return user_qs.first()
# if not user:
user = User(
email=user_id , first_name=first_name ,
last_name=last_name , **kwargs
)
# todo: create the mail here
user.save()
return user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment