Added initial fortnox api client.
authorMikael Frykholm <mikael@frykholm.com>
Mon, 14 May 2018 11:05:13 +0000 (13:05 +0200)
committerMikael Frykholm <mikael@frykholm.com>
Mon, 14 May 2018 11:05:13 +0000 (13:05 +0200)
.gitignore
tranquillity/auth_backend.py
tranquillity/settings.py

index c1cc933..1fe043a 100644 (file)
@@ -1,3 +1,4 @@
 __pycache__/
 *.py[cod]
 /db.sqlite3
+/tranquillity/settings_secret.py
index 44edaee..bd410d1 100644 (file)
@@ -1,12 +1,43 @@
 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):
index cc33677..74d30b0 100644 (file)
@@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/2.0/ref/settings/
 """
 
 import os
+from settings_secret import *
 
 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))