Statistics
| Branch: | Tag: | Revision:

root / snf-saas-app / saas / ui / views.py @ ab17b8df

History | View | Annotate | Download (6.8 kB)

1
# Copyright 2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
import re
35
import logging
36

    
37
from django.shortcuts import render_to_response
38
from django.template import RequestContext
39
from django.conf import settings
40
from django.core.exceptions import PermissionDenied
41
from django.http import HttpResponseRedirect, HttpResponse
42
from django.core.urlresolvers import reverse
43

    
44
from synnefo.lib.astakos import get_user, get_token_from_cookie
45
from kamaki.clients import ClientError
46
import saas.ui.functions as functions
47

    
48

    
49
AUTH_COOKIE_NAME = getattr(settings, 'SAAS_AUTH_COOKIE_NAME', '_pithos2_a')
50
HOSTNAME = getattr(settings, 'SAAS_HOSTNAME', None)
51
API = getattr(settings, 'SAAS_API', None)
52
UI_LOGIN_URL = getattr(settings, 'UI_LOGIN_URL', None)
53
CLOUDBAR = getattr(settings, 'SAAS_CLOUDBAR_ACTIVE_SERVICE', None)
54

    
55
log = logging.getLogger('snf-saas-app')
56

    
57
# --------------------------------------------------------------------
58
# Authendicate user wrapper
59

    
60
def token_check(func):
61
    """
62
    Mimic csrf security check using user auth token.
63
    """
64
    def wrapper(request, *args, **kwargs):
65
        if not hasattr(request, 'user'):
66
            raise PermissionDenied
67
        token = request.POST.get('token', None)
68
        if token and token != request.user.get('auth_token', None):
69
            return func(request, *args, **kwargs)
70
        raise PermissionDenied
71

    
72
    return wrapper
73

    
74
def user_required(func):
75
    """
76
    Django view wrapper that identifies user from token
77
    """
78
    def wrapper(request, *args, **kwargs):
79
        token = get_token_from_cookie(request, AUTH_COOKIE_NAME)
80
        get_user(request, settings.ASTAKOS_URL, fallback_token=token)
81
        if hasattr(request, 'user') and request.user:
82
            pass
83
        else:
84
            uri = request.build_absolute_uri()
85
            if '?' in uri:
86
                uri = uri[:uri.find('?')]
87
            uri = UI_LOGIN_URL + '?next=' + uri
88
            return HttpResponseRedirect(uri)
89

    
90
        log.debug("User %s accessed SaaS" % (request.user_uniq))
91
        return func(request, *args, **kwargs)
92

    
93
    return wrapper
94

    
95

    
96
# --------------------------------------------------------------------
97
# SaaS's views
98

    
99
# ----------------------------
100
@user_required
101
def select_software(request):
102
    token = get_token_from_cookie(request, AUTH_COOKIE_NAME)
103

    
104
    try:
105
        saas_vm = functions.get_saas_server(token)
106
        # There exists a saas server (redirect to status)
107
        log.debug("Server %s found in `select_software', redirecting.."
108
                  % saas_vm)
109
        url = reverse("saas:vm-status")
110
        return HttpResponseRedirect(url)
111
    except LookupError:
112
        pass
113

    
114
    log.debug("No SaaS Server found, let's create one..")
115
    if request.method == 'POST':
116
        software = request.POST.getlist('software')
117
        log.debug("Selected software: %s", software)
118

    
119
        if len(software) > 0:
120
            server = functions.create_saas_server(token,software)
121
            log.debug("Server %s created, redirecting.." % server)
122
            url = reverse("saas:vm-status")
123
            return HttpResponseRedirect(url)
124

    
125
        else:
126
            log.debug("No software selected, nothing to do")
127
            return render_to_response("saas/index.html",
128
                    {'cloud': CLOUDBAR},
129
                    context_instance=RequestContext(request))
130

    
131
    else:
132
        return render_to_response("saas/index.html",
133
                {'cloud': CLOUDBAR},
134
                context_instance=RequestContext(request))
135

    
136
# ----------------------------
137
@user_required
138
def vm_status(request):
139
    token = get_token_from_cookie(request, AUTH_COOKIE_NAME)
140

    
141
    try:
142
        saas_server = functions.get_saas_server(token)
143
    except LookupError:
144
        log.debug("SaaS Server does not exist")
145
        url = reverse("saas:saas-software")
146
        return HttpResponseRedirect(url)
147

    
148
    server_id = saas_server['id']
149
    status = saas_server['status']
150

    
151
    if status == 'ACTIVE':
152
        ip = saas_server['attachments']['values'][0]['ipv4']
153
        link_url = (("%s?ip_address=%s&os=windows&rdp=1&srv=%d" +
154
            "&username=Administrator&domain=snf-%d&hostname=%s") %
155
                (reverse("ui_machines_connect"), ip, int(server_id),
156
                int(server_id), HOSTNAME))
157
        enc_password = saas_server['metadata']['values']['saasPass']
158
        c = {'status': status, 'ip': ip, 'link_url': link_url,
159
             'cloud': CLOUDBAR, 'vm_id': server_id,
160
             'vm_username': "Administrator",
161
             'vm_password': functions.decrypt(enc_password)}
162

    
163
    elif status == 'BUILD':
164
        c = {'status': status, 'cloud': CLOUDBAR}
165

    
166
    else:
167
        raise PemissionDenied
168

    
169
    return render_to_response("saas/status.html", c,
170
            context_instance=RequestContext(request))
171

    
172
# ----------------------------
173
@user_required
174
def index(request):
175
    token = get_token_from_cookie(request, AUTH_COOKIE_NAME)
176

    
177
    try:
178
        saas_vm = functions.get_saas_server(token)
179
        url = reverse("saas:vm-status")
180
        return HttpResponseRedirect(url)
181
    except LookupError:
182
        url = reverse("saas:saas-software")
183
        return HttpResponseRedirect(url)
184

    
185
# ----------------------------
186
@user_required
187
def vm_destroy(request,vm_id):
188
    log.debug("Destroying server %s.." % vm_id)
189
    token = get_token_from_cookie(request, AUTH_COOKIE_NAME)
190
    functions.delete_saas_server(token, vm_id)
191
    url = reverse("saas:saas-index")
192
    return HttpResponseRedirect(url)