several changes on auth flow
[osm/LW-UI.git] / authosm / backend.py
index 1b92156..6c23e91 100644 (file)
 #   See the License for the specific language governing permissions and
 #   limitations under the License.
 #
-from .models import OsmUser
+from django.core.exceptions import PermissionDenied
 
+from .models import OsmUser
+from lib.osm.osmclient.clientv2 import Client
+from .exceptions import OSMAuthException
 
 class OsmBackend(object):
 
@@ -26,20 +29,31 @@ class OsmBackend(object):
         if all(k in kwargs for k in ('username', 'password', 'project_id')):
             username = kwargs['username']
             password = kwargs['password']
-            project_id = kwargs['project_id']
 
-            print username
-            print password
-            print project_id
+            client = Client()
+            result = client.auth(kwargs)
+
+            if 'error' in result and result['error'] is True:
+                raise OSMAuthException(result['data'])
+            else:
+
+                try:
+                    user = OsmUser.objects.get(username=username)
+                    user.psw = password
+                    user.token=result['data']['id']
+                    user.project_id=result['data']['project_id']
+                    user.token_expires=result['data']['expires']
+                    user.session = result['data']
+                    user.save()
+
+                except OsmUser.DoesNotExist:
+                    user = OsmUser(username=username, psw=password, token=result['data']['id'],
+                                                       project_id=result['data']['project_id'],
+                                                       token_expires=result['data']['expires'])
+                    user.session = result['data']
+                    user.save()
 
-            try:
 
-                return OsmUser.objects.get(username=username)
-            except OsmUser.DoesNotExist:
-                # Create a new user. There's no need to set a password
-                # we will keep just some preferences
-                user = OsmUser(username=username)
-                user.save()
                 return user
 
         return None