Skip to content
This repository has been archived by the owner on May 14, 2021. It is now read-only.

Commit

Permalink
Merge pull request #2 from OfficineArduinoTorino/doorsaredevices
Browse files Browse the repository at this point in the history
Doors are devices
  • Loading branch information
mastrolinux authored Jan 25, 2017
2 parents 320c58d + 5af99cc commit 5e04d9c
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 101 deletions.
2 changes: 1 addition & 1 deletion labAdmin/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def subscription(self, obj):
admin.site.register(UserProfile, UserProfileAdmin)

class RoleAdmin(admin.ModelAdmin):
list_display = ('name', 'role_kind','valid',)
list_display = ('name', 'valid',)
ordering = ('name',)

admin.site.register(Role, RoleAdmin)
Expand Down
19 changes: 19 additions & 0 deletions labAdmin/migrations/0007_remove_role_role_kind.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-18 19:12
from __future__ import unicode_literals

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('labAdmin', '0006_device_token'),
]

operations = [
migrations.RemoveField(
model_name='role',
name='role_kind',
),
]
49 changes: 3 additions & 46 deletions labAdmin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,10 @@ def subscription_end(self):
def subscriptionExpired(self):
return self.needSubscription and self.endSubscription < timezone.now()

def can_open_door_now(self):
roles = self.groups.values_list('roles__pk', flat=True).distinct()
return TimeSlot.objects.can_now().filter(
role__in=roles, role__role_kind=0, role__valid=True
).exists()

def can_use_device_now(self, device):
roles = self.groups.values_list('roles__pk', flat=True).distinct()
return TimeSlot.objects.can_now().filter(
role__in=roles, role__role_kind=1, role__valid=True
role__in=roles, role__valid=True, role__categories=device.category
).exists()

def displaygroups(self):
Expand All @@ -128,57 +122,20 @@ class Group(models.Model):
# define Many-To-Many fields
roles=models.ManyToManyField('Role')

def can_open_door_now(self):
# Define groups and role
try:
return TimeSlot.objects.can_now().filter(role__group=self,role__role_kind=0,role__valid=True).exists()
except:
# Any Exception return False
return False

def can_use_device_now(self, device):
try:
return TimeSlot.objects.can_now().filter(role__group=self,role__role_kind=1, role__category_device=device.category_device, role__valid=True).exists()
except:
# Any Exception return False
return False

def __str__(self):
return "%s" % (self.name)
return self.name

class Role(models.Model):
# define role kind choices
ROLE_KIND_CHOICES = (
(0, "Door Access"),
(1, "Use Device"),
)

name=models.CharField(max_length=50)

role_kind=models.IntegerField(choices=ROLE_KIND_CHOICES)
time_slots=models.ManyToManyField(TimeSlot)
valid=models.BooleanField(default=True)

# define Many-To-Many Fieds
categories=models.ManyToManyField('Category',blank=True)

def can_open_door_now(self):
# Define groups and role
try:
return TimeSlot.objects.can_now().filter(role=self, role__role_kind=0,role__valid=True).exists()
except:
# Any Exception return False
return False

def can_use_device_now(self, device):
try:
return TimeSlot.objects.can_now().filter(role=self, role__role_kind=1, role__category_device=device.category_device, role__valid=True).exists()
except:
# Any Exception Return False
return False

def __str__(self):
return "%s - %s" % (self.name, self.ROLE_KIND_CHOICES[self.role_kind][1])
return self.name

class Device(models.Model):
name = models.CharField(max_length=100)
Expand Down
92 changes: 55 additions & 37 deletions labAdmin/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,14 @@
from django.utils import timezone, dateparse

from .models import (
Card, Group, LogAccess, Role, TimeSlot, UserProfile, TimeSlot,
Card, Group, LogAccess, Role, TimeSlot, UserProfile,
LogCredits, Category, Device, LogDevice
)


class TestLabAdmin(TestCase):
@classmethod
def setUpTestData(cls):
daily_timeslot = TimeSlot.objects.create(
name="thursday full day",
weekday_start=4,
weekday_end=4,
hour_start=dateparse.parse_time("8:0:0"),
hour_end=dateparse.parse_time("23:0:0"),
)
reduced_timeslot = TimeSlot.objects.create(
name="thursday reduced",
weekday_start=4,
weekday_end=4,
hour_start=dateparse.parse_time("14:0:0"),
hour_end=dateparse.parse_time("20:0:0"),
)
full_timeslot = TimeSlot.objects.create(
name="any day",
weekday_start=1,
Expand All @@ -37,28 +23,11 @@ def setUpTestData(cls):
hour_end=dateparse.parse_time("23:59:59"),
)

fablab_role = Role.objects.create(
name="Fablab Access",
role_kind=0
)
fablab_role.time_slots.add(daily_timeslot)

guest_role = Role.objects.create(
name="Guest Access",
role_kind=0
)
guest_role.time_slots.add(reduced_timeslot)

full_devices_role = Role.objects.create(
name="Devices Access",
role_kind=1
)
full_devices_role.time_slots.add(full_timeslot)

fab_guest_group = Group.objects.create(name="Fablab Guest")
fab_guest_group.roles.add(fablab_role, guest_role)
guest_group = Group.objects.create(name="Guest")
guest_group.roles.add(guest_role)
devices_group = Group.objects.create(name="Full Devices access")
devices_group.roles.add(full_devices_role)

Expand All @@ -71,7 +40,6 @@ def setUpTestData(cls):
needSubscription=False,
endSubscription=timezone.now()
)
u.groups.add(guest_group)
u.groups.add(devices_group)

noperm_card = Card.objects.create(nfc_id=654321)
Expand All @@ -87,6 +55,7 @@ def setUpTestData(cls):
category = Category.objects.create(
name="category"
)
full_devices_role.categories.add(category)

device = Device.objects.create(
name="device",
Expand Down Expand Up @@ -129,11 +98,12 @@ def test_open_door_by_nfc(self):
self.assertFalse(LogAccess.objects.all().exists())

client = Client()
auth = 'Token {}'.format(self.device.token)
url = reverse('open-door-nfc')
data = {
'nfc_id': self.card.nfc_id
}
response = client.post(url, data, format='json')
response = client.post(url, data, format='json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 201)
response_data = json.loads(str(response.content, encoding='utf8'))
self.assertIn('users', response_data)
Expand All @@ -143,19 +113,22 @@ def test_open_door_by_nfc(self):
self.assertEqual(user_profile['name'], self.userprofile.name)
self.assertEqual(response_data['type'], 'other')
self.assertIn('datetime', response_data)
self.assertEqual(response_data['open'], self.userprofile.can_open_door_now())
self.assertEqual(response_data['open'], self.userprofile.can_use_device_now(self.device))

users = UserProfile.objects.all()
logaccess = LogAccess.objects.filter(users=users, card=self.card)
self.assertTrue(logaccess.exists())

response = client.post(url, data, format='json')
self.assertEqual(response.status_code, 403)

data = {
'nfc_id': 0
}
response = client.post(url, data, format='json')
response = client.post(url, data, format='json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 400)

response = client.get(url)
response = client.get(url, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 405)

def test_timeslot_manager_now(self):
Expand Down Expand Up @@ -480,3 +453,48 @@ def test_device_stop_use(self):
self.assertJSONEqual(response.content.decode('utf-8'), {
'cost': 0
})

def test_user_can_use_device_now(self):
self.assertTrue(self.userprofile.can_use_device_now(self.device))

def test_user_can_use_device_now_invalid_role(self):
timeslot = TimeSlot.objects.create(
name="any day for invalid role",
weekday_start=1,
weekday_end=7,
hour_start=dateparse.parse_time("00:00:00"),
hour_end=dateparse.parse_time("23:59:59"),
)

role = Role.objects.create(
name="invalid role",
valid=False
)
role.time_slots.add(timeslot)

group = Group.objects.create(name="group with invalid role")
group.roles.add(role)
self.noperm_userprofile.groups.add(group)
self.assertFalse(self.noperm_userprofile.can_use_device_now(self.device))

def test_user_can_use_device_now_no_group(self):
self.assertFalse(self.noperm_userprofile.can_use_device_now(self.device))

def test_user_can_use_device_role_not_categories(self):
timeslot = TimeSlot.objects.create(
name="any day",
weekday_start=1,
weekday_end=7,
hour_start=dateparse.parse_time("00:00:00"),
hour_end=dateparse.parse_time("23:59:59"),
)

role = Role.objects.create(
name="role",
)
role.time_slots.add(timeslot)

group = Group.objects.create(name="group")
group.roles.add(role)
self.noperm_userprofile.groups.add(group)
self.assertFalse(self.noperm_userprofile.can_use_device_now(self.device))
8 changes: 1 addition & 7 deletions labAdmin/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from . import views


urlpatterns = [
url(r'^opendoorbynfc/$', views.OpenDoorByNFC.as_view(), name="open-door-nfc"),
url(r'^updateUsers/$', views.tempUpdateUser.as_view()),
Expand All @@ -10,11 +11,4 @@
url(r'^card/credits/$', views.CardCredits.as_view(), name='card-credits'),
url(r'^device/use/start/$', views.DeviceStartUse.as_view(), name='device-use-start'),
url(r'^device/use/stop/$', views.DeviceStopUse.as_view(), name='device-use-stop'),
# url(r'^nfc/(?P<nfc>.+)/$', views.NfcLogin.as_view()),
# url(r'^nfc/', views.NfcLogin.as_view()),
# url(r'^getpermission/', views.GetPermission.as_view()),
# url(r'^usedevicelist/', views.LogdeviceUseList.as_view()),
# url(r'^getToken/', views.GetTokenExample.as_view()),
# url(r'^users/', views.UserList.as_view()),
# url(r'^repeat/', views.Repeat.as_view()),
]
28 changes: 18 additions & 10 deletions labAdmin/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,27 @@ class OpenDoorByNFC(APIView):
If the nfc code isn't correct or valid, the API save in 'LogError' a new error that contains the error then return an alert message to client (HTTP_400_BAD_REQUEST)
"""

permission_classes = (DeviceTokenPermission,)

def post(self, request, format=None):
nfc = request.data.get('nfc_id')
users = UserProfile.objects.filter(card__nfc_id=nfc)
if not users.exists():
LogError(description="Api: Open Door By NFC - NFC not Valid", code=nfc).save()
nfc_id = request.data.get('nfc_id')
try:
card = Card.objects.get(nfc_id=nfc_id)
except Card.DoesNotExist:
LogError(description="Api: Use Device - nfc ID not valid", code=nfc_id or '').save()
return Response("", status=status.HTTP_400_BAD_REQUEST)

can_open = False
for u in users:
if u.can_open_door_now():
can_open = True
break
card = users.first().card
token = get_token_from_request(request)
try:
device = Device.objects.get(token=token)
except Card.DoesNotExist:
LogError(description="Api: Open Door By NFC - token not valid", code=token or '').save()
return Response("", status=status.HTTP_400_BAD_REQUEST)

user = card.userprofile
can_open = user.can_use_device_now(device)
users = UserProfile.objects.filter(pk=user.pk)
log_access = LogAccess.objects.log(users=users, card=card, opened=can_open)
users_pks = users.values_list('pk', flat=True)
if Group.objects.filter(userprofile__in=users_pks, name__icontains='Fablab').exists():
Expand Down

0 comments on commit 5e04d9c

Please sign in to comment.