script_utils.py 3.54 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# ⁻*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2018  Lev-Arcady Sellem
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 22 23 24
"""re2o.script_utils
A set of utility scripts that can be used as standalone to interact easily
with Re2o throught the CLI
"""
25

Maël Kervella's avatar
Maël Kervella committed
26
import os
27
from os.path import dirname
Maël Kervella's avatar
Maël Kervella committed
28 29
import sys
import pwd
30

31 32
from getpass import getpass
from reversion import revisions as reversion
33

34
from django.core.wsgi import get_wsgi_application
35
from django.core.management.base import CommandError
36
from django.db import transaction
37 38 39
from django.utils.html import strip_tags

from users.models import User
40

41
proj_path = dirname(dirname(__file__))
Maël Kervella's avatar
Maël Kervella committed
42 43 44 45 46 47
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "re2o.settings")
sys.path.append(proj_path)
os.chdir(proj_path)

application = get_wsgi_application()

48

49 50 51
def get_user(pseudo):
    """Cherche un utilisateur re2o à partir de son pseudo"""
    user = User.objects.filter(pseudo=pseudo)
Maël Kervella's avatar
Maël Kervella committed
52
    if len(user) == 0:
53
        raise CommandError("Invalid user.")
Maël Kervella's avatar
Maël Kervella committed
54
    if len(user) > 1:
55 56
        raise CommandError("Several users match this username. This SHOULD"
                           " NOT happen.")
57 58
    return user[0]

59 60 61 62

def get_system_user():
    """Retourne l'utilisateur système ayant lancé la commande"""
    return pwd.getpwuid(int(os.getenv("SUDO_UID") or os.getuid())).pw_name
63 64


Maël Kervella's avatar
Maël Kervella committed
65
def form_cli(Form, user, action, *args, **kwargs):
66 67 68 69 70 71 72
    """
    Remplit un formulaire à partir de la ligne de commande
        Form : le formulaire (sous forme de classe) à remplir
        user : l'utilisateur re2o faisant la modification
        action : l'action réalisée par le formulaire (pour les logs)
    Les arguments suivants sont transmis tels quels au formulaire.
    """
Maël Kervella's avatar
Maël Kervella committed
73 74
    data = {}
    dumb_form = Form(user=user, *args, **kwargs)
75
    for key in dumb_form.fields:
Maël Kervella's avatar
Maël Kervella committed
76 77 78
        if not dumb_form.fields[key].widget.input_type == 'hidden':
            if dumb_form.fields[key].widget.input_type == 'password':
                data[key] = getpass("%s : " % dumb_form.fields[key].label)
79
            else:
Maël Kervella's avatar
Maël Kervella committed
80
                data[key] = input("%s : " % dumb_form.fields[key].label)
81

Maël Kervella's avatar
Maël Kervella committed
82
    form = Form(data, user=user, *args, **kwargs)
83
    if not form.is_valid():
84
        sys.stderr.write("Errors: \n")
85
        for err in form.errors:
Maël Kervella's avatar
Maël Kervella committed
86 87 88 89 90
            # Oui, oui, on gère du HTML là où d'autres ont eu la
            # lumineuse idée de le mettre
            sys.stderr.write(
                "\t%s : %s\n" % (err, strip_tags(form.errors[err]))
            )
91
        raise CommandError("Invalid form.")
92 93

    with transaction.atomic(), reversion.create_revision():
Maël Kervella's avatar
Maël Kervella committed
94 95 96
        form.save()
        reversion.set_user(user)
        reversion.set_comment(action)
97

98 99
    sys.stdout.write("%s : done. The edit may take several minutes to"
                     " apply.\n" % action)