9c316a93152b5c6ead7a99525056e17cb30c2bbb
[osm/LW-UI.git] / authosm / backend.py
1 #
2 # Copyright 2018 EveryUP Srl
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 from django.core.exceptions import PermissionDenied
17
18 from .models import OsmUser
19 from lib.osm.osmclient.clientv2 import Client
20 from .exceptions import OSMAuthException
21
22
23 class OsmBackend(object):
24 def authenticate(self, **kwargs):
25 '''
26 kwargs will receive the python dict that may contain
27 {username, password, project-id} to authenticate
28 '''
29 if all(k in kwargs for k in ('username', 'password', 'project_id')):
30 username = kwargs['username']
31 password = kwargs['password']
32
33 client = Client()
34 result = client.auth(kwargs)
35
36 if 'error' in result and result['error'] is True:
37 raise OSMAuthException(result['data'])
38 else:
39
40 try:
41 user = OsmUser.objects.get(username=username)
42 user.psw = password
43 user.token = result['data']['id']
44 user.project_id = result['data']['project_id']
45 user.token_expires = result['data']['expires']
46 user.is_admin = bool(result['data']['admin'])
47 user.save()
48 except OsmUser.DoesNotExist:
49 user = OsmUser(username=username, psw=password, token=result['data']['id'],
50 project_id=result['data']['project_id'],
51 token_expires=result['data']['expires'], is_admin=result['data']['admin'])
52 user.save()
53
54 return user
55
56 return None
57
58 def get_user(self, user_id):
59 try:
60 return OsmUser.objects.get(pk=user_id)
61 except OsmUser.DoesNotExist:
62 return None