Make secret settings actually work.
[tranquillity.git] / tranquillity / auth_backend.py
1 from django.contrib.auth import get_user_model
2 from django.contrib.auth.models import User
3 from django.contrib.auth.backends import ModelBackend
4 import requests
5 from django.conf import settings
6
7 class EmailBackend(ModelBackend):
8 def fetch_fortnox(self):
9 """ Fetch all active customers from Fortnox API. Return as dict keyed on email."""
10 res = None
11 customers = {}
12 headers = {"Access-Token":settings.FORTNOX_ACCESS_TOKEN,
13 "Client-Secret":settings.FORTNOX_CLIENT_SECRET,
14 "Content-Type":"application/json",
15 "Accept":"application/json" }
16
17 res = requests.get("https://api.fortnox.se/3/customers?filter=active", headers=headers)
18 for customer in res.json()['Customers']:
19 customers[customer['Email']] = customer
20 return customers
21
22 def authenticate(self, username=None, password=None, **kwargs):
23 UserModel = get_user_model()
24 try:
25 user = UserModel.objects.get(email=username)
26 except UserModel.DoesNotExist:
27 customers = self.fetch_fortnox()
28 if username in customers:
29 if ' ' in customers[username]['Name']:
30 (fname,lname) = customers[username]['Name'].split(' ',1)
31 user = User.objects.create_user(username=username,
32 email=username,
33 first_name=fname,
34 last_name=lname)
35 return user
36 else:
37 fname = customers[username]['Name']
38 user = User.objects.create_user(username=username,
39 email=username,
40 first_name=fname)
41 return user
42 return None
43 else:
44 if user.check_password(password):
45 return user
46 return None