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