Commit 97721b49 authored by Valentin Samir's avatar Valentin Samir

[pageperso] Ajoute la possibilité de se créer sa base de donnée mysql personnelle sur zamok

parent 0ca0a24d
......@@ -12,3 +12,21 @@ class PagePersoForm(forms.ModelForm):
model = PagePerso
fields = ['nom_site', 'slogan', 'logo']
class SqlPasswordForm(forms.Form):
password = forms.CharField(
label="mot de passe",
max_length=256,
widget=forms.PasswordInput,
required=True
)
password_confirmation = forms.CharField(
label="confirmation",
max_length=256,
widget=forms.PasswordInput,
required=True
)
def clean(self):
if self.cleaned_data.get("password") != self.cleaned_data.get("password_confirmation"):
Please register or sign in to reply
Please register or sign in to reply
  • mais il y a un bouton pour générer un mot de passe aléatoire sur la page.

Please register or sign in to reply
raise forms.ValidationError("Les mots de passes ne sont pas identique")
......@@ -2,6 +2,9 @@
{% block title %} Ma page Perso {% endblock %}
{% block h1 %} Ma page perso {% endblock %}
{% block content %}
<h2>Référencement</h2>
Cette interface permet de référencer sa page perso sur <a href="https://wiki.crans.org/PagesPerso"a>Wiki/PagesPerso</a><br/>
Pour plus d'informations, rendez-vous sur le <a href="https://wiki.crans.org/HowToEspacePerso"a>Wiki</a>
<form class="form-full-width" method="post"> {% csrf_token %}
<div class="error-container">
{{ form.non_field_errors }}
......@@ -34,13 +37,23 @@
{% if deref %}
<h2>Déréférencement</h2>
<form action="{% url 'pageperso:deref' %}">
<footer>
<input type="submit" value="Déréférencer ma page perso" class="button-del">
</footer>
<input type="submit" value="Déréférencer ma page perso" class="button-del">
</form>
{% endif %}
Cette interface permet de référencer sa page perso sur <a href="https://wiki.crans.org/PagesPerso"a>Wiki/PagesPerso</a><br/>
Pour plus d'informations, rendez-vous sur le <a href="https://wiki.crans.org/HowToEspacePerso"a>Wiki</a>
<h2>Base de donnée</h2>
{% if not mysql_error %}
{% if mysql_exists %}
Vous disposez d'une base de donnée mysql accessible depuis zamok.<br/>
Nom d'utilisateur "{{user.username}}", nom de la base, "{{user.username}}", adresse "localhost".<br/>
<a href="{% url "pageperso:reset_db_password" %}" class="button">Réinitialisé le mot de passe de ma base de donnée</a>
<a href="{% url "pageperso:delete_database" %}" class="button-del">Supprimer ma base de donnée</a>
{% else %}
Vous ne disposez pas encore d'une base de donnée mysql accessible depuis zamok.<br/>
<a href="{% url "pageperso:create_database"%}" class="button">Créer une base de donnée</a>
{% endif %}
{% else %}
Impossible d'accéder aux information de connexion mysql
{% endif %}
{% endblock %}
......
{% extends "template.html" %}
{% block title %} Ma page Perso {% endblock %}
{% block h1 %} Ma page perso {% endblock %}
{% block content %}
<script>
function generatePassword(){
var password = Math.random().toString(36).slice(-8);
password = password + Math.random().toString(36).slice(-8);
form = document.forms['form'];
form.elements["password"].value = password;
form.elements["password_confirmation"].value = password;
form.elements["generated"].value = password;
return false;
}
</script>
<h2>Création de la base de donnée</h2>
Merci de choisir un mot de passe pour votre base de donnée.<br/>
Il est fortement recommendé d'utiliser un mot de passe différent de celui de votre compte crans.
<form id="form" class="form" method="post"> {% csrf_token %}
<table>
{{form}}
<tr><th>Généré un mot de passe
<a href="#" onclick="return generatePassword();" class="button">Générer</a>
</th><td>
<input type="text" name="generated"></td></tr>
</table>
<footer>
<input type="submit" value="envoyer" />
<a href="{% url "pageperso:pageperso" %}" class="button">annuler</a>
</footer>
</form>
{% endblock %}
{% extends "template.html" %}
{% block title %} Ma page Perso {% endblock %}
{% block h1 %} Ma page perso {% endblock %}
{% block content %}
<h2>Création de la base de donnée</h2>
<form class="form" method="post"> {% csrf_token %}
<label>
<input name="confirm" type="checkbox" value="yes"> Vraiment supprimer la base de donnée ? Toutes les donnée contenu dedans seront irrémédiablement perdu.
</label>
<footer>
<input type="submit" value="supprimer" class="button-del" />
<a href="{% url "pageperso:pageperso" %}" class="button">annuler</a>
</footer>
</form>
{% endblock %}
......@@ -6,6 +6,9 @@ import views
urlpatterns = patterns('',
url('^$', views.pageperso, name='pageperso'),
url('deref', views.deref, name='deref')
url('deref', views.deref, name='deref'),
url('createdb', views.create_database, name='create_database'),
url('resetdbpw', views.reset_db_password, name='reset_db_password'),
url('deletedb', views.delete_database, name='delete_database'),
)
......@@ -2,16 +2,30 @@
# Application pour permettre aux adhérents de lister leur page perso
# Gabriel Détraz <detraz@crans.org>, Hamza Dely <dely@crans.org>
import django.shortcuts
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from models import PagePerso
from django.template import RequestContext
from forms import PagePersoForm
from gestion.mysql import make_cursor
from gestion import secrets_new as secrets
try:
cursor = make_cursor("intranet_cursor", secrets.get("intranet_mysql_admin"))
except (secrets.SecretNotFound, secrets.SecretForbidden):
cursor = None
# intranet_mysql_admin
from forms import PagePersoForm, SqlPasswordForm
def test_backticks(name):
if '`' in name:
raise ValueError("%r should not contain '`'")
return name
# Vue d'affichage du formulaire d'indexation de la pageperso
@login_required
@require_http_methods(["GET", "POST"])
def pageperso(request):
result = PagePerso.objects.filter(login=str(request.user))
if request.method == "POST":
......@@ -33,7 +47,7 @@ def pageperso(request):
deref = False
# Si c'est pas un post, on renvoie le formulaire prérempli (si deja une page)
else:
elif request.method == "GET":
if result.exists():
res = result[0]
initial_data = {
......@@ -48,10 +62,105 @@ def pageperso(request):
form = PagePersoForm()
labelperso = u"Référencer ma page perso"
deref = False
return django.shortcuts.render_to_response("pageperso/affichage.html", locals(), context_instance=RequestContext(request))
if cursor:
mysql_error = False
with cursor() as cur:
if cur.execute(
"SELECT User From mysql.user WHERE User = %s",
(request.user.username,)
):
# one user found, clean cursor
cur.fetchone()
mysql_exists = True
if not cur.execute(
(
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "
"WHERE SCHEMA_NAME = %s"
),
(request.user.username,)
):
cur.execute(
(
"CREATE DATABASE `%s` CHARACTER SET utf8 COLLATE utf8_unicode_ci;"
) % test_backticks(request.user.username)
)
cur.execute(
(
"GRANT ALL PRIVILEGES ON `%s`.* TO %%s@'localhost'"
) % test_backticks(request.user.username),
(request.user.username,)
)
else:
mysql_error = True
return render(request, "pageperso/affichage.html", locals())
@login_required
def deref(request):
result = PagePerso.objects.filter(login=str(request.user))
result.delete()
return django.shortcuts.redirect("/pageperso/")
return redirect("/pageperso/")
@login_required
@require_http_methods(["GET", "POST"])
def create_database(request):
if cursor is None:
return redirect("pageperso:pageperso")
if request.method == "POST":
form = SqlPasswordForm(request.POST)
if form.is_valid():
with cursor() as cur:
cur.execute(
(
"CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET utf8 "
"COLLATE utf8_unicode_ci;"
) % test_backticks(request.user.username)
)
cur.execute(
(
"GRANT ALL PRIVILEGES ON `%s`.* TO %%s@'localhost' IDENTIFIED BY %%s"
) % test_backticks(request.user.username),
(request.user.username, form.cleaned_data["password"])
)
return redirect("pageperso:pageperso")
elif request.method == "GET":
form = SqlPasswordForm()
return render(request, "pageperso/createdb.html", {'form': form})
@login_required
@require_http_methods(["GET", "POST"])
def reset_db_password(request):
if cursor is None:
return redirect("pageperso:pageperso")
if request.method == "POST":
form = SqlPasswordForm(request.POST)
if form.is_valid():
with cursor() as cur:
if cur.execute(
"SELECT User From mysql.user WHERE User = %s",
(request.user.username,)
):
cur.fetchone()
cur.execute(
"SET PASSWORD FOR %s@'localhost' = PASSWORD(%s);",
(request.user.username, form.cleaned_data["password"],)
)
return redirect("pageperso:pageperso")
elif request.method == "GET":
form = SqlPasswordForm()
return render(request, "pageperso/createdb.html", {'form': form})
@login_required
@require_http_methods(["GET", "POST"])
def delete_database(request):
if cursor is None:
return redirect("pageperso:pageperso")
Please register or sign in to reply
  • Un message est affiché sur "pageperso:pageperso" quand cursor is None. ("Impossible d'accéder aux information de connexion mysql") Donc ça n'est pas vraiment silencieux. D'ailleur "pageperso:pageperso" ne présente pas de liens vers delete_database et reset_db_password si cursor is None.

    Edited by Valentin Samir
Please register or sign in to reply
Please register or sign in to reply
if request.method == "POST":
if request.POST.get("confirm") == "yes":
with cursor() as cur:
cur.execute("DROP DATABASE IF EXISTS `%s`" % test_backticks(request.user.username))
cur.execute("DROP USER %s@'localhost'", (request.user.username,))
return redirect("pageperso:pageperso")
return render(request, "pageperso/deletedb.html")
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