views.py 9.72 KB
Newer Older
1
# -*- coding: utf-8 -*
2

3

4
from django.shortcuts import render,  redirect
5
from django.core.urlresolvers import reverse
6
from django.contrib.auth.decorators import login_required
7
from django.http import Http404
8 9 10

from django.template import RequestContext

11 12
from django.contrib import messages

13
from lc_ldap.ldap_locks import LockError
14
from django.contrib import messages
15
from intranet import conn_pool, settings
16
from intranet.mixins import CableurMixin
17
from lc_ldap import attributs
18
from django.views.generic import View
19
import models
20 21
import hashlib
import time
22
import subprocess
23
from forms import MachineForm
24
from django.utils.translation import ugettext_lazy as _
25

26
def unicode_of_Error(x):
27
    """Formate l'exception de type ValueError"""
28 29
    # TODO templatetag ?
    return u"\n".join(unicode(i, 'utf-8') if type(i) == str
30
            else repr(i) for i in x.args)
31

32
# TODO obsolete !!
33 34 35
def keep(request, mid, hash, action, valid_until):
    """Confirmer la suppression ou création de machine"""
    if hashlib.sha256(settings.SECRET_KEY + mid + valid_until).hexdigest() != hash or int(valid_until, 16) < time.time():
Daniel Stan's avatar
Daniel Stan committed
36
        return render(request, 'machines/confirm_keep.html', {'message':_(u'Lien invalide.')})
37 38 39 40
    if action == 'drop':
        models.delete_machine(request.user, mid)
    with open('/var/www/to_keep', 'a') as f:
        f.write('%s: %s\n' % (mid, action))
Daniel Stan's avatar
Daniel Stan committed
41
    return render(request, 'machines/confirm_keep.html', {'message':_(u'Votre demande a bien été prise en compte, merci.')})
42 43 44

@login_required
def index(request):
45 46 47 48
    clubs = []
    for cl in models.get_user(request.user).clubs():
        machines = []
        for machine in cl.machines():
49
            # TODO template tags !
50 51 52 53 54 55 56 57
            machines.append({
                'type' : str(machine['objectClass'][0]),
                'host' : str(machine['host'][0]).split('.',1)[0],
                'mid' : str(machine['mid'][0]),
            })

        clubs.append({'nom' : str(cl['nom'][0]), 'machines' : machines, 'cid' : str(cl['cid'][0]) })

58 59
    machines = []
    for machine in models.get_user(request.user).machines():
60
        # TODO templatetags. Typiquement le type de machine est mauche
61 62 63
        machines.append({
            'type' : str(machine['objectClass'][0]),
            'host' : str(machine['host'][0]).split('.',1)[0],
64
            'mid' : str(machine['mid'][0]),
65
        })
66 67

    return render(request, 'machines/index.html', {'clubs' : clubs, 'machines' : machines, 'can_create_machine_fil' : models.can_create_machine_fil(request.user)})
68 69 70


@login_required
71 72
def detail(request, mid=None):
    if request.method == "GET":
73 74 75 76 77 78 79 80
        try:
            machine = models.Machine(user=request.user, mid=mid)
            if not machine:
                return redirect('machines:index')
            return render(request, 'machines/detail.html', {'machine' : machine})
        except (ValueError, EnvironmentError, LockError) as error:
            messages.error(request, 'Erreur : %s' % unicode_of_Error(error))
            return redirect("machines:index")
81 82
        except models.Machine.DoesNotExist:
            raise Http404()
83
    else:
84
        print request.POST
85

86 87 88
@login_required
def advanced(request, mid=None):
    if request.method == "GET":
89 90 91 92
        try:
            machine = models.Machine(user=request.user, mid=mid)
        except models.Machine.DoesNotExist:
            raise Http404()
93 94 95 96 97 98 99 100 101
        if not machine:
            return redirect('machines:index')

        return render(request, 'machines/advanced.html', {'machine' : machine})
    else:
        print request.POST

@login_required
def ssh_keys(request, mid=None, delete=None):
102 103 104 105
    try:
        machine = models.Machine(user=request.user, mid=mid, mode= 'rw' if delete or request.method == "POST" else 'ro')
    except models.Machine.DoesNotExist:
        raise Http404()
106 107 108 109 110 111
    if not machine:
        return redirect('machines:index')
    try:
        if request.method == "GET":
            if delete:
                machine.delete('sshFingerprint', int(delete))
112
                return redirect('machines:ssh_fprs', mid=mid)
113

114
            return render(request, 'machines/ssh_fprs.html', {'machine' : machine})
115
        else:
116
            machine.machine['sshFingerprint'].append(request.POST['ssh_fpr'])
117 118 119
            machine.machine.validate_changes()
            machine.machine.save()
            conn_pool.get_user(request.user, refresh=True)
120
            return redirect('machines:ssh_fprs', mid=mid)
121
    except (ValueError, EnvironmentError, LockError) as error:
122
        return render(request, 'machines/ssh_fprs.html', {
123
            'machine' : machine,
124
            'ssh_fpr' : request.POST['ssh_fpr'],
125
            'error' : 'Erreur : %s' % unicode_of_Error(error)})
126 127 128

        print request.POST

129
@login_required
130 131 132 133
def delete(request, mid):
    try:
        machine = models.Machine(user=request.user, mid=mid)
    except (ValueError, EnvironmentError, LockError) as error:
134
        _(messages.error(request, 'Erreur : %s' % unicode_of_Error(error)))
135
        return redirect("machines:index")
136 137
    except models.Machine.DoesNotExist:
        raise Http404()
138
    if not machine:
139
        messages.error(request, _(u"Cette machine n'existe pas"))
140
        return redirect("machines:index")
141 142

    if request.method == 'POST':
143 144
        try:
            models.delete_machine(request.user, mid)
145
            messages.success(request, _(u'La machine a bien été supprimée'))
146
            return redirect("machines:index")
147
        except (ValueError, EnvironmentError, LockError) as error:
148 149 150 151 152
            return render(request, 'machines/detail.html', {
                'machine' : machine,
                'error' : 'Erreur : %s' % unicode_of_Error(error)})

    return render(request, "confirm.html", {
153 154
        'confirm_title': _(u'Suppression de %s' % machine.machine['host'][0]),
        'confirm_message': _(u'Êtes-vous sûr de vouloir effacer cette machine ?'),
155 156
        'confirm_cancel_url': reverse('machines:detail', args=[mid]),
    })
157

158
@login_required
159
def add(request, mtype=None, cid=None, mac=None, aid=None, ptype=None):
160
    # TODO factoriser !
161
    if not models.can_create_machine(request.user):
Daniel Stan's avatar
Daniel Stan committed
162
        messages.error(request, _(u'Vous ne pouvez pas ajouter de machine !'))
163
        return redirect('machines:index')
164
    if cid and not request.user.has_perm('auth.crans_cableur'):
165
        if not cid in [str(cl['cid'][0]) for cl in models.get_user(request.user).clubs() ]:
Daniel Stan's avatar
Daniel Stan committed
166
            messages.error(request, _(u'Vous ne pouvez pas ajouter de machine pour ce club !'))
167
            return redirect('machines:index')
168
    if aid and not request.user.has_perm('auth.crans_cableur'):
169
        messages.error(request, _(u"Vous n'etes pas câbleur !"))
170
        return redirect('machines:index')
171
    if mtype == 'fil' and not cid and not models.can_create_machine_fil(request.user):
Daniel Stan's avatar
Daniel Stan committed
172
        messages.error(request, _(u'Vous avez atteint votre nombre limite de machines filaires !'))
173 174
        return redirect('machines:index')

175 176
    if request.POST:
        form = MachineForm(request.POST)
177
        machine = models.Machine(request.user, cid=cid, aid=aid)
178
        machine.create_init(mtype)
179

180 181 182
        if form.is_valid():
            try:
                machine.set(host=form.cleaned_data['hostname'], mac=form.cleaned_data['mac'])
183
                machine.create(cid=cid, aid=aid)
184
                messages.success(request, _(u'Machine correctement ajoutée.'))
185 186 187
                return redirect('machines:detail', mid=str(machine['mid']))
            except (ValueError, EnvironmentError, LockError) as error:
                messages.error(request, unicode_of_Error(error))
188
    else:
189 190 191 192 193 194 195
        if mac is not None:
            mac_initial = mac
        else:
            mac_initial = u'<automatique>'
        initial = {'mac': mac_initial}
        form = MachineForm(initial=initial)
    return render(request, 'machines/add_edit.html', {'form' : form})
196

197 198 199 200 201 202 203 204 205 206 207
class PrintTicket(CableurMixin, View):
    """
      Classe pour la réinitialisation du mot de passe et l'impression d'un ticket
    """
    def get(self, request, mid, *args, **kwargs):
        subprocess.call(['/usr/scripts/cransticket/dump_creds.py', '--forced', 'mid=%s' % mid])
        messages.success(request, u"""Ticket en cours d'impression.""")
        return redirect('machines:detail', mid=mid)

print_ticket = PrintTicket.as_view()

208 209
@login_required
def edit(request, mid=None):
210
    # TODO factoriser !
211 212
    try:
        machine = models.Machine(user=request.user, mid=mid, mode='rw')
213 214
    except models.Machine.DoesNotExist:
        raise Http404()
215 216
    except ValueError:
        machine = None
217
    if not machine:
Daniel Stan's avatar
Daniel Stan committed
218
        messages.error(request, _(u'Cette machine ne vous appartient pas !'))
219
        return redirect('machines:index')
220

221 222 223 224 225 226 227 228 229 230 231
    if request.POST:
        form = MachineForm(request.POST)
        if form.is_valid():
            try:
                machine.set(
                    host=form.cleaned_data['hostname'],
                    mac=form.cleaned_data['mac'],
                    dnsipv6=form.cleaned_data['dns_ipv6']
                )
                ssh_fpr = form.cleaned_data['ssh_fpr']
                if ssh_fpr:
232
                    machine.machine['sshFingerprint'].append(request.POST['ssh_fpr'])
233
                    machine.machine.validate_changes()
234
                    machine.machine.history_gen()
235
                machine.save()
236
                messages.success(request, _(u'Les changements ont bien été enregistrés.'))
237 238 239 240 241 242 243 244 245 246 247
                return redirect('machines:detail', mid=str(machine['mid']))
            except (ValueError, EnvironmentError, LockError) as error:
                messages.error(request, unicode_of_Error(error))
    else:
        initial = {
            'hostname': machine['host'],
            'mac': machine['mac'],
            'dns_ipv6': machine['dnsipv6'],
        }
        form = MachineForm(initial=initial)
    return render(request, 'machines/add_edit.html', {'form' : form, 'edit': True})
248