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