Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (4.4 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

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

    
43

    
44
def helpdesk_user_required(func, groups=['helpdesk']):
45
    """
46
    Django view wrapper that checks if identified request user has helpdesk
47
    permissions (exists in helpdesk group)
48
    """
49
    def wrapper(request, *args, **kwargs):
50
        HELPDESK_ENABLED = getattr(settings, 'HELPDESK_ENABLED', True)
51
        if not HELPDESK_ENABLED:
52
            raise Http404
53

    
54
        token = get_token_from_cookie(request, AUTH_COOKIE)
55
        get_user(request, settings.ASTAKOS_URL, fallback_token=token)
56
        if hasattr(request, 'user') and request.user:
57
            groups = request.user.get('groups', [])
58

    
59
            if not groups:
60
                raise PermissionDenied
61

    
62
            for g in groups:
63
                if not g in groups:
64
                    raise PermissionDenied
65
        else:
66
            raise PermissionDenied
67

    
68
        return func(request, *args, **kwargs)
69

    
70
    return wrapper
71

    
72

    
73
@helpdesk_user_required
74
def index(request):
75
    """
76
    Helpdesk index view.
77
    """
78

    
79
    # if form submitted redirect to details
80
    account = request.GET.get('account', None)
81
    if account:
82
        return redirect('synnefo.helpdesk.views.account', account_or_ip=account)
83

    
84
    # show index template
85
    return direct_to_template(request, "helpdesk/index.html")
86

    
87

    
88
@helpdesk_user_required
89
def account(request, account_or_ip):
90
    """
91
    Account details view.
92
    """
93

    
94
    account_exists = True
95
    vms = []
96
    networks = []
97
    is_ip = IP_SEARCH_REGEX.match(account_or_ip)
98
    account = account_or_ip
99

    
100
    if is_ip:
101
        try:
102
            nic = NetworkInterface.objects.get(ipv4=account_or_ip)
103
            account = nic.machine.userid
104
        except NetworkInterface.DoesNotExist:
105
            account_exists = False
106
    else:
107
        # all user vms
108
        vms = VirtualMachine.objects.filter(userid=account).order_by('deleted')
109

    
110
        # return all user private and public networks
111
        public_networks = Network.objects.filter(public=True).order_by('state')
112
        private_networks = Network.objects.filter(userid=account).order_by('state')
113
        networks = list(public_networks) + list(private_networks)
114

    
115
        if vms.count() == 0 and private_networks.count() == 0:
116
            account_exists = False
117

    
118
    user_context = {
119
        'account_exists': account_exists,
120
        'is_ip': is_ip,
121
        'account': account,
122
        'vms': vms,
123
        'networks': networks,
124
        'UI_MEDIA_URL': settings.UI_MEDIA_URL
125
    }
126

    
127
    return direct_to_template(request, "helpdesk/account.html",
128
        extra_context=user_context)
129

    
130

    
131
@helpdesk_user_required
132
def user_list(request):
133
    """
134
    Return a json list of users based on the prefix provided. Prefix
135
    should end with "@".
136
    """
137

    
138
    prefix = request.GET.get('prefix', None)
139
    if not prefix or "@" not in prefix:
140
        raise Http404
141

    
142
    # keep only the user part (e.g. "user@")
143
    prefix = prefix.split("@")[0] + "@"
144

    
145
    q = Q(userid__startswith=prefix) & ~Q(userid=None)
146
    vm_users = VirtualMachine.objects.filter(q).values_list("userid", flat=True)
147
    net_users = Network.objects.filter(q).values_list("userid", flat=True)
148
    users = list(set(list(vm_users) + list(net_users)))
149
    return HttpResponse(json.dumps(users), content_type="application/json")
150