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, last_name=edited_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 def reg_4m_f4f_process(request):
569     if 'submit' in request.POST:
570         return HttpResponse('Registration Successful. Please wait for account validation')
571         
572     
573
574 # view for contact form
575 def contact(request):
576     if request.method == 'POST': # If the form has been submitted...
577         form = ContactForm(request.POST) # A form bound to the POST data
578         if form.is_valid(): # All validation rules pass
579             # Process the data in form.cleaned_data
580             first_name = form.cleaned_data['first_name']
581             last_name = form.cleaned_data['last_name']
582             affiliation = form.cleaned_data['affiliation']
583             subject = form.cleaned_data['subject']
584             message = form.cleaned_data['message']
585             email = form.cleaned_data['email'] # email of the sender
586             cc_myself = form.cleaned_data['cc_myself']
587
588             recipients = ['yasin.upmc@gmail.com']
589             if cc_myself:
590                 recipients.append(email)
591
592             from django.core.mail import send_mail
593             send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
594             return render(request,'contact_sent.html') # Redirect after POST
595     else:
596         form = ContactForm() # An unbound form
597
598     return render(request, 'contact.html', {
599         'form': form,
600     })
601
602
603 def slice_request(request):
604     if request.method == 'POST': # If the form has been submitted...
605         form = SliceRequestForm(request.POST) # A form bound to the POST data
606         if form.is_valid(): # All validation rules pass
607             # Process the data in form.cleaned_data
608             slice_name = form.cleaned_data['slice_name']
609             number_of_nodes = form.cleaned_data['number_of_nodes']
610             type_of_nodes = form.cleaned_data['type_of_nodes']
611             purpose = form.cleaned_data['purpose']
612             email = form.cleaned_data['email'] # email of the sender
613             cc_myself = form.cleaned_data['cc_myself']
614
615             recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
616             if cc_myself:
617                 recipients.append(email)
618
619             from django.core.mail import send_mail
620             send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
621             return render(request,'slicereq_recvd.html') # Redirect after POST
622     else:
623         form = SliceRequestForm() # An unbound form
624
625 #    template_env = {}
626 #    template_env['form'] = form
627 #    template_env['topmenu_items'] = topmenu_items('Request a slice', request) 
628 #    template_env['unfold1_main'] = render(request, 'slice_request_.html', {
629 #        'form': form,
630 #    })
631 #    from django.shortcuts                import render_to_response
632 #    from django.template                 import RequestContext
633 #    return render_to_response ('view-unfold1.html',template_env,
634 #                               context_instance=RequestContext(request))
635
636     return render(request, 'slice_request.html', {
637         'form': form,
638         'topmenu_items': topmenu_items('Request a slice', request),
639         'username': the_user (request) 
640     })
641
642
643 class PresViewView(TemplateView):
644     template_name = "view-unfold1.html"
645
646     def get_context_data(self, **kwargs):
647
648         page = Page(self.request)
649
650         pres_view = PresView(page = page)
651
652         context = super(PresViewView, self).get_context_data(**kwargs)
653
654         #context['ALL_STATIC'] = "all_static"
655         context['unfold1_main'] = pres_view.render(self.request)
656
657         # XXX This is repeated in all pages
658         # more general variables expected in the template
659         context['title'] = 'Test view that combines various plugins'
660         # the menu items on the top
661         context['topmenu_items'] = topmenu_items('PresView', self.request)
662         # so we can sho who is logged
663         context['username'] = the_user(self.request)
664
665         prelude_env = page.prelude_env()
666         context.update(prelude_env)
667
668         return context
669
670 def json_me(config_file,type):
671     json_answer = ''
672     for ligne in config_file:
673         if not ligne.startswith('#'):
674             args = ligne.split(';')
675             json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1]  + '" ,"descriptif":"' + args[2]+'"')
676             if type!="dynamic":
677                 json_answer += str(',"contraints":')
678                 if args[3]=="":
679                     json_answer += str('""')
680                 else:
681                     json_answer += str(args[3])
682             json_answer += str('},')
683     return json_answer[:-1]
684
685
686 DIR = '/var/myslice/'
687 STATIC = '%s/config_method_static' % DIR
688 DYNAMIC = '%s/config_method_dynamic' % DIR
689 ANIMATION = '%s/config_method_animation' % DIR
690
691 def pres_view_methods(request, type):
692
693     if type ==None:
694         return 0
695     elif type =="static":
696         config = open(STATIC, "r")
697         json_answer = str('{ "options": [')
698         json_answer += str(json_me(config,"static"))
699         json_answer += str('] }')
700         config.close()
701     elif type =="dynamic":
702         config = open(DYNAMIC, "r")
703         json_answer = str('{ "options": [')
704         json_answer += str(json_me(config,"dynamic"))
705         json_answer += str('] }')
706         config.close()
707     elif type =="animation":
708         config = open(ANIMATION, "r")
709         json_answer = str('{ "options": [')
710         json_answer += str(json_me(config,"animation"))
711         json_answer += str('] }')
712         config.close()
713     elif type =="all":
714         config = open(STATIC, "r")
715         json_answer = str('{ "static": [')
716         json_answer += str(json_me(config,"static"))
717         json_answer += str('],')
718         json_answer += str('"dynamic": [')
719         config.close()
720         config = open(DYNAMIC, "r")
721         json_answer += str(json_me(config,"dynamic"))
722         json_answer += str('],')
723         json_answer += str('"animation": [')
724         config.close()
725         config = open(ANIMATION, "r")
726         json_answer += str(json_me(config,"animation"))
727         json_answer += str('] }')
728         config.close()
729     else:
730         return 0
731     return HttpResponse (json_answer, mimetype="application/json")
732
733 def pres_view_animation(request, constraints, id):
734
735 # sites crees depuis 2008
736 # static.py?contraints=']date_created':1262325600&id='name_id"'
737
738     # method = request.getvalue('method') #ex : GetSites
739     #constraints = "']date_created':1262325600"
740     #id = "2"
741
742     if id == None:
743         return 0
744
745     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
746     # constraints = {}#request.getvalue('constraints') // nul = {}
747     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
748
749     config_file = open(ANIMATION, "r")
750     for ligne in config_file:
751         if not ligne.startswith('#'):
752             ligne = ligne.split('\n')
753             first = ligne[0].split(';')
754             if (str(first[1]) == str(id)):
755                 save = first
756     config_file.close()
757
758     #Les print_method, print_option sont definis par le client (js)
759     #Les animations acceptent que les connexions anonymous
760     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
761     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
762
763
764     #Creation d'un objet event
765     event = Event(args)
766     cmd = [{"params": {
767             "data": {
768                 "print_options": event.print_options,
769                 "print_method": event.print_method,
770                 "message": event.data
771             }
772         }
773     }]
774
775     json_answer = json.dumps(cmd)
776     return HttpResponse (json_answer, mimetype="application/json")
777
778 def pres_view_static(request, constraints, id):
779     #constraints = "']date_created':1262325600"
780     #id = "2"
781
782     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
783     # constraints = {}#request.getvalue('constraints') // nul = {}
784     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
785
786     config_file = open(STATIC, "r")
787     for ligne in config_file:
788         if not ligne.startswith('#'):
789             ligne = ligne.split('\n')
790             first = ligne[0].split(';')
791             if (str(first[1]) == str(id)):
792                 save = first
793     config_file.close()
794
795     #Les print_method, print_option sont definis par le client (js)
796     #Les animations acceptent que les connexions anonymous
797     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
798     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
799
800
801     #Creation d'un objet event
802     event = Event(args)
803     cmd = [{"params": {
804             "data": {
805                 "print_options": event.print_options,
806                 "print_method": event.print_method,
807                 "message": event.data
808             }
809         }
810     }]
811
812     json_answer = json.dumps(cmd)
813     return HttpResponse (json_answer, mimetype="application/json")