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