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 from plugins.lists.simplelist    import SimpleList
31 from portal                      import signals
32 from portal.forms                import UserRegisterForm, SliceRequestForm, ContactForm
33 from portal.util                 import RegistrationView, ActivationView
34 from portal.models               import PendingUser, PendingSlice
35 from manifold.core.query         import Query
36 from unfold.page                 import Page
37 from myslice.viewutils           import topmenu_items, the_user
38 from django.http                 import HttpResponseRedirect
39
40 class DashboardView(TemplateView):
41     template_name = "dashboard.html"
42
43     def get_context_data(self, **kwargs):
44         user_hrn = 'ple.upmc.jordan_auge'
45
46         #messages.info(self.request, 'You have logged in')
47         page = Page(self.request)
48
49         # Slow...
50         #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
51         slice_query = Query().get('user').filter_by('user_hrn', '==', user_hrn).select('user_hrn', 'slice.slice_hrn')
52         auth_query  = Query().get('network').select('network_hrn')
53         page.enqueue_query(slice_query)
54         page.enqueue_query(auth_query)
55
56         page.expose_queries()
57
58         slicelist = SimpleList(
59             title = None,
60             page  = page,
61             key   = 'slice.slice_hrn',
62             query = slice_query,
63         )
64          
65         authlist = SimpleList(
66             title = None,
67             page  = page,
68             key   = 'network_hrn',
69             query = auth_query,
70         )
71
72         context = super(DashboardView, self).get_context_data(**kwargs)
73         context['person']   = self.request.user
74         context['networks'] = authlist.render(self.request) 
75         context['slices']   = slicelist.render(self.request)
76
77         # XXX This is repeated in all pages
78         # more general variables expected in the template
79         context['title'] = 'Test view that combines various plugins'
80         # the menu items on the top
81         context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
82         # so we can sho who is logged
83         context['username'] = the_user(self.request) 
84
85         context.update(page.prelude_env())
86
87         return context
88
89 class UserRegisterView(RegistrationView):
90     """
91     A registration backend which follows a simple workflow:
92
93     1. User signs up, inactive account is created.
94
95     2. Email is sent to user with activation link.
96
97     3. User clicks activation link, account is now active.
98
99     Using this backend requires that
100
101     * ``registration`` be listed in the ``INSTALLED_APPS`` setting
102       (since this backend makes use of models defined in this
103       application).
104
105     * The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
106       (as an integer) the number of days from registration during
107       which a user may activate their account (after that period
108       expires, activation will be disallowed).
109
110     * The creation of the templates
111       ``registration/activation_email_subject.txt`` and
112       ``registration/activation_email.txt``, which will be used for
113       the activation email. See the notes for this backends
114       ``register`` method for details regarding these templates.
115
116     Additionally, registration can be temporarily closed by adding the
117     setting ``REGISTRATION_OPEN`` and setting it to
118     ``False``. Omitting this setting, or setting it to ``True``, will
119     be interpreted as meaning that registration is currently open and
120     permitted.
121
122     Internally, this is accomplished via storing an activation key in
123     an instance of ``registration.models.RegistrationProfile``. See
124     that model and its custom manager for full documentation of its
125     fields and supported operations.
126     
127     """
128     form_class = UserRegisterForm
129     
130     def register(self, request, **cleaned_data):
131         """
132         Given a username, email address and password, register a new
133         user account, which will initially be inactive.
134
135         Along with the new ``User`` object, a new
136         ``registration.models.RegistrationProfile`` will be created,
137         tied to that ``User``, containing the activation key which
138         will be used for this account.
139
140         An email will be sent to the supplied email address; this
141         email should contain an activation link. The email will be
142         rendered using two templates. See the documentation for
143         ``RegistrationProfile.send_activation_email()`` for
144         information about these templates and the contexts provided to
145         them.
146
147         After the ``User`` and ``RegistrationProfile`` are created and
148         the activation email is sent, the signal
149         ``registration.signals.user_registered`` will be sent, with
150         the new ``User`` as the keyword argument ``user`` and the
151         class of this backend as the sender.
152
153         """
154         first_name = cleaned_data['first_name']
155         last_name  = cleaned_data['last_name']
156         affiliation= cleaned_data['affiliation']
157         email      = cleaned_data['email']
158         password   = cleaned_data['password1']
159         
160         #password2  = cleaned_data['password2']
161         keypair    = cleaned_data['keypair']
162
163         #if Site._meta.installed:
164         #    site = Site.objects.get_current()
165         #else:
166         #    site = RequestSite(request) 
167         site = None
168
169         new_user = PendingUser.objects.create_inactive_user(first_name, last_name, email, password, site)
170         signals.user_registered.send(sender=self.__class__,
171                                      user=new_user,
172                                      request=request)
173         return new_user
174
175     def get_context_data(self, **kwargs):
176         context = super(UserRegisterView, self).get_context_data(**kwargs)
177         context['topmenu_items'] = topmenu_items('Register', self.request)
178         context['username'] = the_user (self.request)
179         return context
180
181     def registration_allowed(self, request):
182         """
183         Indicate whether account registration is currently permitted,
184         based on the value of the setting ``REGISTRATION_OPEN``. This
185         is determined as follows:
186
187         * If ``REGISTRATION_OPEN`` is not specified in settings, or is
188           set to ``True``, registration is permitted.
189
190         * If ``REGISTRATION_OPEN`` is both specified and set to
191           ``False``, registration is not permitted.
192         
193         """
194         return getattr(settings, 'REGISTRATION_OPEN', True)
195
196     def get_success_url(self, request, user):
197         """
198         Return the name of the URL to redirect to after successful
199         user registration.
200         
201         """
202         return ('user_register_complete', (), {})
203
204
205 class UserValidateView(ActivationView):
206     def activate(self, request, activation_key):
207         """
208         Given an an activation key, look up and activate the user
209         account corresponding to that key (if possible).
210
211         After successful activation, the signal
212         ``registration.signals.user_activated`` will be sent, with the
213         newly activated ``User`` as the keyword argument ``user`` and
214         the class of this backend as the sender.
215         
216         """
217         activated_user = RegistrationProfile.objects.activate_user(activation_key)
218         if activated_user:
219             signals.user_activated.send(sender=self.__class__,
220                                         user=activated_user,
221                                         request=request)
222         return activated_user
223
224     def get_success_url(self, request, user):
225         return ('registration_activation_complete', (), {})
226
227
228 # DEPRECATED #from portal.portalpage  import PortalPage
229 # DEPRECATED #from plugins.wizard     import Wizard
230 # DEPRECATED #from plugins.form       import CreateForm
231 # DEPRECATED #from plugins.raw.raw    import Raw          # XXX
232 # DEPRECATED #
233 # DEPRECATED #from myslice.viewutils  import the_user
234 # DEPRECATED #
235 # DEPRECATED #from django.template.loader import render_to_string
236 # DEPRECATED #from django.template import RequestContext
237 # DEPRECATED #from django.views import generic
238 # DEPRECATED #
239 # DEPRECATED #from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
240 # DEPRECATED ##from django.core.files.storage import FileSystemStorage
241 # DEPRECATED #from django.core.files.storage import default_storage
242 # DEPRECATED #
243 # DEPRECATED ##class MerlinWizard(NamedUrlSessionWizardView):
244 # DEPRECATED ##
245 # DEPRECATED ##    ...
246 # DEPRECATED ##    ...
247 # DEPRECATED ##
248 # DEPRECATED ##    @classonlymethod
249 # DEPRECATED ##    def as_view(cls, *args, **kwargs):
250 # DEPRECATED ##        kwargs.update({
251 # DEPRECATED ##            'form_list': [
252 # DEPRECATED ##                NameForm,
253 # DEPRECATED ##                QuestForm,
254 # DEPRECATED ##                ColorForm,
255 # DEPRECATED ##            ],
256 # DEPRECATED ##            'url_name': 'merlin_wizard'
257 # DEPRECATED ##        })
258 # DEPRECATED ##        return super(MerlinWizard, cls).as_view(*args, **kwargs)
259 # DEPRECATED #
260 # DEPRECATED #class UserRegisterWizardView(NamedUrlSessionWizardView):
261 # DEPRECATED ##class UserRegisterWizardView(LoginRequiredMixin, NamedUrlSessionWizardView):
262 # DEPRECATED #    # Notice that I specify a file storage instance. If you don't specify this,
263 # DEPRECATED #    # and you need to support FileField or ImageField in your forms, you'll get
264 # DEPRECATED #    # errors from Django. This is something else I think could be handled by
265 # DEPRECATED #    # the views better. Seems to me that it should just use whatever the
266 # DEPRECATED #    # default/specified storage is for the rest of your project/application.
267 # DEPRECATED #    file_storage = default_storage # FileSystemStorage()
268 # DEPRECATED #    template_name = "register_user_wizard.html"
269 # DEPRECATED #
270 # DEPRECATED #    def done(self, form_list, **kwargs):
271 # DEPRECATED #        step1_form = form_list[0]
272 # DEPRECATED #        step2_form = form_list[1]
273 # DEPRECATED #
274 # DEPRECATED #        productext = self.create_product(product_form)
275 # DEPRECATED #        shippings = self.create_shippings(productext, shipping_forms)
276 # DEPRECATED #        images = self.create_images(productext, image_forms)
277 # DEPRECATED #
278 # DEPRECATED #        if all([productext, shippings, images]):
279 # DEPRECATED #            del self.request.session["wizard_product_wizard_view"]
280 # DEPRECATED #
281 # DEPRECATED #            messages.success(self.request,
282 # DEPRECATED #                _("Your product has been created."))
283 # DEPRECATED #            return HttpResponseRedirect(self.get_success_url(productext))
284 # DEPRECATED #
285 # DEPRECATED #        messages.error(self.request, _("Something went wrong creating your "
286 # DEPRECATED #            "product. Please try again or contact support."))
287 # DEPRECATED #        return HttpResponseRedirect(reverse("register_wizard"))
288 # DEPRECATED #
289 # DEPRECATED #    #def get_form_kwargs(self, step):
290 # DEPRECATED #    #    if step == "product":
291 # DEPRECATED #    #        return {"user": self.request.user}
292 # DEPRECATED #    #    return {}
293 # DEPRECATED #
294 # DEPRECATED ## The portal should hook the slice and user creation pages
295 # DEPRECATED #
296 # DEPRECATED #def register_user(request):
297 # DEPRECATED #    
298 # DEPRECATED #    if request.method == 'POST':
299 # DEPRECATED #        form = UserRegisterForm(request.POST) # Nous reprenons les données
300 # DEPRECATED #        if form.is_valid():
301 # DEPRECATED #            first_name = form.cleaned_data['first_name']
302 # DEPRECATED #            last_name  = form.cleaned_data['last_name']
303 # DEPRECATED #            email      = form.cleaned_data['email']
304 # DEPRECATED #            password   = form.cleaned_data['password']
305 # DEPRECATED #            password2  = form.cleaned_data['password2']
306 # DEPRECATED #            keypair    = form.cleaned_data['keypair']
307 # DEPRECATED #            ## Ici nous pouvons traiter les données du formulaire
308 # DEPRECATED #            #sujet = form.cleaned_data['sujet']
309 # DEPRECATED #            #message = form.cleaned_data['message']
310 # DEPRECATED #            #envoyeur = form.cleaned_data['envoyeur']
311 # DEPRECATED #            #renvoi = form.cleaned_data['renvoi']
312 # DEPRECATED #            ## Nous pourrions ici envoyer l'e-mail grâce aux données que nous venons de récupérer
313 # DEPRECATED #            #envoi = True
314 # DEPRECATED #    else:
315 # DEPRECATED #        form = UserRegisterForm()
316 # DEPRECATED #    return render(request, 'register_user.html', locals())
317 # DEPRECATED #
318 # DEPRECATED #def index(request):
319 # DEPRECATED #
320 # DEPRECATED #    WIZARD_TITLE = 'User registration'
321 # DEPRECATED #    STEP1_TITLE  = 'Enter your details'
322 # DEPRECATED #    STEP2_TITLE  = 'Select your institution'
323 # DEPRECATED #    STEP3_TITLE  = 'Authentication'
324 # DEPRECATED #    STEP4_TITLE  = 'Request a slice (optional)'
325 # DEPRECATED #    STEP5_TITLE  = 'Waiting for validation'
326 # DEPRECATED #    STEP6_TITLE  = 'Account validated'
327 # DEPRECATED #
328 # DEPRECATED #    STEP0 = render_to_string('account_validated.html', context_instance=RequestContext(request))
329 # DEPRECATED #    STEP2_HTML   = """
330 # DEPRECATED #    coucou
331 # DEPRECATED #    """
332 # DEPRECATED #    STEP4 = """
333 # DEPRECATED #    mede
334 # DEPRECATED #    """
335 # DEPRECATED #    STEP5 = render_to_string('account_validated.html', context_instance=RequestContext(request))
336 # DEPRECATED #
337 # DEPRECATED #    p = PortalPage(request)
338 # DEPRECATED #
339 # DEPRECATED #    # This is redundant with the Wizard title
340 # DEPRECATED #    p << "<h3>User registration</h3>"
341 # DEPRECATED #
342 # DEPRECATED #    sons = []
343 # DEPRECATED #    start_step = 1
344 # DEPRECATED #
345 # DEPRECATED #    # STEP 1
346 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of his account details
347 # DEPRECATED #    # Otherwise propose a form to fill in
348 # DEPRECATED #    if the_user(request):
349 # DEPRECATED #        # Fill a disabled form with user info
350 # DEPRECATED #        # Please logout to register another user
351 # DEPRECATED #        sons.append(Raw(page=p, title=STEP1_TITLE, togglable=False, html=STEP0))
352 # DEPRECATED #        start_step += 1
353 # DEPRECATED #    else:
354 # DEPRECATED #        # We could pass a list of fields also, instead of retrieving them from metadata
355 # DEPRECATED #        # Otherwise we need some heuristics to display nice forms
356 # DEPRECATED #        # XXX Could we log the user in after the form is validated ?
357 # DEPRECATED #        # XXX Explain the password is for XXX
358 # DEPRECATED #        field_list = [{
359 # DEPRECATED #            'name'        : 'First name',
360 # DEPRECATED #            'field'       : 'firstname',
361 # DEPRECATED #            'type'        : 'text',
362 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
363 # DEPRECATED #            'validate_err': 'Your first name must be comprised of letters only',
364 # DEPRECATED #            'description' : 'Enter your first name',
365 # DEPRECATED #        }, {
366 # DEPRECATED #            'name'        : 'Last name',
367 # DEPRECATED #            'field'       : 'lastname',
368 # DEPRECATED #            'type'        : 'text',
369 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
370 # DEPRECATED #            'validate_err': 'Your last name must be comprised of letters only',
371 # DEPRECATED #            'description' : 'Enter your last name',
372 # DEPRECATED #        }, { 
373 # DEPRECATED #            'name'        : 'Email',
374 # DEPRECATED #            'field'       : 'email',
375 # DEPRECATED #            'type'        : 'text',
376 # DEPRECATED #            'description' : 'Enter your email address',
377 # DEPRECATED #        }, {
378 # DEPRECATED #            'name'        : 'Password',
379 # DEPRECATED #            'field'       : 'password',
380 # DEPRECATED #            'type'        : 'password',
381 # DEPRECATED #            'description' : 'Enter your password',
382 # DEPRECATED #        }, {
383 # DEPRECATED #            'name'        : 'Confirm password',
384 # DEPRECATED #            'field'       : 'password2',
385 # DEPRECATED #            'type'        : 'password',
386 # DEPRECATED #            'description' : 'Enter your password again',
387 # DEPRECATED #        }]
388 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP1_TITLE, togglable = False, object = 'local:user', fields = field_list))
389 # DEPRECATED #
390 # DEPRECATED #    # STEP 2
391 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of its institution
392 # DEPRECATED #    # Otherwise propose a form to fill in (we should base our selection on the email)
393 # DEPRECATED #    if the_user(request):
394 # DEPRECATED #        # Fill a disabled form with institution
395 # DEPRECATED #        # Please logout to register another user
396 # DEPRECATED #        sons.append(Raw(page=p, title=STEP2_TITLE, togglable=False, html="User created"))
397 # DEPRECATED #        start_step += 1
398 # DEPRECATED #    else:
399 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP2_TITLE, togglable = False, object = 'slice')) #institution'))
400 # DEPRECATED #
401 # DEPRECATED #    # STEP3
402 # DEPRECATED #    # Please should your prefered authentication method
403 # DEPRECATED #    # This step should allow the user to either choose the user or managed mode in MySlice
404 # DEPRECATED #    sons.append(Raw(page = p, title = STEP3_TITLE, togglable = False, html = STEP2_HTML))
405 # DEPRECATED #
406 # DEPRECATED #    # Step 4: Request a slice (optional)
407 # DEPRECATED #    sons.append(CreateForm(page = p, title = STEP4_TITLE, togglable = False, object = 'slice'))
408 # DEPRECATED #
409 # DEPRECATED #    # Step 5: Your request is waiting for validation
410 # DEPRECATED #    # Periodic refresh
411 # DEPRECATED #    sons.append(Raw(page = p, title = STEP5_TITLE, togglable = False, html = STEP4))
412 # DEPRECATED #
413 # DEPRECATED #    # Step 6: Account validation  = welcome for newly validated users
414 # DEPRECATED #    # . delegation
415 # DEPRECATED #    # . platforms
416 # DEPRECATED #    # . slice
417 # DEPRECATED #    # . pointers
418 # DEPRECATED #    sons.append(Raw(page = p, title = STEP6_TITLE, togglable = False, html = STEP5))
419 # DEPRECATED #
420 # DEPRECATED #    wizard = Wizard(
421 # DEPRECATED #        page       = p,
422 # DEPRECATED #        title      = WIZARD_TITLE,
423 # DEPRECATED #        togglable  = False,
424 # DEPRECATED #        sons       = sons,
425 # DEPRECATED #        start_step = start_step,
426 # DEPRECATED #    )
427 # DEPRECATED #
428 # DEPRECATED #    p << wizard.render(request) # in portal page if possible
429 # DEPRECATED #
430 # DEPRECATED #    return p.render()
431
432 class MyAccountView(TemplateView):
433     template_name = "my_account.html"
434
435     def get_context_data(self, **kwargs):
436         #user_hrn = 'ple.upmc.jordan_auge'
437
438         #messages.info(self.request, 'You have logged in')
439         page = Page(self.request)
440
441         # Slow...
442         #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
443         #slice_query = Query().get('user').filter_by('user_hrn', '==', user_hrn).select('slice.slice_hrn')
444         #auth_query  = Query().get('network').select('network_hrn')
445         #page.enqueue_query(slice_query)
446         #page.enqueue_query(auth_query)
447
448         #page.expose_queries()
449
450         #slicelist = SimpleList(
451         #    title = None,
452         #    page  = page,
453         #    key   = 'slice.slice_hrn',
454         #    query = slice_query,
455         #)
456
457         #authlist = SimpleList(
458         #    title = None,
459         #    page  = page,
460         #    key   = 'network_hrn',
461         #    query = auth_query,
462         #)
463
464         context = super(MyAccountView, self).get_context_data(**kwargs)
465         context['person']   = self.request.user
466         #context['networks'] = authlist.render(self.request)
467         #context['slices']   = slicelist.render(self.request)
468
469         # XXX This is repeated in all pages
470         # more general variables expected in the template
471         context['title'] = 'User Profile Page'
472         # the menu items on the top
473         context['topmenu_items'] = topmenu_items('my_account', self.request)
474         # so we can sho who is logged
475         context['username'] = the_user(self.request)
476
477         context.update(page.prelude_env())
478
479         return context
480
481
482
483
484
485
486
487 # view for contact form
488 def contact(request):
489     if request.method == 'POST': # If the form has been submitted...
490         form = ContactForm(request.POST) # A form bound to the POST data
491         if form.is_valid(): # All validation rules pass
492             # Process the data in form.cleaned_data
493             first_name = form.cleaned_data['first_name']
494             last_name = form.cleaned_data['last_name']
495             affiliation = form.cleaned_data['affiliation']
496             subject = form.cleaned_data['subject']
497             message = form.cleaned_data['message']
498             email = form.cleaned_data['email'] # email of the sender
499             cc_myself = form.cleaned_data['cc_myself']
500
501             recipients = ['yasin.upmc@gmail.com']
502             if cc_myself:
503                 recipients.append(email)
504
505             from django.core.mail import send_mail
506             send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
507             return render(request,'contact_sent.html') # Redirect after POST
508     else:
509         form = ContactForm() # An unbound form
510
511     return render(request, 'contact.html', {
512         'form': form,
513     })
514
515
516 def slice_request(request):
517     if request.method == 'POST': # If the form has been submitted...
518         form = SliceRequestForm(request.POST) # A form bound to the POST data
519         if form.is_valid(): # All validation rules pass
520             # Process the data in form.cleaned_data
521             slice_name = form.cleaned_data['slice_name']
522             number_of_nodes = form.cleaned_data['number_of_nodes']
523             type_of_nodes = form.cleaned_data['type_of_nodes']
524             purpose = form.cleaned_data['purpose']
525             email = form.cleaned_data['email'] # email of the sender
526             cc_myself = form.cleaned_data['cc_myself']
527
528             recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
529             if cc_myself:
530                 recipients.append(email)
531
532             from django.core.mail import send_mail
533             send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
534             return render(request,'slicereq_recvd.html') # Redirect after POST
535     else:
536         form = SliceRequestForm() # An unbound form
537
538 #    template_env = {}
539 #    template_env['form'] = form
540 #    template_env['topmenu_items'] = topmenu_items('Request a slice', request) 
541 #    template_env['unfold1_main'] = render(request, 'slice_request_.html', {
542 #        'form': form,
543 #    })
544 #    from django.shortcuts                import render_to_response
545 #    from django.template                 import RequestContext
546 #    return render_to_response ('view-unfold1.html',template_env,
547 #                               context_instance=RequestContext(request))
548
549     return render(request, 'slice_request.html', {
550         'form': form,
551         'topmenu_items': topmenu_items('Request a slice', request),
552         'username': the_user (request) 
553     })
554