from django.contrib.auth import get_user_model
+from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
+import requests
class EmailBackend(ModelBackend):
+ def fetch_fortnox(self):
+ """ Fetch all active customers from Fortnox API. Return as dict keyed on email."""
+ res = None
+ customers = {}
+ headers = {"Access-Token":FORTNOX_Access_Token,
+ "Client-Secret":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']:
+ 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()
+ 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,
+ first_name=fname,
+ last_name=lname)
+ return user
+ else:
+ fname = customers[username]['Name']
+ user = User.objects.create_user(username=username,
+ email=username,
+ first_name=fname)
+ return user
return None
else:
if user.check_password(password):