Commit 0d809092 authored by Charlie Jacomme's avatar Charlie Jacomme Committed by root

[login_note.py] Interfaçage avec la note (a tester)

parent f2c6b0ca
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# LOGIN.PY -- Gère l'interface d'authentification à l'aide des modèles Django.
#
# Copyright (C) 2009-2010 Nicolas Dandrimont
# Authors: Nicolas Dandrimont <olasd@crans.org>
# Censor: Antoine Durand-Gasselin <adg@crans.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.contrib.auth.models import Group, User
from django.contrib.auth.backends import ModelBackend
from django.utils.importlib import import_module
class NoteUserBackend(ModelBackend):
"""Authentifie un utilisateur à l'aide de la note"""
supports_anonymous_user = False
def authenticate(self, username=None, password=None):
"""Authentifie l'utilisateur sur la base LDAP. Crée un
utilisateur django s'il n'existe pas encore."""
if not username or not password:
return None
# <!>
shortcut = lc_ldap.shortcuts.lc_ldap_test if settings.BASE_LDAP_TEST else lc_ldap.shortcuts.lc_ldap
try:
data = login_NK(username,password)
except NKError:
return None
# On stocke les utilisateurs dans la base avec un truc canonique
django_username = '#%s' % idbde
try:
user = User.objects.get(username=django_username)
except User.DoesNotExist:
user = User(username=django_username, password="Note Backend User!")
user.save()
#self.refresh_droits(user, ldap_user) #TODO
self.refresh_fields(user, data)
return user
def refresh_droits(self, user, cl_user):
"""Rafraîchit les droits de l'utilisateur django `user' depuis
l'utilisateur LDAP `cl_user'"""
return # À écrire
cl_droits = [x.value for x in cl_user['droits']]
if u"Nounou" in cl_droits:
user.is_staff = True
user.is_superuser = True
else:
user.is_staff = False
user.is_superuser = False
groups = []
for cl_droit in cl_droits:
group, created = Group.objects.get_or_create(name="crans_%s" % cl_droit.lower())
group.save()
groups.append(group)
user.groups.add(*groups)
user.save()
def refresh_fields(self, user, data):
"""Rafraîchit les champs correspondants à l'utilisateur (nom,
prénom, email)"""
user.first_name = unicode(cl_user['prenom'][0])
user.last_name = unicode(cl_user['nom'][0])
mail = unicode(cl_user['mail'][0])
if '@' not in mail: # Ne devrait pas arriver (pour migration)
mail += u'@crans.org'
user.email = mail
user.save()
def get_user(self, uid):
"""Récupère l'objet django correspondant à l'uid"""
try:
return User.objects.get(pk=uid)
except User.DoesNotExist:
return None
def connect_NK():
"""Connecte une socket au servuer NK2015 et la renvoie après avoir effectué le hello.
Lève une erreur en cas d'échec"""
sock = socket.socket()
try:
# On établit la connexion sur port 4242
sock.connect((settings.NK2015_IP, settings.NK2015_PORT))
# On passe en SSL sock = ssl.wrap_socket(sock, ca_certs='../keys/ca_.crt')
# On fait un hello
sock.write(json.dumps(["hello", "HTTP Django"]))
# On récupère la réponse du hello
out = full_read(sock)
except Exception as exc:
# Si on a foiré quelque part, c'est que le serveur est down
raise NKError()
if out["retcode"] == 0:
return sock
else:
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 login_NK(username, password):
"""Ouvre une connexion au serveur NK2015 par username/password
Renvoie dans tous les cas un objet HttpResponse[Redirect] utilisable directement"""
try:
sock = connect_NK()
data = [username, password, "bdd",[[],[],False]]
paquet = ["login", data]
sock.write(json.dumps(paquet))
out = full_read(sock)
retcode, errmsg = out["retcode"], out["errmsg"]
except NKError as exc:
raise NKError
if retcode == 0:
# login réussi
request.session["logged"] = "ok"
# On demande au serveur qui on est
sock.write(json.dumps(["whoami"]))
out = full_read(sock)
whoami = out["msg"]
return whoami
else:
raise NKError
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