various cleanups and tweaks
[myslice.git] / portal / registrationview.py
1 import os.path, re
2
3 from django.core.mail            import send_mail
4
5 from django.views.generic       import View
6 from django.template.loader     import render_to_string
7 from django.shortcuts           import render
8
9 from myslice.viewutils          import topmenu_items
10
11 from manifold.manifoldapi       import execute_query
12 from manifold.core.query        import Query
13
14 # This is a rough porting from views.py
15 # the former function-based view is now made a class
16 # we redefine dispatch as it is simple
17 # and coincidentally works since we do not need LoginRequiredAutoLogoutView
18 # a second stab should redefine post and get instead
19 # also this was not thoroughly tested either, might miss some imports
20 # to be continued...
21
22 class RegistrationView (View):
23
24   def dispatch (self, request):
25
26     errors = []
27
28     authorities_query = Query.get('authority').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc']).select('name', 'authority_hrn')
29     #authorities_query = Query.get('authority').select('authority_hrn')
30     authorities = execute_query(request, authorities_query)
31
32     if request.method == 'POST':
33         # We shall use a form here
34
35         #get_email = PendingUser.objects.get(email)
36         reg_fname = request.POST.get('firstname', '')
37         reg_lname = request.POST.get('lastname', '')
38         #reg_aff = request.POST.get('affiliation','')
39         reg_auth = request.POST.get('authority_hrn', '')
40         reg_email = request.POST.get('email','').lower()
41         
42         #POST value validation  
43         if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
44             errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
45             #return HttpResponse("Only Letters, Numbers, - and _ allowd in First Name")
46             #return render(request, 'registration_view.html')
47         if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
48             errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
49             #return HttpResponse("Only Letters, Numbers, - and _ is allowed in Last name")
50             #return render(request, 'registration_view.html')
51 #        if (re.search(r'^[\w+\s.@+-]+$', reg_aff) == None):
52 #            errors.append('Affiliation may contain only letters, numbers, spaces and @/./+/-/_ characters.')
53             #return HttpResponse("Only Letters, Numbers and _ is allowed in Affiliation")
54             #return render(request, 'registration_view.html')
55         # XXX validate authority hrn !!
56         if PendingUser.objects.filter(email__iexact=reg_email):
57             errors.append('Email already registered.Please provide a new email address.')
58             #return HttpResponse("Email Already exists")
59             #return render(request, 'registration_view.html')
60         if 'generate' in request.POST['question']:
61             # Generate public and private keys using SFA Library
62             from sfa.trust.certificate  import Keypair
63             k = Keypair(create=True)
64             public_key = k.get_pubkey_string()
65             private_key = k.as_pem()
66             private_key = ''.join(private_key.split())
67             public_key = "ssh-rsa " + public_key
68             # Saving to DB
69             keypair = '{"user_public_key":"'+ public_key + '", "user_private_key":"'+ private_key + '"}'
70 #            keypair = re.sub("\r", "", keypair)
71 #            keypair = re.sub("\n", "\\n", keypair)
72 #            #keypair = keypair.rstrip('\r\n')
73 #            keypair = ''.join(keypair.split())
74         else:
75             up_file = request.FILES['user_public_key']
76             file_content =  up_file.read()
77             file_name = up_file.name
78             file_extension = os.path.splitext(file_name)[1]
79             allowed_extension =  ['.pub','.txt']
80             if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
81                 keypair = '{"user_public_key":"'+ file_content +'"}'
82                 keypair = re.sub("\r", "", keypair)
83                 keypair = re.sub("\n", "\\n",keypair)
84                 keypair = ''.join(keypair.split())
85             else:
86                 errors.append('Please upload a valid RSA public key [.txt or .pub].')
87
88         #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
89         #                email=reg_email, password=request.POST['password'], keypair=keypair)
90         #b.save()
91         if not errors:
92             b = PendingUser(
93                 first_name=reg_fname, 
94                 last_name=reg_lname, 
95                 #affiliation=reg_aff,
96                 authority_hrn=reg_auth,
97                 email=reg_email, 
98                 password=request.POST['password'],
99                 keypair=keypair
100             )
101             b.save()
102
103             # Send email
104             ctx = {
105                 first_name   : reg_fname, 
106                 last_name    : reg_lname, 
107                 #affiliation  : reg_aff,
108                 authority_hrn: reg_auth,
109                 email        : reg_email, 
110                 keypair      : keypair,
111                 cc_myself    : True # form.cleaned_data['cc_myself']
112             }
113
114             recipients = authority_get_pi_emails(authority_hrn)
115             if ctx['cc_myself']:
116                 recipients.append(ctx['email'])
117
118             msg = render_to_string('user_request_email.txt', ctx)
119             send_mail("Onelab New User request for %s submitted"%email, msg, email, recipients)
120
121             return render(request, 'user_register_complete.html')
122
123     return render(request, 'registration_view.html',{
124         'topmenu_items': topmenu_items('Register', request),
125         'errors': errors,
126         'firstname': request.POST.get('firstname', ''),
127         'lastname': request.POST.get('lastname', ''),
128         #'affiliation': request.POST.get('affiliation', ''),
129         'authority_hrn': request.POST.get('authority_hrn', ''),
130         'email': request.POST.get('email', ''),
131         'password': request.POST.get('password', ''),           
132         'authorities': authorities
133     })