From d1f79ec89f8d20836d3ba11760a8ad2f1bbc6b68 Mon Sep 17 00:00:00 2001 From: Mikael Frykholm Date: Mon, 14 May 2018 13:05:13 +0200 Subject: [PATCH] Added initial fortnox api client. --- .gitignore | 1 + tranquillity/auth_backend.py | 31 +++++++++++++++++++++++++++++++ tranquillity/settings.py | 1 + 3 files changed, 33 insertions(+) diff --git a/.gitignore b/.gitignore index c1cc933..1fe043a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ __pycache__/ *.py[cod] /db.sqlite3 +/tranquillity/settings_secret.py diff --git a/tranquillity/auth_backend.py b/tranquillity/auth_backend.py index 44edaee..bd410d1 100644 --- a/tranquillity/auth_backend.py +++ b/tranquillity/auth_backend.py @@ -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): diff --git a/tranquillity/settings.py b/tranquillity/settings.py index cc33677..74d30b0 100644 --- a/tranquillity/settings.py +++ b/tranquillity/settings.py @@ -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__))) -- 2.39.2