Merge branch 'jordan' of ssh://git.onelab.eu/git/myslice into jordan
[myslice.git] / portal / views.py
1 # -*- coding: utf-8 -*-
2 #
3 # portal/views.py: views for the portal application
4 # This file is part of the Manifold project.
5 #
6 # Authors:
7 #   Jordan AugĂ© <jordan.auge@lip6.fr>
8 #   Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne UniversitĂ©s / LIP6
10 #
11 # This program is free software; you can redistribute it and/or modify it under
12 # the terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 3, or (at your option) any later version.
14
15 # This program is distributed in the hope that it will be useful, but WITHOUT
16 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18 # details.
19
20 # You should have received a copy of the GNU General Public License along with
21 # this program; see the file COPYING.  If not, write to the Free Software
22 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
24 from django.conf                 import settings
25 from django.contrib.sites.models import Site, RequestSite
26 from django.contrib              import messages
27 from django.views.generic        import View
28 from django.views.generic.base   import TemplateView
29 from django.shortcuts            import render
30
31 from plugins.lists.simplelist    import SimpleList
32
33 from plugins.pres_view           import PresView
34 from portal.event import Event
35 import json
36
37 from portal                      import signals
38 from portal.forms                import UserRegisterForm, SliceRequestForm, ContactForm
39 from portal.util                 import RegistrationView, ActivationView
40 from portal.models               import PendingUser, PendingSlice
41 from manifold.core.query         import Query
42 from unfold.page                 import Page
43 from myslice.viewutils           import topmenu_items, the_user
44 from django.http                 import HttpResponseRedirect, HttpResponse
45 import os.path, re
46
47 class DashboardView(TemplateView):
48     template_name = "dashboard.html"
49
50     def get_context_data(self, **kwargs):
51         # We might have slices on different registries with different user accounts 
52         # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
53         # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
54
55         #messages.info(self.request, 'You have logged in')
56         page = Page(self.request)
57
58         # Slow...
59         #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
60         slice_query = Query().get('user').filter_by('user_hrn', '==', '$user_hrn').select('user_hrn', 'slice.slice_hrn')
61         auth_query  = Query().get('network').select('network_hrn')
62         page.enqueue_query(slice_query)
63         page.enqueue_query(auth_query)
64
65         page.expose_js_metadata()
66         page.expose_queries()
67
68         slicelist = SimpleList(
69             title = None,
70             page  = page,
71             key   = 'slice.slice_hrn',
72             query = slice_query,
73         )
74          
75         authlist = SimpleList(
76             title = None,
77             page  = page,
78             key   = 'network_hrn',
79             query = auth_query,
80         )
81
82         context = super(DashboardView, self).get_context_data(**kwargs)
83         context['person']   = self.request.user
84         context['networks'] = authlist.render(self.request) 
85         context['slices']   = slicelist.render(self.request)
86
87         # XXX This is repeated in all pages
88         # more general variables expected in the template
89         context['title'] = 'Test view that combines various plugins'
90         # the menu items on the top
91         context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
92         # so we can sho who is logged
93         context['username'] = the_user(self.request) 
94
95         context.update(page.prelude_env())
96
97         return context
98
99 class UserRegisterView(RegistrationView):
100     """
101     A registration backend which follows a simple workflow:
102
103     1. User signs up, inactive account is created.
104
105     2. Email is sent to user with activation link.
106
107     3. User clicks activation link, account is now active.
108
109     Using this backend requires that
110
111     * ``registration`` be listed in the ``INSTALLED_APPS`` setting
112       (since this backend makes use of models defined in this
113       application).
114
115     * The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
116       (as an integer) the number of days from registration during
117       which a user may activate their account (after that period
118       expires, activation will be disallowed).
119
120     * The creation of the templates
121       ``registration/activation_email_subject.txt`` and
122       ``registration/activation_email.txt``, which will be used for
123       the activation email. See the notes for this backends
124       ``register`` method for details regarding these templates.
125
126     Additionally, registration can be temporarily closed by adding the
127     setting ``REGISTRATION_OPEN`` and setting it to
128     ``False``. Omitting this setting, or setting it to ``True``, will
129     be interpreted as meaning that registration is currently open and
130     permitt ed.
131
132     Internally, this is accomplished via storing an activation key in
133     an instance of ``registration.models.RegistrationProfile``. See
134     that model and its custom manager for full documentation of its
135     fields and supported operations.
136     
137     """
138     form_class = UserRegisterForm
139     
140     def register(self, request, **cleaned_data):
141         """
142         Given a username, email address and password, register a new
143         user account, which will initially be inactive.
144
145         Along with the new ``User`` object, a new
146         ``registration.models.RegistrationProfile`` will be created,
147         tied to that ``User``, containing the activation key which
148         will be used for this account.
149
150         An email will be sent to the supplied email address; this
151         email should contain an activation link. The email will be
152         rendered using two templates. See the documentation for
153         ``RegistrationProfile.send_activation_email()`` for
154         information about these templates and the contexts provided to
155         them.
156
157         After the ``User`` and ``RegistrationProfile`` are created and
158         the activation email is sent, the signal
159         ``registration.signals.user_registered`` will be sent, with
160         the new ``User`` as the keyword argument ``user`` and the
161         class of this backend as the sender.
162
163         """
164         first_name = cleaned_data['first_name']
165         last_name  = cleaned_data['last_name']
166         affiliation= cleaned_data['affiliation']
167         email      = cleaned_data['email']
168         password   = cleaned_data['password1']
169         
170         #password2  = cleaned_data['password2']
171         keypair    = cleaned_data['keypair']
172
173         #if Site._meta.installed:
174         #    site = Site.objects.get_current()
175         #else:
176         #    site = RequestSite(request) 
177         site = None
178
179         new_user = PendingUser.objects.create_inactive_user(first_name, last_name, email, password, site)
180         signals.user_registered.send(sender=self.__class__,
181                                      user=new_user,
182                                      request=request)
183         return new_user
184
185     def get_context_data(self, **kwargs):
186         context = super(UserRegisterView, self).get_context_data(**kwargs)
187         context['topmenu_items'] = topmenu_items('Register', self.request)
188         context['username'] = the_user (self.request)
189         return context
190
191     def registration_allowed(self, request):
192         """
193         Indicate whether account registration is currently permitted,
194         based on the value of the setting ``REGISTRATION_OPEN``. This
195         is determined as follows:
196
197         * If ``REGISTRATION_OPEN`` is not specified in settings, or is
198           set to ``True``, registration is permitted.
199
200         * If ``REGISTRATION_OPEN`` is both specified and set to
201           ``False``, registration is not permitted.
202         
203         """
204         return getattr(settings, 'REGISTRATION_OPEN', True)
205
206     def get_success_url(self, request, user):
207         """
208         Return the name of the URL to redirect to after successful
209         user registration.
210         
211         """
212         return ('user_register_complete', (), {})
213
214
215 class UserValidateView(ActivationView):
216     def activate(self, request, activation_key):
217         """
218         Given an an activation key, look up and activate the user
219         account corresponding to that key (if possible).
220
221         After successful activation, the signal
222         ``registration.signals.user_activated`` will be sent, with the
223         newly activated ``User`` as the keyword argument ``user`` and
224         the class of this backend as the sender.
225         
226         """
227         activated_user = RegistrationProfile.objects.activate_user(activation_key)
228         if activated_user:
229             signals.user_activated.send(sender=self.__class__,
230                                         user=activated_user,
231                                         request=request)
232         return activated_user
233
234     def get_success_url(self, request, user):
235         return ('registration_activation_complete', (), {})
236
237
238 # DEPRECATED #from portal.portalpage  import PortalPage
239 # DEPRECATED #from plugins.wizard     import Wizard
240 # DEPRECATED #from plugins.form       import CreateForm
241 # DEPRECATED #from plugins.raw.raw    import Raw          # XXX
242 # DEPRECATED #
243 # DEPRECATED #from myslice.viewutils  import the_user
244 # DEPRECATED #
245 # DEPRECATED #from django.template.loader import render_to_string
246 # DEPRECATED #from django.template import RequestContext
247 # DEPRECATED #from django.views import generic
248 # DEPRECATED #
249 # DEPRECATED #from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
250 # DEPRECATED ##from django.core.files.storage import FileSystemStorage
251 # DEPRECATED #from django.core.files.storage import default_storage
252 # DEPRECATED #
253 # DEPRECATED ##class MerlinWizard(NamedUrlSessionWizardView):
254 # DEPRECATED ##
255 # DEPRECATED ##    ...
256 # DEPRECATED ##    ...
257 # DEPRECATED ##
258 # DEPRECATED ##    @classonlymethod
259 # DEPRECATED ##    def as_view(cls, *args, **kwargs):
260 # DEPRECATED ##        kwargs.update({
261 # DEPRECATED ##            'form_list': [
262 # DEPRECATED ##                NameForm,
263 # DEPRECATED ##                QuestForm,
264 # DEPRECATED ##                ColorForm,
265 # DEPRECATED ##            ],
266 # DEPRECATED ##            'url_name': 'merlin_wizard'
267 # DEPRECATED ##        })
268 # DEPRECATED ##        return super(MerlinWizard, cls).as_view(*args, **kwargs)
269 # DEPRECATED #
270 # DEPRECATED #class UserRegisterWizardView(NamedUrlSessionWizardView):
271 # DEPRECATED ##class UserRegisterWizardView(LoginRequiredMixin, NamedUrlSessionWizardView):
272 # DEPRECATED #    # Notice that I specify a file storage instance. If you don't specify this,
273 # DEPRECATED #    # and you need to support FileField or ImageField in your forms, you'll get
274 # DEPRECATED #    # errors from Django. This is something else I think could be handled by
275 # DEPRECATED #    # the views better. Seems to me that it should just use whatever the
276 # DEPRECATED #    # default/specified storage is for the rest of your project/application.
277 # DEPRECATED #    file_storage = default_storage # FileSystemStorage()
278 # DEPRECATED #    template_name = "register_user_wizard.html"
279 # DEPRECATED #
280 # DEPRECATED #    def done(self, form_list, **kwargs):
281 # DEPRECATED #        step1_form = form_list[0]
282 # DEPRECATED #        step2_form = form_list[1]
283 # DEPRECATED #
284 # DEPRECATED #        productext = self.create_product(product_form)
285 # DEPRECATED #        shippings = self.create_shippings(productext, shipping_forms)
286 # DEPRECATED #        images = self.create_images(productext, image_forms)
287 # DEPRECATED #
288 # DEPRECATED #        if all([productext, shippings, images]):
289 # DEPRECATED #            del self.request.session["wizard_product_wizard_view"]
290 # DEPRECATED #
291 # DEPRECATED #            messages.success(self.request,
292 # DEPRECATED #                _("Your product has been created."))
293 # DEPRECATED #            return HttpResponseRedirect(self.get_success_url(productext))
294 # DEPRECATED #
295 # DEPRECATED #        messages.error(self.request, _("Something went wrong creating your "
296 # DEPRECATED #            "product. Please try again or contact support."))
297 # DEPRECATED #        return HttpResponseRedirect(reverse("register_wizard"))
298 # DEPRECATED #
299 # DEPRECATED #    #def get_form_kwargs(self, step):
300 # DEPRECATED #    #    if step == "product":
301 # DEPRECATED #    #        return {"user": self.request.user}
302 # DEPRECATED #    #    return {}
303 # DEPRECATED #
304 # DEPRECATED ## The portal should hook the slice and user creation pages
305 # DEPRECATED #
306 # DEPRECATED #def register_user(request):
307 # DEPRECATED #    
308 # DEPRECATED #    if request.method == 'POST':
309 # DEPRECATED #        form = UserRegisterForm(request.POST) # Nous reprenons les donnĂ©es
310 # DEPRECATED #        if form.is_valid():
311 # DEPRECATED #            first_name = form.cleaned_data['first_name']
312 # DEPRECATED #            last_name  = form.cleaned_data['last_name']
313 # DEPRECATED #            email      = form.cleaned_data['email']
314 # DEPRECATED #            password   = form.cleaned_data['password']
315 # DEPRECATED #            password2  = form.cleaned_data['password2']
316 # DEPRECATED #            keypair    = form.cleaned_data['keypair']
317 # DEPRECATED #            ## Ici nous pouvons traiter les donnĂ©es du formulaire
318 # DEPRECATED #            #sujet = form.cleaned_data['sujet']
319 # DEPRECATED #            #message = form.cleaned_data['message']
320 # DEPRECATED #            #envoyeur = form.cleaned_data['envoyeur']
321 # DEPRECATED #            #renvoi = form.cleaned_data['renvoi']
322 # DEPRECATED #            ## Nous pourrions ici envoyer l'e-mail grâce aux donnĂ©es que nous venons de rĂ©cupĂ©rer
323 # DEPRECATED #            #envoi = True
324 # DEPRECATED #    else:
325 # DEPRECATED #        form = UserRegisterForm()
326 # DEPRECATED #    return render(request, 'register_user.html', locals())
327 # DEPRECATED #
328 # DEPRECATED #def index(request):
329 # DEPRECATED #
330 # DEPRECATED #    WIZARD_TITLE = 'User registration'
331 # DEPRECATED #    STEP1_TITLE  = 'Enter your details'
332 # DEPRECATED #    STEP2_TITLE  = 'Select your institution'
333 # DEPRECATED #    STEP3_TITLE  = 'Authentication'
334 # DEPRECATED #    STEP4_TITLE  = 'Request a slice (optional)'
335 # DEPRECATED #    STEP5_TITLE  = 'Waiting for validation'
336 # DEPRECATED #    STEP6_TITLE  = 'Account validated'
337 # DEPRECATED #
338 # DEPRECATED #    STEP0 = render_to_string('account_validated.html', context_instance=RequestContext(request))
339 # DEPRECATED #    STEP2_HTML   = """
340 # DEPRECATED #    coucou
341 # DEPRECATED #    """
342 # DEPRECATED #    STEP4 = """
343 # DEPRECATED #    mede
344 # DEPRECATED #    """
345 # DEPRECATED #    STEP5 = render_to_string('account_validated.html', context_instance=RequestContext(request))
346 # DEPRECATED #
347 # DEPRECATED #    p = PortalPage(request)
348 # DEPRECATED #
349 # DEPRECATED #    # This is redundant with the Wizard title
350 # DEPRECATED #    p << "<h3>User registration</h3>"
351 # DEPRECATED #
352 # DEPRECATED #    sons = []
353 # DEPRECATED #    start_step = 1
354 # DEPRECATED #
355 # DEPRECATED #    # STEP 1
356 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of his account details
357 # DEPRECATED #    # Otherwise propose a form to fill in
358 # DEPRECATED #    if the_user(request):
359 # DEPRECATED #        # Fill a disabled form with user info
360 # DEPRECATED #        # Please logout to register another user
361 # DEPRECATED #        sons.append(Raw(page=p, title=STEP1_TITLE, togglable=False, html=STEP0))
362 # DEPRECATED #        start_step += 1
363 # DEPRECATED #    else:
364 # DEPRECATED #        # We could pass a list of fields also, instead of retrieving them from metadata
365 # DEPRECATED #        # Otherwise we need some heuristics to display nice forms
366 # DEPRECATED #        # XXX Could we log the user in after the form is validated ?
367 # DEPRECATED #        # XXX Explain the password is for XXX
368 # DEPRECATED #        field_list = [{
369 # DEPRECATED #            'name'        : 'First name',
370 # DEPRECATED #            'field'       : 'firstname',
371 # DEPRECATED #            'type'        : 'text',
372 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
373 # DEPRECATED #            'validate_err': 'Your first name must be comprised of letters only',
374 # DEPRECATED #            'description' : 'Enter your first name',
375 # DEPRECATED #        }, {
376 # DEPRECATED #            'name'        : 'Last name',
377 # DEPRECATED #            'field'       : 'lastname',
378 # DEPRECATED #            'type'        : 'text',
379 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
380 # DEPRECATED #            'validate_err': 'Your last name must be comprised of letters only',
381 # DEPRECATED #            'description' : 'Enter your last name',
382 # DEPRECATED #        }, { 
383 # DEPRECATED #            'name'        : 'Email',
384 # DEPRECATED #            'field'       : 'email',
385 # DEPRECATED #            'type'        : 'text',
386 # DEPRECATED #            'description' : 'Enter your email address',
387 # DEPRECATED #        }, {
388 # DEPRECATED #            'name'        : 'Password',
389 # DEPRECATED #            'field'       : 'password',
390 # DEPRECATED #            'type'        : 'password',
391 # DEPRECATED #            'description' : 'Enter your password',
392 # DEPRECATED #        }, {
393 # DEPRECATED #            'name'        : 'Confirm password',
394 # DEPRECATED #            'field'       : 'password2',
395 # DEPRECATED #            'type'        : 'password',
396 # DEPRECATED #            'description' : 'Enter your password again',
397 # DEPRECATED #        }]
398 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP1_TITLE, togglable = False, object = 'local:user', fields = field_list))
399 # DEPRECATED #
400 # DEPRECATED #    # STEP 2
401 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of its institution
402 # DEPRECATED #    # Otherwise propose a form to fill in (we should base our selection on the email)
403 # DEPRECATED #    if the_user(request):
404 # DEPRECATED #        # Fill a disabled form with institution
405 # DEPRECATED #        # Please logout to register another user
406 # DEPRECATED #        sons.append(Raw(page=p, title=STEP2_TITLE, togglable=False, html="User created"))
407 # DEPRECATED #        start_step += 1
408 # DEPRECATED #    else:
409 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP2_TITLE, togglable = False, object = 'slice')) #institution'))
410 # DEPRECATED #
411 # DEPRECATED #    # STEP3
412 # DEPRECATED #    # Please should your prefered authentication method
413 # DEPRECATED #    # This step should allow the user to either choose the user or managed mode in MySlice
414 # DEPRECATED #    sons.append(Raw(page = p, title = STEP3_TITLE, togglable = False, html = STEP2_HTML))
415 # DEPRECATED #
416 # DEPRECATED #    # Step 4: Request a slice (optional)
417 # DEPRECATED #    sons.append(CreateForm(page = p, title = STEP4_TITLE, togglable = False, object = 'slice'))
418 # DEPRECATED #
419 # DEPRECATED #    # Step 5: Your request is waiting for validation
420 # DEPRECATED #    # Periodic refresh
421 # DEPRECATED #    sons.append(Raw(page = p, title = STEP5_TITLE, togglable = False, html = STEP4))
422 # DEPRECATED #
423 # DEPRECATED #    # Step 6: Account validation  = welcome for newly validated users
424 # DEPRECATED #    # . delegation
425 # DEPRECATED #    # . platforms
426 # DEPRECATED #    # . slice
427 # DEPRECATED #    # . pointers
428 # DEPRECATED #    sons.append(Raw(page = p, title = STEP6_TITLE, togglable = False, html = STEP5))
429 # DEPRECATED #
430 # DEPRECATED #    wizard = Wizard(
431 # DEPRECATED #        page       = p,
432 # DEPRECATED #        title      = WIZARD_TITLE,
433 # DEPRECATED #        togglable  = False,
434 # DEPRECATED #        sons       = sons,
435 # DEPRECATED #        start_step = start_step,
436 # DEPRECATED #    )
437 # DEPRECATED #
438 # DEPRECATED #    p << wizard.render(request) # in portal page if possible
439 # DEPRECATED #
440 # DEPRECATED #    return p.render()
441
442
443 # DEPRECATED ## view for my_account
444 # DEPRECATED # class MyAccountView(TemplateView):
445 # DEPRECATED #    template_name = "my_account.html"
446 # DEPRECATED #    
447 # DEPRECATED #    def from_process(self, request, **cleaned_data): 
448 # DEPRECATED #        #if request.method == 'POST':
449 # DEPRECATED #         #       if request.POST['submit_name']:
450 # DEPRECATED #        if 'fname' in request.POST:            
451 # DEPRECATED #                messsag= "Got Name"
452 # DEPRECATED #                #return render(request, 'portal/my_account.html')
453 # DEPRECATED #                #response = HttpResponse("Here's the text of the Web page.")    
454 # DEPRECATED #                return HttpResponse(message)
455 # DEPRECATED #            
456 # DEPRECATED #    def get_context_data(self, **kwargs):
457 # DEPRECATED #        page = Page(self.request)
458 # DEPRECATED #        context = super(MyAccountView, self).get_context_data(**kwargs)
459 # DEPRECATED #        context['person']   = self.request.user
460 # DEPRECATED #        # XXX This is repeated in all pages
461 # DEPRECATED #        # more general variables expected in the template
462 # DEPRECATED #        context['title'] = 'User Profile Page'
463 # DEPRECATED #        # the menu items on the top
464 # DEPRECATED #        context['topmenu_items'] = topmenu_items('my_account', self.request)
465 # DEPRECATED #        # so we can sho who is logged
466 # DEPRECATED #        context['username'] = the_user(self.request)
467 # DEPRECATED #        context.update(page.prelude_env())
468 # DEPRECATED #        return context
469
470
471
472 # View for my_account form
473 def my_account(request):
474     return render(request, 'my_account.html')
475
476 #my_acc form value processing
477 def acc_process(request):
478     # getting the user_id from the session [now hardcoded]
479     get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
480     if 'submit_name' in request.POST:
481         edited_first_name =  request.POST['fname']
482         edited_last_name =  request.POST['lname']
483         #email = 'test_email@gmail.com'
484         #password = 'test_pp'
485         #message = 'F_Name: %s L_name: %s dummy_pp: %s' % (first_name, last_name, password)
486         #site = None
487         
488         # insert into DB [needed for registration page]
489         #approach borrowed from register view     
490         #new_user = PendingUser.objects.create_inactive_user(edited_first_name, edited_last_name, email,  password, site) 
491         #conventional approach
492         #b = PendingUser(first_name=edited_first_name, edited_last_name=last_name)
493         #b.save()
494         
495         # select and update [will be used throughout this view]
496         # select the logged in user [for the moment hard coded]
497         #get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
498         # update first and last name
499         get_user.first_name = edited_first_name
500         get_user.last_name = edited_last_name
501         get_user.save() 
502
503         return HttpResponse('Success: Name Updated!!')       
504     elif 'submit_pass' in request.POST:
505         edited_password = request.POST['password']
506         # select the logged in user [for the moment hard coded]
507         #get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
508         # update password
509         get_user.password = edited_password
510         get_user.save()
511         return HttpResponse('Success: Password Changed!!')
512     elif 'generate' in request.POST:
513         import os
514         from M2Crypto import Rand, RSA, BIO
515
516         KEY_LENGTH = 2048
517
518         def blank_callback():
519             "Replace the default dashes"
520             return
521
522         # Random seed
523         Rand.rand_seed (os.urandom (KEY_LENGTH))
524         # Generate key pair
525         key = RSA.gen_key (KEY_LENGTH, 65537, blank_callback)
526         # Create memory buffers
527         pri_mem = BIO.MemoryBuffer()
528         pub_mem = BIO.MemoryBuffer()
529         # Save keys to buffers
530         key.save_key_bio(pri_mem, None)
531         key.save_pub_key_bio(pub_mem)
532
533         # Get keys 
534         public_key = pub_mem.getvalue()
535         private_key = pri_mem.getvalue()
536         # Saving to DB
537         keypair = '{"user_public_key":"'+ public_key + '", "user_private_key":"'+ private_key + '"}'
538         #keypair = re.sub("\r", "", keypair)
539         #keypair = re.sub("\n", "\\n", keypair)
540         keypair = keypair.rstrip('\r\n')
541         get_user.keypair = keypair
542         get_user.save()
543         return HttpResponse('Success: New Keypair Generated! %s' % keypair)
544
545     elif 'upload_key' in request.POST:
546         up_file = request.FILES['pubkey']
547         file_content =  up_file.read()
548         file_name = up_file.name
549         file_extension = os.path.splitext(file_name)[1] 
550         allowed_extension =  ['.pub','.txt']
551         if file_extension in allowed_extension:
552             file_content = '{"user_public_key":"'+ file_content +'"}'
553             file_content = re.sub("\r", "", file_content)
554             file_content = re.sub("\n", "\\n",file_content)
555             get_user.keypair = file_content
556             get_user.save()
557             return HttpResponse('Success: Publickey uploaded! Old records overwritten')
558         else:
559             return HttpResponse('Please upload a valid public key.')    
560         
561     else:
562         message = 'You submitted an empty form.'
563         return HttpResponse(message)
564
565 def register_4m_f4f(request):
566     return render(request, 'register_4m_f4f.html')
567
568 # view for contact form
569 def contact(request):
570     if request.method == 'POST': # If the form has been submitted...
571         form = ContactForm(request.POST) # A form bound to the POST data
572         if form.is_valid(): # All validation rules pass
573             # Process the data in form.cleaned_data
574             first_name = form.cleaned_data['first_name']
575             last_name = form.cleaned_data['last_name']
576             affiliation = form.cleaned_data['affiliation']
577             subject = form.cleaned_data['subject']
578             message = form.cleaned_data['message']
579             email = form.cleaned_data['email'] # email of the sender
580             cc_myself = form.cleaned_data['cc_myself']
581
582             recipients = ['yasin.upmc@gmail.com']
583             if cc_myself:
584                 recipients.append(email)
585
586             from django.core.mail import send_mail
587             send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
588             return render(request,'contact_sent.html') # Redirect after POST
589     else:
590         form = ContactForm() # An unbound form
591
592     return render(request, 'contact.html', {
593         'form': form,
594     })
595
596
597 def slice_request(request):
598     if request.method == 'POST': # If the form has been submitted...
599         form = SliceRequestForm(request.POST) # A form bound to the POST data
600         if form.is_valid(): # All validation rules pass
601             # Process the data in form.cleaned_data
602             slice_name = form.cleaned_data['slice_name']
603             number_of_nodes = form.cleaned_data['number_of_nodes']
604             type_of_nodes = form.cleaned_data['type_of_nodes']
605             purpose = form.cleaned_data['purpose']
606             email = form.cleaned_data['email'] # email of the sender
607             cc_myself = form.cleaned_data['cc_myself']
608
609             recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
610             if cc_myself:
611                 recipients.append(email)
612
613             from django.core.mail import send_mail
614             send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
615             return render(request,'slicereq_recvd.html') # Redirect after POST
616     else:
617         form = SliceRequestForm() # An unbound form
618
619 #    template_env = {}
620 #    template_env['form'] = form
621 #    template_env['topmenu_items'] = topmenu_items('Request a slice', request) 
622 #    template_env['unfold1_main'] = render(request, 'slice_request_.html', {
623 #        'form': form,
624 #    })
625 #    from django.shortcuts                import render_to_response
626 #    from django.template                 import RequestContext
627 #    return render_to_response ('view-unfold1.html',template_env,
628 #                               context_instance=RequestContext(request))
629
630     return render(request, 'slice_request.html', {
631         'form': form,
632         'topmenu_items': topmenu_items('Request a slice', request),
633         'username': the_user (request) 
634     })
635
636
637 class PresViewView(TemplateView):
638     template_name = "view-unfold1.html"
639
640     def get_context_data(self, **kwargs):
641
642         page = Page(self.request)
643
644         pres_view = PresView(page = page)
645
646         context = super(PresViewView, self).get_context_data(**kwargs)
647
648         #context['ALL_STATIC'] = "all_static"
649         context['unfold1_main'] = pres_view.render(self.request)
650
651         # XXX This is repeated in all pages
652         # more general variables expected in the template
653         context['title'] = 'Test view that combines various plugins'
654         # the menu items on the top
655         context['topmenu_items'] = topmenu_items('PresView', self.request)
656         # so we can sho who is logged
657         context['username'] = the_user(self.request)
658
659         prelude_env = page.prelude_env()
660         context.update(prelude_env)
661
662         return context
663
664 def json_me(config_file,type):
665     json_answer = ''
666     for ligne in config_file:
667         if not ligne.startswith('#'):
668             args = ligne.split(';')
669             json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1]  + '" ,"descriptif":"' + args[2]+'"')
670             if type!="dynamic":
671                 json_answer += str(',"contraints":')
672                 if args[3]=="":
673                     json_answer += str('""')
674                 else:
675                     json_answer += str(args[3])
676             json_answer += str('},')
677     return json_answer[:-1]
678
679
680 DIR = '/var/myslice/'
681 STATIC = '%s/config_method_static' % DIR
682 DYNAMIC = '%s/config_method_dynamic' % DIR
683 ANIMATION = '%s/config_method_animation' % DIR
684
685 def pres_view_methods(request, type):
686
687     if type ==None:
688         return 0
689     elif type =="static":
690         config = open(STATIC, "r")
691         json_answer = str('{ "options": [')
692         json_answer += str(json_me(config,"static"))
693         json_answer += str('] }')
694         config.close()
695     elif type =="dynamic":
696         config = open(DYNAMIC, "r")
697         json_answer = str('{ "options": [')
698         json_answer += str(json_me(config,"dynamic"))
699         json_answer += str('] }')
700         config.close()
701     elif type =="animation":
702         config = open(ANIMATION, "r")
703         json_answer = str('{ "options": [')
704         json_answer += str(json_me(config,"animation"))
705         json_answer += str('] }')
706         config.close()
707     elif type =="all":
708         config = open(STATIC, "r")
709         json_answer = str('{ "static": [')
710         json_answer += str(json_me(config,"static"))
711         json_answer += str('],')
712         json_answer += str('"dynamic": [')
713         config.close()
714         config = open(DYNAMIC, "r")
715         json_answer += str(json_me(config,"dynamic"))
716         json_answer += str('],')
717         json_answer += str('"animation": [')
718         config.close()
719         config = open(ANIMATION, "r")
720         json_answer += str(json_me(config,"animation"))
721         json_answer += str('] }')
722         config.close()
723     else:
724         return 0
725     return HttpResponse (json_answer, mimetype="application/json")
726
727 def pres_view_animation(request, constraints, id):
728
729 # sites crees depuis 2008
730 # static.py?contraints=']date_created':1262325600&id='name_id"'
731
732     # method = request.getvalue('method') #ex : GetSites
733     #constraints = "']date_created':1262325600"
734     #id = "2"
735
736     if id == None:
737         return 0
738
739     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
740     # constraints = {}#request.getvalue('constraints') // nul = {}
741     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
742
743     config_file = open(ANIMATION, "r")
744     for ligne in config_file:
745         if not ligne.startswith('#'):
746             ligne = ligne.split('\n')
747             first = ligne[0].split(';')
748             if (str(first[1]) == str(id)):
749                 save = first
750     config_file.close()
751
752     #Les print_method, print_option sont definis par le client (js)
753     #Les animations acceptent que les connexions anonymous
754     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
755     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
756
757
758     #Creation d'un objet event
759     event = Event(args)
760     cmd = [{"params": {
761             "data": {
762                 "print_options": event.print_options,
763                 "print_method": event.print_method,
764                 "message": event.data
765             }
766         }
767     }]
768
769     json_answer = json.dumps(cmd)
770     return HttpResponse (json_answer, mimetype="application/json")
771
772 def pres_view_static(request, constraints, id):
773     #constraints = "']date_created':1262325600"
774     #id = "2"
775
776     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
777     # constraints = {}#request.getvalue('constraints') // nul = {}
778     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
779
780     config_file = open(STATIC, "r")
781     for ligne in config_file:
782         if not ligne.startswith('#'):
783             ligne = ligne.split('\n')
784             first = ligne[0].split(';')
785             if (str(first[1]) == str(id)):
786                 save = first
787     config_file.close()
788
789     #Les print_method, print_option sont definis par le client (js)
790     #Les animations acceptent que les connexions anonymous
791     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
792     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
793
794
795     #Creation d'un objet event
796     event = Event(args)
797     cmd = [{"params": {
798             "data": {
799                 "print_options": event.print_options,
800                 "print_method": event.print_method,
801                 "message": event.data
802             }
803         }
804     }]
805
806     json_answer = json.dumps(cmd)
807     return HttpResponse (json_answer, mimetype="application/json")