1 # -*- coding: utf-8 -*-
3 # portal/views.py: views for the portal application
4 # This file is part of the Manifold project.
7 # Jordan Augé <jordan.auge@lip6.fr>
8 # Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne Universités / LIP6
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.
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
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.
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, HttpResponse
40 class DashboardView(TemplateView):
41 template_name = "dashboard.html"
43 def get_context_data(self, **kwargs):
44 user_hrn = 'ple.upmc.jordan_auge'
46 #messages.info(self.request, 'You have logged in')
47 page = Page(self.request)
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)
58 slicelist = SimpleList(
61 key = 'slice.slice_hrn',
65 authlist = SimpleList(
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)
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)
85 context.update(page.prelude_env())
89 class UserRegisterView(RegistrationView):
91 A registration backend which follows a simple workflow:
93 1. User signs up, inactive account is created.
95 2. Email is sent to user with activation link.
97 3. User clicks activation link, account is now active.
99 Using this backend requires that
101 * ``registration`` be listed in the ``INSTALLED_APPS`` setting
102 (since this backend makes use of models defined in this
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).
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.
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
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.
128 form_class = UserRegisterForm
130 def register(self, request, **cleaned_data):
132 Given a username, email address and password, register a new
133 user account, which will initially be inactive.
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.
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
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.
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']
160 #password2 = cleaned_data['password2']
161 keypair = cleaned_data['keypair']
163 #if Site._meta.installed:
164 # site = Site.objects.get_current()
166 # site = RequestSite(request)
169 new_user = PendingUser.objects.create_inactive_user(first_name, last_name, email, password, site)
170 signals.user_registered.send(sender=self.__class__,
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)
181 def registration_allowed(self, request):
183 Indicate whether account registration is currently permitted,
184 based on the value of the setting ``REGISTRATION_OPEN``. This
185 is determined as follows:
187 * If ``REGISTRATION_OPEN`` is not specified in settings, or is
188 set to ``True``, registration is permitted.
190 * If ``REGISTRATION_OPEN`` is both specified and set to
191 ``False``, registration is not permitted.
194 return getattr(settings, 'REGISTRATION_OPEN', True)
196 def get_success_url(self, request, user):
198 Return the name of the URL to redirect to after successful
202 return ('user_register_complete', (), {})
205 class UserValidateView(ActivationView):
206 def activate(self, request, activation_key):
208 Given an an activation key, look up and activate the user
209 account corresponding to that key (if possible).
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.
217 activated_user = RegistrationProfile.objects.activate_user(activation_key)
219 signals.user_activated.send(sender=self.__class__,
222 return activated_user
224 def get_success_url(self, request, user):
225 return ('registration_activation_complete', (), {})
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
233 # DEPRECATED #from myslice.viewutils import the_user
235 # DEPRECATED #from django.template.loader import render_to_string
236 # DEPRECATED #from django.template import RequestContext
237 # DEPRECATED #from django.views import generic
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
243 # DEPRECATED ##class MerlinWizard(NamedUrlSessionWizardView):
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,
256 # DEPRECATED ## 'url_name': 'merlin_wizard'
258 # DEPRECATED ## return super(MerlinWizard, cls).as_view(*args, **kwargs)
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"
270 # DEPRECATED # def done(self, form_list, **kwargs):
271 # DEPRECATED # step1_form = form_list[0]
272 # DEPRECATED # step2_form = form_list[1]
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)
278 # DEPRECATED # if all([productext, shippings, images]):
279 # DEPRECATED # del self.request.session["wizard_product_wizard_view"]
281 # DEPRECATED # messages.success(self.request,
282 # DEPRECATED # _("Your product has been created."))
283 # DEPRECATED # return HttpResponseRedirect(self.get_success_url(productext))
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"))
289 # DEPRECATED # #def get_form_kwargs(self, step):
290 # DEPRECATED # # if step == "product":
291 # DEPRECATED # # return {"user": self.request.user}
292 # DEPRECATED # # return {}
294 # DEPRECATED ## The portal should hook the slice and user creation pages
296 # DEPRECATED #def register_user(request):
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
315 # DEPRECATED # form = UserRegisterForm()
316 # DEPRECATED # return render(request, 'register_user.html', locals())
318 # DEPRECATED #def index(request):
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'
328 # DEPRECATED # STEP0 = render_to_string('account_validated.html', context_instance=RequestContext(request))
329 # DEPRECATED # STEP2_HTML = """
330 # DEPRECATED # coucou
332 # DEPRECATED # STEP4 = """
335 # DEPRECATED # STEP5 = render_to_string('account_validated.html', context_instance=RequestContext(request))
337 # DEPRECATED # p = PortalPage(request)
339 # DEPRECATED # # This is redundant with the Wizard title
340 # DEPRECATED # p << "<h3>User registration</h3>"
342 # DEPRECATED # sons = []
343 # DEPRECATED # start_step = 1
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
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',
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',
373 # DEPRECATED # 'name' : 'Email',
374 # DEPRECATED # 'field' : 'email',
375 # DEPRECATED # 'type' : 'text',
376 # DEPRECATED # 'description' : 'Enter your email address',
378 # DEPRECATED # 'name' : 'Password',
379 # DEPRECATED # 'field' : 'password',
380 # DEPRECATED # 'type' : 'password',
381 # DEPRECATED # 'description' : 'Enter your password',
383 # DEPRECATED # 'name' : 'Confirm password',
384 # DEPRECATED # 'field' : 'password2',
385 # DEPRECATED # 'type' : 'password',
386 # DEPRECATED # 'description' : 'Enter your password again',
388 # DEPRECATED # sons.append(CreateForm(page = p, title = STEP1_TITLE, togglable = False, object = 'local:user', fields = field_list))
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
399 # DEPRECATED # sons.append(CreateForm(page = p, title = STEP2_TITLE, togglable = False, object = 'slice')) #institution'))
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))
406 # DEPRECATED # # Step 4: Request a slice (optional)
407 # DEPRECATED # sons.append(CreateForm(page = p, title = STEP4_TITLE, togglable = False, object = 'slice'))
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))
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))
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,
428 # DEPRECATED # p << wizard.render(request) # in portal page if possible
430 # DEPRECATED # return p.render()
433 # DEPRECATED ## view for my_account
434 # DEPRECATED # class MyAccountView(TemplateView):
435 # DEPRECATED # template_name = "my_account.html"
437 # DEPRECATED # def from_process(self, request, **cleaned_data):
438 # DEPRECATED # #if request.method == 'POST':
439 # DEPRECATED # # if request.POST['submit_name']:
440 # DEPRECATED # if 'fname' in request.POST:
441 # DEPRECATED # messsag= "Got Name"
442 # DEPRECATED # #return render(request, 'portal/my_account.html')
443 # DEPRECATED # #response = HttpResponse("Here's the text of the Web page.")
444 # DEPRECATED # return HttpResponse(message)
446 # DEPRECATED # def get_context_data(self, **kwargs):
447 # DEPRECATED # page = Page(self.request)
448 # DEPRECATED # context = super(MyAccountView, self).get_context_data(**kwargs)
449 # DEPRECATED # context['person'] = self.request.user
450 # DEPRECATED # # XXX This is repeated in all pages
451 # DEPRECATED # # more general variables expected in the template
452 # DEPRECATED # context['title'] = 'User Profile Page'
453 # DEPRECATED # # the menu items on the top
454 # DEPRECATED # context['topmenu_items'] = topmenu_items('my_account', self.request)
455 # DEPRECATED # # so we can sho who is logged
456 # DEPRECATED # context['username'] = the_user(self.request)
457 # DEPRECATED # context.update(page.prelude_env())
458 # DEPRECATED # return context
462 # View for my_account form
463 def my_account(request):
464 return render(request, 'my_account.html')
466 #my_acc form value processing
467 def acc_process(request):
468 if 'submit_name' in request.POST:
469 edited_first_name = request.POST['fname']
470 edited_last_name = request.POST['lname']
471 #email = 'test_email@gmail.com'
472 #password = 'test_pp'
473 #message = 'F_Name: %s L_name: %s dummy_pp: %s' % (first_name, last_name, password)
476 # insert into DB [needed for registration page]
477 #approach borrowed from register view
478 #new_user = PendingUser.objects.create_inactive_user(edited_first_name, edited_last_name, email, password, site)
479 #conventional approach
480 #b = PendingUser(first_name=edited_first_name, edited_last_name=last_name)
483 # select and update [will be used throughout this view]
484 # select the logged in user [for the moment hard coded]
485 get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
486 # update first and last name
487 get_user.first_name = edited_first_name
488 get_user.last_name = edited_last_name
491 return HttpResponse('Success: Name Updated!!')
492 elif 'submit_pass' in request.POST:
493 edited_password = request.POST['password']
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
497 get_user.password = edited_password
499 return HttpResponse('Success: Password Changed!!')
500 elif 'generate' in request.POST:
502 message = 'Here will generate ssh-rsa keys :D %d' %a
503 return HttpResponse(message)
505 message = 'You submitted an empty form.'
506 return HttpResponse(message)
510 # view for contact form
511 def contact(request):
512 if request.method == 'POST': # If the form has been submitted...
513 form = ContactForm(request.POST) # A form bound to the POST data
514 if form.is_valid(): # All validation rules pass
515 # Process the data in form.cleaned_data
516 first_name = form.cleaned_data['first_name']
517 last_name = form.cleaned_data['last_name']
518 affiliation = form.cleaned_data['affiliation']
519 subject = form.cleaned_data['subject']
520 message = form.cleaned_data['message']
521 email = form.cleaned_data['email'] # email of the sender
522 cc_myself = form.cleaned_data['cc_myself']
524 recipients = ['yasin.upmc@gmail.com']
526 recipients.append(email)
528 from django.core.mail import send_mail
529 send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
530 return render(request,'contact_sent.html') # Redirect after POST
532 form = ContactForm() # An unbound form
534 return render(request, 'contact.html', {
539 def slice_request(request):
540 if request.method == 'POST': # If the form has been submitted...
541 form = SliceRequestForm(request.POST) # A form bound to the POST data
542 if form.is_valid(): # All validation rules pass
543 # Process the data in form.cleaned_data
544 slice_name = form.cleaned_data['slice_name']
545 number_of_nodes = form.cleaned_data['number_of_nodes']
546 type_of_nodes = form.cleaned_data['type_of_nodes']
547 purpose = form.cleaned_data['purpose']
548 email = form.cleaned_data['email'] # email of the sender
549 cc_myself = form.cleaned_data['cc_myself']
551 recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
553 recipients.append(email)
555 from django.core.mail import send_mail
556 send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
557 return render(request,'slicereq_recvd.html') # Redirect after POST
559 form = SliceRequestForm() # An unbound form
562 # template_env['form'] = form
563 # template_env['topmenu_items'] = topmenu_items('Request a slice', request)
564 # template_env['unfold1_main'] = render(request, 'slice_request_.html', {
567 # from django.shortcuts import render_to_response
568 # from django.template import RequestContext
569 # return render_to_response ('view-unfold1.html',template_env,
570 # context_instance=RequestContext(request))
572 return render(request, 'slice_request.html', {
574 'topmenu_items': topmenu_items('Request a slice', request),
575 'username': the_user (request)