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