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('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 registration_allowed(self, request):
176         """
177         Indicate whether account registration is currently permitted,
178         based on the value of the setting ``REGISTRATION_OPEN``. This
179         is determined as follows:
180
181         * If ``REGISTRATION_OPEN`` is not specified in settings, or is
182           set to ``True``, registration is permitted.
183
184         * If ``REGISTRATION_OPEN`` is both specified and set to
185           ``False``, registration is not permitted.
186         
187         """
188         return getattr(settings, 'REGISTRATION_OPEN', True)
189
190     def get_success_url(self, request, user):
191         """
192         Return the name of the URL to redirect to after successful
193         user registration.
194         
195         """
196         return ('user_register_complete', (), {})
197
198
199 class UserValidateView(ActivationView):
200     def activate(self, request, activation_key):
201         """
202         Given an an activation key, look up and activate the user
203         account corresponding to that key (if possible).
204
205         After successful activation, the signal
206         ``registration.signals.user_activated`` will be sent, with the
207         newly activated ``User`` as the keyword argument ``user`` and
208         the class of this backend as the sender.
209         
210         """
211         activated_user = RegistrationProfile.objects.activate_user(activation_key)
212         if activated_user:
213             signals.user_activated.send(sender=self.__class__,
214                                         user=activated_user,
215                                         request=request)
216         return activated_user
217
218     def get_success_url(self, request, user):
219         return ('registration_activation_complete', (), {})
220
221
222 # DEPRECATED #from portal.portalpage  import PortalPage
223 # DEPRECATED #from plugins.wizard     import Wizard
224 # DEPRECATED #from plugins.form       import CreateForm
225 # DEPRECATED #from plugins.raw.raw    import Raw          # XXX
226 # DEPRECATED #
227 # DEPRECATED #from myslice.viewutils  import the_user
228 # DEPRECATED #
229 # DEPRECATED #from django.template.loader import render_to_string
230 # DEPRECATED #from django.template import RequestContext
231 # DEPRECATED #from django.views import generic
232 # DEPRECATED #
233 # DEPRECATED #from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
234 # DEPRECATED ##from django.core.files.storage import FileSystemStorage
235 # DEPRECATED #from django.core.files.storage import default_storage
236 # DEPRECATED #
237 # DEPRECATED ##class MerlinWizard(NamedUrlSessionWizardView):
238 # DEPRECATED ##
239 # DEPRECATED ##    ...
240 # DEPRECATED ##    ...
241 # DEPRECATED ##
242 # DEPRECATED ##    @classonlymethod
243 # DEPRECATED ##    def as_view(cls, *args, **kwargs):
244 # DEPRECATED ##        kwargs.update({
245 # DEPRECATED ##            'form_list': [
246 # DEPRECATED ##                NameForm,
247 # DEPRECATED ##                QuestForm,
248 # DEPRECATED ##                ColorForm,
249 # DEPRECATED ##            ],
250 # DEPRECATED ##            'url_name': 'merlin_wizard'
251 # DEPRECATED ##        })
252 # DEPRECATED ##        return super(MerlinWizard, cls).as_view(*args, **kwargs)
253 # DEPRECATED #
254 # DEPRECATED #class UserRegisterWizardView(NamedUrlSessionWizardView):
255 # DEPRECATED ##class UserRegisterWizardView(LoginRequiredMixin, NamedUrlSessionWizardView):
256 # DEPRECATED #    # Notice that I specify a file storage instance. If you don't specify this,
257 # DEPRECATED #    # and you need to support FileField or ImageField in your forms, you'll get
258 # DEPRECATED #    # errors from Django. This is something else I think could be handled by
259 # DEPRECATED #    # the views better. Seems to me that it should just use whatever the
260 # DEPRECATED #    # default/specified storage is for the rest of your project/application.
261 # DEPRECATED #    file_storage = default_storage # FileSystemStorage()
262 # DEPRECATED #    template_name = "register_user_wizard.html"
263 # DEPRECATED #
264 # DEPRECATED #    def done(self, form_list, **kwargs):
265 # DEPRECATED #        step1_form = form_list[0]
266 # DEPRECATED #        step2_form = form_list[1]
267 # DEPRECATED #
268 # DEPRECATED #        productext = self.create_product(product_form)
269 # DEPRECATED #        shippings = self.create_shippings(productext, shipping_forms)
270 # DEPRECATED #        images = self.create_images(productext, image_forms)
271 # DEPRECATED #
272 # DEPRECATED #        if all([productext, shippings, images]):
273 # DEPRECATED #            del self.request.session["wizard_product_wizard_view"]
274 # DEPRECATED #
275 # DEPRECATED #            messages.success(self.request,
276 # DEPRECATED #                _("Your product has been created."))
277 # DEPRECATED #            return HttpResponseRedirect(self.get_success_url(productext))
278 # DEPRECATED #
279 # DEPRECATED #        messages.error(self.request, _("Something went wrong creating your "
280 # DEPRECATED #            "product. Please try again or contact support."))
281 # DEPRECATED #        return HttpResponseRedirect(reverse("register_wizard"))
282 # DEPRECATED #
283 # DEPRECATED #    #def get_form_kwargs(self, step):
284 # DEPRECATED #    #    if step == "product":
285 # DEPRECATED #    #        return {"user": self.request.user}
286 # DEPRECATED #    #    return {}
287 # DEPRECATED #
288 # DEPRECATED ## The portal should hook the slice and user creation pages
289 # DEPRECATED #
290 # DEPRECATED #def register_user(request):
291 # DEPRECATED #    
292 # DEPRECATED #    if request.method == 'POST':
293 # DEPRECATED #        form = UserRegisterForm(request.POST) # Nous reprenons les données
294 # DEPRECATED #        if form.is_valid():
295 # DEPRECATED #            first_name = form.cleaned_data['first_name']
296 # DEPRECATED #            last_name  = form.cleaned_data['last_name']
297 # DEPRECATED #            email      = form.cleaned_data['email']
298 # DEPRECATED #            password   = form.cleaned_data['password']
299 # DEPRECATED #            password2  = form.cleaned_data['password2']
300 # DEPRECATED #            keypair    = form.cleaned_data['keypair']
301 # DEPRECATED #            ## Ici nous pouvons traiter les données du formulaire
302 # DEPRECATED #            #sujet = form.cleaned_data['sujet']
303 # DEPRECATED #            #message = form.cleaned_data['message']
304 # DEPRECATED #            #envoyeur = form.cleaned_data['envoyeur']
305 # DEPRECATED #            #renvoi = form.cleaned_data['renvoi']
306 # DEPRECATED #            ## Nous pourrions ici envoyer l'e-mail grâce aux données que nous venons de récupérer
307 # DEPRECATED #            #envoi = True
308 # DEPRECATED #    else:
309 # DEPRECATED #        form = UserRegisterForm()
310 # DEPRECATED #    return render(request, 'register_user.html', locals())
311 # DEPRECATED #
312 # DEPRECATED #def index(request):
313 # DEPRECATED #
314 # DEPRECATED #    WIZARD_TITLE = 'User registration'
315 # DEPRECATED #    STEP1_TITLE  = 'Enter your details'
316 # DEPRECATED #    STEP2_TITLE  = 'Select your institution'
317 # DEPRECATED #    STEP3_TITLE  = 'Authentication'
318 # DEPRECATED #    STEP4_TITLE  = 'Request a slice (optional)'
319 # DEPRECATED #    STEP5_TITLE  = 'Waiting for validation'
320 # DEPRECATED #    STEP6_TITLE  = 'Account validated'
321 # DEPRECATED #
322 # DEPRECATED #    STEP0 = render_to_string('account_validated.html', context_instance=RequestContext(request))
323 # DEPRECATED #    STEP2_HTML   = """
324 # DEPRECATED #    coucou
325 # DEPRECATED #    """
326 # DEPRECATED #    STEP4 = """
327 # DEPRECATED #    mede
328 # DEPRECATED #    """
329 # DEPRECATED #    STEP5 = render_to_string('account_validated.html', context_instance=RequestContext(request))
330 # DEPRECATED #
331 # DEPRECATED #    p = PortalPage(request)
332 # DEPRECATED #
333 # DEPRECATED #    # This is redundant with the Wizard title
334 # DEPRECATED #    p << "<h3>User registration</h3>"
335 # DEPRECATED #
336 # DEPRECATED #    sons = []
337 # DEPRECATED #    start_step = 1
338 # DEPRECATED #
339 # DEPRECATED #    # STEP 1
340 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of his account details
341 # DEPRECATED #    # Otherwise propose a form to fill in
342 # DEPRECATED #    if the_user(request):
343 # DEPRECATED #        # Fill a disabled form with user info
344 # DEPRECATED #        # Please logout to register another user
345 # DEPRECATED #        sons.append(Raw(page=p, title=STEP1_TITLE, togglable=False, html=STEP0))
346 # DEPRECATED #        start_step += 1
347 # DEPRECATED #    else:
348 # DEPRECATED #        # We could pass a list of fields also, instead of retrieving them from metadata
349 # DEPRECATED #        # Otherwise we need some heuristics to display nice forms
350 # DEPRECATED #        # XXX Could we log the user in after the form is validated ?
351 # DEPRECATED #        # XXX Explain the password is for XXX
352 # DEPRECATED #        field_list = [{
353 # DEPRECATED #            'name'        : 'First name',
354 # DEPRECATED #            'field'       : 'firstname',
355 # DEPRECATED #            'type'        : 'text',
356 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
357 # DEPRECATED #            'validate_err': 'Your first name must be comprised of letters only',
358 # DEPRECATED #            'description' : 'Enter your first name',
359 # DEPRECATED #        }, {
360 # DEPRECATED #            'name'        : 'Last name',
361 # DEPRECATED #            'field'       : 'lastname',
362 # DEPRECATED #            'type'        : 'text',
363 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
364 # DEPRECATED #            'validate_err': 'Your last name must be comprised of letters only',
365 # DEPRECATED #            'description' : 'Enter your last name',
366 # DEPRECATED #        }, { 
367 # DEPRECATED #            'name'        : 'Email',
368 # DEPRECATED #            'field'       : 'email',
369 # DEPRECATED #            'type'        : 'text',
370 # DEPRECATED #            'description' : 'Enter your email address',
371 # DEPRECATED #        }, {
372 # DEPRECATED #            'name'        : 'Password',
373 # DEPRECATED #            'field'       : 'password',
374 # DEPRECATED #            'type'        : 'password',
375 # DEPRECATED #            'description' : 'Enter your password',
376 # DEPRECATED #        }, {
377 # DEPRECATED #            'name'        : 'Confirm password',
378 # DEPRECATED #            'field'       : 'password2',
379 # DEPRECATED #            'type'        : 'password',
380 # DEPRECATED #            'description' : 'Enter your password again',
381 # DEPRECATED #        }]
382 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP1_TITLE, togglable = False, object = 'local:user', fields = field_list))
383 # DEPRECATED #
384 # DEPRECATED #    # STEP 2
385 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of its institution
386 # DEPRECATED #    # Otherwise propose a form to fill in (we should base our selection on the email)
387 # DEPRECATED #    if the_user(request):
388 # DEPRECATED #        # Fill a disabled form with institution
389 # DEPRECATED #        # Please logout to register another user
390 # DEPRECATED #        sons.append(Raw(page=p, title=STEP2_TITLE, togglable=False, html="User created"))
391 # DEPRECATED #        start_step += 1
392 # DEPRECATED #    else:
393 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP2_TITLE, togglable = False, object = 'slice')) #institution'))
394 # DEPRECATED #
395 # DEPRECATED #    # STEP3
396 # DEPRECATED #    # Please should your prefered authentication method
397 # DEPRECATED #    # This step should allow the user to either choose the user or managed mode in MySlice
398 # DEPRECATED #    sons.append(Raw(page = p, title = STEP3_TITLE, togglable = False, html = STEP2_HTML))
399 # DEPRECATED #
400 # DEPRECATED #    # Step 4: Request a slice (optional)
401 # DEPRECATED #    sons.append(CreateForm(page = p, title = STEP4_TITLE, togglable = False, object = 'slice'))
402 # DEPRECATED #
403 # DEPRECATED #    # Step 5: Your request is waiting for validation
404 # DEPRECATED #    # Periodic refresh
405 # DEPRECATED #    sons.append(Raw(page = p, title = STEP5_TITLE, togglable = False, html = STEP4))
406 # DEPRECATED #
407 # DEPRECATED #    # Step 6: Account validation  = welcome for newly validated users
408 # DEPRECATED #    # . delegation
409 # DEPRECATED #    # . platforms
410 # DEPRECATED #    # . slice
411 # DEPRECATED #    # . pointers
412 # DEPRECATED #    sons.append(Raw(page = p, title = STEP6_TITLE, togglable = False, html = STEP5))
413 # DEPRECATED #
414 # DEPRECATED #    wizard = Wizard(
415 # DEPRECATED #        page       = p,
416 # DEPRECATED #        title      = WIZARD_TITLE,
417 # DEPRECATED #        togglable  = False,
418 # DEPRECATED #        sons       = sons,
419 # DEPRECATED #        start_step = start_step,
420 # DEPRECATED #    )
421 # DEPRECATED #
422 # DEPRECATED #    p << wizard.render(request) # in portal page if possible
423 # DEPRECATED #
424 # DEPRECATED #    return p.render()
425
426
427 # view for contact form
428 def contact(request):
429     if request.method == 'POST': # If the form has been submitted...
430         form = ContactForm(request.POST) # A form bound to the POST data
431         if form.is_valid(): # All validation rules pass
432             # Process the data in form.cleaned_data
433             first_name = form.cleaned_data['first_name']
434             last_name = form.cleaned_data['last_name']
435             affiliation = form.cleaned_data['affiliation']
436             subject = form.cleaned_data['subject']
437             message = form.cleaned_data['message']
438             email = form.cleaned_data['email']
439             cc_myself = form.cleaned_data['cc_myself']
440
441             recipients = ['yasin.upmc@gmail.com']
442             if cc_myself:
443                 recipients.append(sender)
444
445             from django.core.mail import send_mail
446             send_mail(subject, message, email, recipients)
447             return render(request,'contact_sent.html') # Redirect after POST
448     else:
449         form = ContactForm() # An unbound form
450
451     return render(request, 'contact.html', {
452         'form': form,
453     })
454