X-Git-Url: https://git.frykholm.com/tranquillity.git/blobdiff_plain/26235f08dc5391137a93f77ff145a3a69e002de3..HEAD:/tranquillity/auth_backend.py diff --git a/tranquillity/auth_backend.py b/tranquillity/auth_backend.py index 44edaee..de43992 100644 --- a/tranquillity/auth_backend.py +++ b/tranquillity/auth_backend.py @@ -1,14 +1,62 @@ from django.contrib.auth import get_user_model +from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend +try: + import requests +except ModuleNotFoundError as e: + pass +from django.conf import settings class EmailBackend(ModelBackend): + def fetch_fortnox(self, customer_id=None): + """ Fetch all active customers from Fortnox API. Return as dict keyed on email.""" + res = None + customers = {} + headers = {"Access-Token":settings.FORTNOX_ACCESS_TOKEN, + "Client-Secret":settings.FORTNOX_CLIENT_SECRET, + "Content-Type":"application/json", + "Accept":"application/json" } + if customer_id: #We already have id, use that to update info in local db + res = requests.get(f"https://api.fortnox.se/3/customers/{customer_id}?filter=active", headers=headers) + res = res.json() + res['Customer'] = [res['Customer']] + else: + res = requests.get("https://api.fortnox.se/3/customers?filter=active", headers=headers) + + for customer in res['Customer']: + customers[customer['Email']] = customer + return customers + def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: + customers = self.fetch_fortnox() + # import pdb;pdb.set_trace() + if username in customers: + if ' ' in customers[username]['Name']: + (fname,lname) = customers[username]['Name'].split(' ',1) + user = User.objects.create_user(email=username, + first_name=fname, + last_name=lname, + fortnox_external_id=int(customers[username]['CustomerNumber'])) + return user + else: + fname = customers[username]['Name'] + user = User.objects.create_user(username=username, + email=username, + first_name=fname, + fortnox_external_id=int(customers[username]['CustomerNumber'])) + return user return None else: + customer = self.fetch_fortnox(customer_id=user.fortnox_external_id) + if not customer: + user.is_active=False + return None + user.first_name = customer[user.email]['Name'] #TODO synd more data + user.save() if user.check_password(password): return user return None