]> git.frykholm.com Git - tranquillity.git/blob - tranquillity/auth_backend.py
Djangocon coding
[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 try:
5 import requests
6 except ModuleNotFoundError as e:
7 pass
8 from django.conf import settings
9
10 class EmailBackend(ModelBackend):
11 def fetch_fortnox(self, customer_id=None):
12 """ Fetch all active customers from Fortnox API. Return as dict keyed on email."""
13 res = None
14 customers = {}
15 headers = {"Access-Token":settings.FORTNOX_ACCESS_TOKEN,
16 "Client-Secret":settings.FORTNOX_CLIENT_SECRET,
17 "Content-Type":"application/json",
18 "Accept":"application/json" }
19 if customer_id: #We already have id, use that to update info in local db
20 res = requests.get(f"https://api.fortnox.se/3/customers/{customer_id}?filter=active", headers=headers)
21 res = res.json()
22 res['Customer'] = [res['Customer']]
23 else:
24 res = requests.get("https://api.fortnox.se/3/customers?filter=active", headers=headers)
25
26 for customer in res['Customer']:
27 customers[customer['Email']] = customer
28 return customers
29
30 def authenticate(self, username=None, password=None, **kwargs):
31 UserModel = get_user_model()
32 try:
33 user = UserModel.objects.get(email=username)
34 except UserModel.DoesNotExist:
35 customers = self.fetch_fortnox()
36 # import pdb;pdb.set_trace()
37 if username in customers:
38 if ' ' in customers[username]['Name']:
39 (fname,lname) = customers[username]['Name'].split(' ',1)
40 user = User.objects.create_user(email=username,
41 first_name=fname,
42 last_name=lname,
43 fortnox_external_id=int(customers[username]['CustomerNumber']))
44 return user
45 else:
46 fname = customers[username]['Name']
47 user = User.objects.create_user(username=username,
48 email=username,
49 first_name=fname,
50 fortnox_external_id=int(customers[username]['CustomerNumber']))
51 return user
52 return None
53 else:
54 customer = self.fetch_fortnox(customer_id=user.fortnox_external_id)
55 if not customer:
56 user.is_active=False
57 return None
58 user.first_name = customer[user.email]['Name'] #TODO synd more data
59 user.save()
60 if user.check_password(password):
61 return user
62 return None