X-Git-Url: https://git.frykholm.com/tranquillity.git/blobdiff_plain/93be18536faaa33c9c2d3a4e5625fa7bfca8eb20..40e726c7920217dc583a6f23b9ff0d5c8e1c801e:/tranquillity/auth_backend.py diff --git a/tranquillity/auth_backend.py b/tranquillity/auth_backend.py index e8c682a..de43992 100644 --- a/tranquillity/auth_backend.py +++ b/tranquillity/auth_backend.py @@ -1,11 +1,14 @@ from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend -import requests +try: + import requests +except ModuleNotFoundError as e: + pass from django.conf import settings class EmailBackend(ModelBackend): - def fetch_fortnox(self): + def fetch_fortnox(self, customer_id=None): """ Fetch all active customers from Fortnox API. Return as dict keyed on email.""" res = None customers = {} @@ -13,9 +16,14 @@ class EmailBackend(ModelBackend): "Client-Secret":settings.FORTNOX_CLIENT_SECRET, "Content-Type":"application/json", "Accept":"application/json" } - - res = requests.get("https://api.fortnox.se/3/customers?filter=active", headers=headers) - for customer in res.json()['Customers']: + 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 @@ -25,22 +33,30 @@ class EmailBackend(ModelBackend): 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(username=username, - email=username, + user = User.objects.create_user(email=username, first_name=fname, - last_name=lname) + 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) + 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