]>
git.frykholm.com Git - tranquillity.git/blob - 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
6 except ModuleNotFoundError
as e
:
8 from django
.conf
import settings
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."""
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
)
22 res
['Customer'] = [res
['Customer']]
24 res
= requests
.get("https://api.fortnox.se/3/customers?filter=active", headers
=headers
)
26 for customer
in res
['Customer']:
27 customers
[customer
['Email']] = customer
30 def authenticate(self
, username
=None, password
=None, **kwargs
):
31 UserModel
= get_user_model()
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
,
43 fortnox_external_id
=int(customers
[username
]['CustomerNumber']))
46 fname
= customers
[username
]['Name']
47 user
= User
.objects
.create_user(username
=username
,
50 fortnox_external_id
=int(customers
[username
]['CustomerNumber']))
54 customer
= self
.fetch_fortnox(customer_id
=user
.fortnox_external_id
)
58 user
.first_name
= customer
[user
.email
]['Name'] #TODO synd more data
60 if user
.check_password(password
):