Commit 3cc1b161 authored by Valentin Samir's avatar Valentin Samir

Passage à python3 et Django 2.0

parent d785938a
from django.contrib import admin
import models
from cas_attrs import models
# Register your models here.
#class User(models.Model):
#class AttributeName(models):
......
......@@ -15,26 +15,33 @@ import MySQLdb
import MySQLdb.cursors
import crypt
import models
import os
import base64
import collections
from cas_attrs import models
from cas_server.auth import DummyAuthUser
class MysqlAuthUser(DummyAuthUser):
"""A mysql auth class: authentication user agains a mysql database"""
user = None
user_attrs = None
additional_attrs = None
def __init__(self, username):
mysql_config = {
self.mysql_config = {
"user": settings.CAS_SQL_USERNAME,
"passwd": settings.CAS_SQL_PASSWORD,
"db": settings.CAS_SQL_DBNAME,
"host": settings.CAS_SQL_HOST,
"charset":settings.CAS_SQL_DBCHARSET,
"cursorclass":MySQLdb.cursors.DictCursor
"charset": settings.CAS_SQL_DBCHARSET,
"cursorclass": MySQLdb.cursors.DictCursor
}
if not MySQLdb:
raise RuntimeError("Please install MySQLdb before using the MysqlAuthUser backend")
conn = MySQLdb.connect(**mysql_config)
conn = MySQLdb.connect(**self.mysql_config)
curs = conn.cursor()
if curs.execute(settings.CAS_SQL_USER_QUERY, (username,)) == 1:
self.user = curs.fetchone()
......@@ -45,24 +52,56 @@ class MysqlAuthUser(DummyAuthUser):
for elt in models.AttributeDefault.objects.all():
user_attrs.attributes_manager.create(key=elt.key, value=elt.value, default=True)
self.user_attrs = user_attrs.attributes
super(MysqlAuthUser, self).__init__(self.user['username'])
additional_attrs = collections.defaultdict(list)
for sql in settings.CAS_SQL_ADDITIONAL_ATTRS:
curs.execute(sql, self.user)
for row in curs:
for key, value in row.items():
additional_attrs[key].append(value)
self.additional_attrs = dict(additional_attrs)
super(MysqlAuthUser, self).__init__(self.user['username'])
def test_password(self, password):
"""test `password` agains the user"""
status = False
if not self.user:
return False
return status
else:
if settings.CAS_SQL_PASSWORD_CHECK == "plain":
return password == self.user["password"]
status = password == self.user["password"]
elif settings.CAS_SQL_PASSWORD_CHECK == "crypt":
if self.user["password"].startswith('$'):
salt = '$'.join(self.user["password"].split('$', 3)[:-1])
return crypt.crypt(password, salt) == self.user["password"]
status = crypt.crypt(password, salt) == self.user["password"]
else:
return crypt.crypt(
status = crypt.crypt(
password,
self.user["password"][:2]
) == self.user["password"]
if status is True:
conn = MySQLdb.connect(**self.mysql_config)
curs = conn.cursor()
if settings.CAS_SQL_PASSWORD_CHECK == "crypt" and not password.startswith("$6$"):
salt = "$6$%s" % base64.b64encode(os.urandom(12))
new_hashed_password = crypt.crypt(password, salt)
curs.execute(
"UPDATE mailbox SET password = %s WHERE username = %s",
(new_hashed_password, self.user['username'])
)
updated = set()
attrs = self.attributs()
attrs['clear_password'] = password
for sql in settings.CAS_SQL_UPDATE:
if curs.execute(sql, attrs) > 0:
updated.add(self.user['username'])
if updated:
template = ("%s = %%s" % settings.CAS_SQL_ON_UPDATE[1],) * len(updated)
curs.execute(settings.CAS_SQL_ON_UPDATE[0] % " OR ".join(template), tuple(updated))
conn.commit()
return status
def attributs(self):
"""return a dict of user attributes"""
......@@ -72,5 +111,7 @@ class MysqlAuthUser(DummyAuthUser):
attrs = {}
if self.user_attrs:
attrs.update(self.user_attrs)
if self.additional_attrs:
attrs.update(self.additional_attrs)
attrs.update(self.user)
return attrs
......@@ -43,13 +43,13 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='attribute',
name='name',
field=models.ForeignKey(related_name='attributes', to='cas_attrs.AttributeName'),
field=models.ForeignKey(related_name='attributes', to='cas_attrs.AttributeName', on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name='attribute',
name='user',
field=models.ForeignKey(related_name='attributes', to='cas_attrs.User'),
field=models.ForeignKey(related_name='attributes', to='cas_attrs.User', on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AlterUniqueTogether(
......
......@@ -16,7 +16,7 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('value', models.CharField(unique=True, max_length=255)),
('key', models.ForeignKey(related_name='+', to='cas_attrs.AttributeName')),
('key', models.ForeignKey(related_name='+', to='cas_attrs.AttributeName', on_delete=models.CASCADE)),
],
options={
},
......@@ -29,7 +29,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='attribute',
name='user',
field=models.ForeignKey(related_name='attributes_manager', to='cas_attrs.User'),
field=models.ForeignKey(related_name='attributes_manager', to='cas_attrs.User', on_delete=models.CASCADE),
preserve_default=True,
),
]
......@@ -24,8 +24,8 @@ class Attribute(models.Model):
class Meta:
unique_together = ('user', 'key', 'value')
user = models.ForeignKey(User, related_name="attributes_manager")
key = models.ForeignKey(AttributeName, related_name="attributes")
user = models.ForeignKey(User, related_name="attributes_manager", on_delete=models.CASCADE)
key = models.ForeignKey(AttributeName, related_name="attributes", on_delete=models.CASCADE)
value = models.CharField(max_length=255)
default = models.BooleanField(default=False)
......@@ -41,7 +41,7 @@ class Attribute(models.Model):
class AttributeDefault(models.Model):
class Meta:
unique_together = ('key', 'value')
key = models.ForeignKey(AttributeName, related_name="+")
key = models.ForeignKey(AttributeName, related_name="+", on_delete=models.CASCADE)
value = models.CharField(max_length=255)
......
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