Statistics
| Branch: | Tag: | Revision:

root / snf-saas-app / synnefo / saas / views.py @ df95d930

History | View | Annotate | Download (5.5 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 redirect, get_object_or_404, render_to_response
38
from django.template import Context, loader
39
from django.conf import settings
40
from django.views.generic.simple import direct_to_template
41
from django.core.exceptions import PermissionDenied
42
from django.http import Http404, HttpResponse, HttpResponseRedirect
43
from django.core.urlresolvers import reverse
44

    
45
from synnefo.lib.astakos import get_user
46
from synnefo.saas.forms import VMSettings
47

    
48
from itertools import chain
49
from urllib import unquote
50

    
51
from kamaki.clients.compute import ComputeClient
52
from kamaki.clients.cyclades import CycladesClient
53
from kamaki.clients.image import ImageClient
54
from kamaki.clients import ClientError
55

    
56

    
57
# Demo settings
58
API = "https://cyclades.okeanos.io/api/v1.1"
59
TOKEN = "OwmGvNejXe3KQSh4/F2X+g=="
60
IMAGE_ID = "cba883ae-c261-4df6-9f14-37b39cbf56da"
61
FLAVOR_ID = 81
62

    
63
log = logging.getLogger('snf-saas-app')
64

    
65

    
66
def get_token_from_cookie(request, cookiename):
67
    """
68
    Extract token from the cookie name provided. Cookie should be in the same
69
    form as astakos service sets its cookie contents::
70

71
        <user_uniq>|<user_token>
72
    """
73
    try:
74
        cookie_content = unquote(request.COOKIES.get(cookiename, None))
75
        return cookie_content.split("|")[1]
76
    except AttributeError:
77
        pass
78

    
79
    return None
80

    
81

    
82
def token_check(func):
83
    """
84
    Mimic csrf security check using user auth token.
85
    """
86
    def wrapper(request, *args, **kwargs):
87
        if not hasattr(request, 'user'):
88
            raise PermissionDenied
89

    
90
        token = request.POST.get('token', None)
91
        if token and token != request.user.get('auth_token', None):
92
            return func(request, *args, **kwargs)
93

    
94
        raise PermissionDenied
95

    
96
    return wrapper
97

    
98
def user_required(func):
99
    """
100
    Django view wrapper that identifies user from token
101
    """
102

    
103
    def wrapper(request, *args, **kwargs):
104

    
105
        token = get_token_from_cookie(request, AUTH_COOKIE_NAME)
106
        get_user(request, ASTAKOS_URL, fallback_token=token)
107

    
108
        print token
109

    
110
        has_perm = False
111
        if hasattr(request, 'user') and request.user:
112
            has_perm = True
113

    
114
        if not has_perm:
115
            raise PermissionDenied
116

    
117
        logging.debug("User %s accessed helpdesk view" % (request.user_uniq))
118
        return func(request, *args, **kwargs)
119

    
120
    return wrapper
121

    
122

    
123
def index(request):
124

    
125
    form = VMSettings()
126

    
127
    return render_to_response("saas/index.html", {'form': form})
128

    
129

    
130
def select_software(request):
131
    if request.method ==  'POST':
132

    
133
        form = VMSettings(request.POST)
134

    
135
        if form.is_valid():
136

    
137
            client = ComputeClient(API, TOKEN)
138

    
139
            software = request.POST.getlist('software')
140
            server_name = form.cleaned_data['name']
141

    
142
            #Logging
143
            log.info("Software selected")
144
            log.info(software)
145

    
146
            server = client.create_server(server_name, FLAVOR_ID, IMAGE_ID, None)
147
            log.info(server)
148

    
149
            url = '/saas/status/%s' % str(server["id"])
150

    
151
            return HttpResponseRedirect(url)
152

    
153
        else:
154
            return render_to_response("saas/index.html",{'form': form})
155

    
156
    else:
157
        return HttpResponseRedirect("/saas/software/")
158

    
159
def vm_status(request,vm_id):
160
    
161
    log.info(vm_id)
162
    
163
    client = ComputeClient(API, TOKEN)
164
    details = client.get_server_details(vm_id)
165
    status = details["status"]
166

    
167
    #Logging
168
    log.info(status)
169

    
170
    if status == 'ACTIVE':
171
        active = True
172
        ip = details["attachments"]["values"][0]["ipv4"]
173
        
174
        rdp_tuple = (ip,int(vm_id),int(vm_id))
175

    
176
        rdp = "https://cyclades.okeanos.io/machines/connect?ip_address=%s&os=windows&rdp=1&srv=%d&username=Administrator&domain=snf-%d&hostname=gate.okeanos.io"%rdp_tuple
177

    
178
        template = loader.get_template('saas/status.html')
179
        context = Context({'active': active, 'ip': ip, 'rdp': rdp})
180
        
181
    else:
182
        active = False
183
        template = loader.get_template('saas/status.html')
184
        context = Context({'active': active,})
185

    
186

    
187

    
188
    return HttpResponse(template.render(context))
189