Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / helpdesk / views.py @ d59d86d4

History | View | Annotate | Download (4.3 kB)

1
import re
2

    
3
from itertools import chain
4

    
5
from django.shortcuts import redirect, get_object_or_404
6
from django.views.generic.simple import direct_to_template
7
from django.db.models import get_apps
8
from django.conf import settings
9
from django.core.exceptions import PermissionDenied
10
from django.db.models import Q
11
from django.http import Http404, HttpResponse
12
from django.utils import simplejson as json
13
from urllib import unquote
14

    
15
from synnefo.lib.astakos import get_user
16
from synnefo.db.models import *
17

    
18
IP_SEARCH_REGEX = re.compile('([0-9]+)(?:\.[0-9]+){3}')
19

    
20
def get_token_from_cookie(request, cookiename):
21
    """
22
    Extract token from the cookie name provided. Cookie should be in the same
23
    form as astakos service sets its cookie contents::
24

25
        <user_uniq>|<user_token>
26
    """
27
    try:
28
        cookie_content = unquote(request.COOKIES.get(cookiename, None))
29
        return cookie_content.split("|")[1]
30
    except AttributeError:
31
        pass
32

    
33
    return None
34

    
35
# TODO: here we mix ui setting with helpdesk settings
36
# if sometime in the future helpdesk gets splitted from the
37
# cyclades api code this should change and helpdesk should provide
38
# its own setting HELPDESK_AUTH_COOKIE_NAME.
39
HELPDESK_AUTH_COOKIE = getattr(settings, 'UI_AUTH_COOKIE_NAME', '_pithos2_a')
40

    
41
def helpdesk_user_required(func, groups=['helpdesk']):
42
    """
43
    Django view wrapper that checks if identified request user has helpdesk
44
    permissions (exists in helpdesk group)
45
    """
46
    def wrapper(request, *args, **kwargs):
47
        token = get_token_from_cookie(request, HELPDESK_AUTH_COOKIE)
48
        get_user(request, settings.ASTAKOS_URL, fallback_token=token)
49
        if hasattr(request, 'user') and request.user:
50
            groups = request.user.get('groups', [])
51

    
52
            if not groups:
53
                raise PermissionDenied
54

    
55
            for g in groups:
56
                if not g in groups:
57
                    raise PermissionDenied
58
        else:
59
            raise PermissionDenied
60

    
61
        return func(request, *args, **kwargs)
62

    
63
    return wrapper
64

    
65

    
66
@helpdesk_user_required
67
def index(request):
68
    """
69
    Helpdesk index view.
70
    """
71

    
72
    # if form submitted redirect to details
73
    account = request.GET.get('account', None)
74
    if account:
75
        return redirect('synnefo.helpdesk.views.account', account_or_ip=account)
76

    
77
    # show index template
78
    return direct_to_template(request, "helpdesk/index.html")
79

    
80

    
81
@helpdesk_user_required
82
def account(request, account_or_ip):
83
    """
84
    Account details view.
85
    """
86

    
87
    account_exists = True
88
    vms = []
89
    networks = []
90
    is_ip = IP_SEARCH_REGEX.match(account_or_ip)
91
    account = account_or_ip
92

    
93
    if is_ip:
94
        try:
95
            nic = NetworkInterface.objects.get(ipv4=account_or_ip)
96
            account = nic.machine.userid
97
        except NetworkInterface.DoesNotExist:
98
            account_exists = False
99
    else:
100
        # all user vms
101
        vms = VirtualMachine.objects.filter(userid=account).order_by('deleted')
102

    
103
        # return all user private and public networks
104
        public_networks = Network.objects.filter(public=True).order_by('state')
105
        private_networks = Network.objects.filter(userid=account).order_by('state')
106
        networks = list(public_networks) + list(private_networks)
107

    
108
        if vms.count() == 0 and private_networks.count() == 0:
109
            account_exists = False
110

    
111
    user_context = {
112
        'account_exists': account_exists,
113
        'is_ip': is_ip,
114
        'account': account,
115
        'vms': vms,
116
        'networks': networks,
117
        'UI_MEDIA_URL': settings.UI_MEDIA_URL
118
    }
119

    
120
    return direct_to_template(request, "helpdesk/account.html",
121
        extra_context=user_context)
122

    
123

    
124
@helpdesk_user_required
125
def user_list(request):
126
    """
127
    Return a json list of users based on the prefix provided. Prefix
128
    should end with "@".
129
    """
130

    
131
    prefix = request.GET.get('prefix', None)
132
    if not prefix or "@" not in prefix:
133
        raise Http404
134

    
135
    # keep only the user part (e.g. "user@")
136
    prefix = prefix.split("@")[0] + "@"
137

    
138
    q = Q(userid__startswith=prefix) & ~Q(userid=None)
139
    vm_users = VirtualMachine.objects.filter(q).values_list("userid", flat=True)
140
    net_users = Network.objects.filter(q).values_list("userid", flat=True)
141
    users = list(set(list(vm_users) + list(net_users)))
142
    return HttpResponse(json.dumps(users), content_type="application/json")
143