Commit 203593ae authored by root's avatar root

Dirtyest commit ever

parent 3bc253db
# -*- coding: utf-8 -*-
from django.forms import ModelForm
from models import Acces
class AccesPonctuel(ModelForm):
class Meta:
model = Acces
fields = ['user', 'start_time', 'end_time']
......@@ -2,6 +2,8 @@
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.urlresolvers import reverse
import random
import string
import datetime
......@@ -41,7 +43,7 @@ class Local(models.Model):
default=_generate_secret,
help_text=u"Secret partagé stocké dans le digicode",
)
stockage = models.BooleanField(help_text=u"Si le local est pour du stockage")
def __unicode__(self):
return self.nom
......@@ -54,9 +56,21 @@ class Local(models.Model):
for possible in possibles:
for acces in Acces.objects.filter(user=possible.proprietaire).filter(local=self):
if acces.start_time < timezone.now() and timezone.now() < acces.end_time :
log = Log()
log.user = acces.user
log.save()
return True
return False
class Log(models.Model):
"""Un log pour une entrée dans un local """
user = models.ForeignKey(User)
date = models.DateTimeField(auto_now_add=True, blank=True)
class Acces(models.Model):
"""Un accès à un local donné"""
......@@ -75,13 +89,25 @@ class Acces(models.Model):
help_text=u"Date correspondant à la fin de la période de validité",
)
# TODO retirer ça/faire un truc mieux
periodicity = models.IntegerField(default=0,
help_text=u"Période en jour de répétition de la validité de l'accès",
)
# TODO: fonction statique qui prend un query dict
def details(self):
if self.responsable:
return u"Responsable"
# TODO hebdomadaire
if self.start_time and self.end_time:
return u"de %s au %s" % (self.start_time, self.end_time)
# Toute autre restriction d'accès envisageables (créneaux horaires etc)
# Idem, mais avec des groupes (TODO ?)
def edit_url(self):
return "/prout"
return reverse('digicode.views.edit_acces', args=[str(self.id)])
class Code(models.Model):
......@@ -94,6 +120,7 @@ class Code(models.Model):
touches = models.CharField(max_length=CODE_LENGTH,
help_text=u"Une chaîne de caractère ne contenant que des chiffres",
default=_generate_code,
unique = True,
)
proprietaire = models.ForeignKey(User)
......
from django.shortcuts import render
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseForbidden
import calendar as calendar_module
import datetime
from models import Code, Local, Acces
from forms import AccesPonctuel
from models import Code
def home(request):
return render(request, "home.html", {'liste_local' : Local.objects.all()})
@login_required
def liste(request):
return render(request, "liste.html", {
'liste': Code.objects.all().filter(proprietaire=request.user),
})
# Create your views here.
@login_required
def liste_respo(request, pk):
#
local = get_object_or_404(Local, pk=pk)
#
accesses = Acces.objects.all().filter(local=local)
mine = accesses.filter(user=request.user)
responsable = bool(mine.filter(responsable=True))
if not mine:
return HttpResponseForbidden("forbidden")
return render(request, "liste_respo.html", {
'local': local,
'accesses': accesses,
'responsable': responsable,
})
@login_required
def edit_access(request, pk):
acc = get_object_or_404(Acces, pk=pk)
# Ai-je le droit ?
if not Acces.objects.all().filter(local=local, user=request.user):
return HttpResponseForbidden("forbidden")
return
@login_required
def add_acces(request, pk):
local = get_object_or_404(Local, pk=pk)
# Ai-je le droit ?
if not Acces.objects.all().filter(local=local, user=request.user):
return HttpResponseForbidden("forbidden")
if request.method == 'POST':
form = AccesPonctuel(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.local = local
obj.responsable = False
obj.save()
# TODO: message de succès
return redirect('liste_respo', pk)
else:
form = AccesPonctuel()
return render(request, 'add_acces.html', {
'form': form,
'local': local,
})
@login_required
def calendar(request, month=None, year=None, local=None):
today = datetime.date.today()
month = month or today.month
year = year or today.year
if not month and not year:
return HttpResponseForbidden()
c = calendar_module.Calendar()
calendr = c.monthdatescalendar(int(year),int(month))
if not local :
local = Local.objects.all()[0]
month_start = calendr[0][0]
month_end = calendr[len(calendr)-1][6]
reservations = Acces.objects.all().filter(start_time__lte = month_end,end_time__gte = month_start).order_by('start_time')
final_calendar=[]
for i in xrange(len(calendr)):
final_calendar.append([])
for j in xrange(7):
final_calendar[i].append([calendr[i][j]])
for reservation in reservations:
if reservation.start_time.date() <= calendr[i][j] <= reservation.end_time.date():
final_calendar[i][j].append(reservation)
return render(request, "calendar.html", {'calendar' : final_calendar})
......@@ -119,22 +119,25 @@ def connect_NK():
print "Code d'erreur %s" %out["retcode"]
raise NKError()
def full_read(sock):
"""Lit sur la socket jusqu'à ce que l'output soit déJSON-izable"""
output = ""
tries = 0
while True:
output += sock.read()
try:
return json.loads(output)
except ValueError: # le JSON n'est pas valide
pass
if output == "":
tries += 1
if tries == 10:
# Au bout d'un moment, on laisse tomber
raise NKError()
time.sleep(0.01)
def full_read(socket):
# On récupère d'abord la taille du message
length_str = ''
char = socket.recv(1)
while char != '\n':
length_str += char
char = socket.recv(1)
total = int(length_str)
# On utilise une memoryview pour recevoir les données chunk par chunk efficacement
view = memoryview(bytearray(total))
next_offset = 0
while total - next_offset > 0:
recv_size = socket.recv_into(view[next_offset:], total - next_offset)
next_offset += recv_size
try:
msg = json.loads(view.tobytes())
except (TypeError, ValueError) as e:
raise NKError()
return msg
def login_NK(username, password):
"""Ouvre une connexion au serveur NK2015 par username/password
......
......@@ -8,7 +8,7 @@ urlpatterns = patterns('',
# url(r'^$', 'gestion.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'gestion.views.home', name='home'),
url(r'^$', 'digicode.views.home', name='home'),
url(r'^login/$', 'gestion.views.login_view', name='login'),
url(r'^logout/$', 'gestion.views.logout_view', name='logout'),
......@@ -16,7 +16,11 @@ urlpatterns = patterns('',
url(r'^rpc/', include('rpc_server.urls')),
url(r'^liste/', 'digicode.views.liste', name='liste'),
url(r'^local/([0-9]*)', 'digicode.views.liste_respo', name='liste_respo'),
url(r'^calendar/(?P<month>[^/]*)/(?P<year>[^/]*)/(?P<local>[^/]*)/$', 'digicode.views.calendar', name='calendar')
url(r'^local/([0-9]*)$', 'digicode.views.liste_respo', name='liste_respo'),
url(r'^local/([0-9]*)/add_acces', 'digicode.views.add_acces', name='add_acces'),
url(r'^calendar/(?P<month>[^/]*)/(?P<year>[^/]*)/(?P<local>[^/]*)/$', 'digicode.views.calendar', name='calendar'),
url(r'^calendar/(?P<local>[^/]*)/$', 'digicode.views.calendar', name='calendar_now'),
url(r'^calendar$', 'digicode.views.calendar', name='calendar_all'),
)
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'title' %}:: Accès pour {{local}} {% endblock %}
{% block 'content' %}
<h1>Ajout d'un accès à {{ local }}</h1>
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Enregistrer"/>
</form>
{% endblock 'content' %}
{% load staticfiles %}
<html>
<head>
<title>Hello world</title>
<title>Digicodes BDE {% block 'title' %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static "style.css" %}" />
</head>
<body>
......@@ -11,11 +11,14 @@
<ul id="menu">
{% block 'menu' %}
<li>
Menu principal
<a href="{% url home %}">Les locaux</a>
</li>
<li>
<a href="{% url liste %}">Mes codes</a>
</li>
<li>
<a href="{% url calendar_all %}">Calendrier</a>
</li>
<li>
À propos
</li>
......@@ -36,8 +39,6 @@
</ul>
<div id="content">
{% block 'content' %}
<h1>Hello</h1>
<img src="{% static "hello.png" %}" alt="hello.png">
{% endblock 'content' %}
</div>
</body>
......
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'title' %}:: Accès pour {{local}} {% endblock %}
{% block 'content' %}
<h1>Calendrier des réservations</h1>
<table>
<tr>
<th>Lundi</th>
<th>Mardi</th>
<th>Mercredi</th>
<th>Jeudi</th>
<th>Samedi</th>
<th>Dimanche</th>
</tr>
{% for week in calendar %}
<tr>
{% for days in week %}
<td>{% for info in days %}
{% if forloop.first %}
{{ info }}
<ul>
{% else %}
<li> {{ info.local }} par {{ info.user }} du {{ info.start_time }} au {{ info.end_time }}
</li>
{% endif %}
{% endfor %}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endblock 'content' %}
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'content' %}
<h1>Hello</h1>
<img src="{% static "hello.png" %}" alt="hello.png">
<h1>Bienvenue sur le système de gestion des digicodes</h1>
<p>
<img src="{% static "hello.png" %}" alt="hello.png"><br />
<em>Liste des locaux</em>
<ul>
{% for local in liste_local %}
<li><a href="{% if local.stockage %} {% url liste_respo local.pk %}
{% else %} {% url calendar_now local.pk %} {% endif %}
"> {{local.nom}}</a>
</li>
{% endfor %}
</ul>
</p>
{% endblock 'content' %}
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'title' %}:: Mes codes{% endblock %}
{% block 'content' %}
<h1>Liste de mes codes</h1>
<ul>
......
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'title' %}:: Accès pour {{local}} {% endblock %}
{% block 'content' %}
<h1>Gestion des accès pour {{ local }}</h1>
{% if responsable %}
<a href="{% url add_acces local.pk %}">Rajouter un accès</a>
{% endif %}
<table>
<tr>
<th>Qui</th>
<th>Type</th>
<th><!--Action--></th>
</tr>
{% for acc in accesses %}
<tr>
<td>{{ acc.user }}</td>
<td>{{ acc.details }}</td>
<td><a href="{{ acc.edit_url }}">Editer</a></td>
</tr>
{% endfor %}
</table>
{% endblock 'content' %}
{% extends 'base.html' %}
{% load staticfiles %}
{% block 'title' %}:: Connexion{% endblock %}
{% block 'content' %}
<form method="post">
{% csrf_token %}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment