Fixed: Registration & My Account, Generate new keys with a valid RSA format - http...
[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 unfold.page                import Page
10 from ui.topmenu                 import topmenu_items
11
12 from manifold.manifoldapi       import execute_query
13 from manifold.core.query        import Query
14
15 from portal.models              import PendingUser
16 from portal.actions             import authority_get_pi_emails 
17
18 # This is a rough porting from views.py
19 # the former function-based view is now made a class
20 # we redefine dispatch as it is simple
21 # and coincidentally works since we do not need LoginRequiredAutoLogoutView
22 # a second stab should redefine post and get instead
23 # also this was not thoroughly tested either, might miss some imports
24 # to be continued...
25
26 class RegistrationView (View):
27
28     def dispatch (self, request):
29
30         errors = []
31
32         authorities_query = Query.get('authority').\
33             filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc']).\
34             select('name', 'authority_hrn')
35         #authorities_query = Query.get('authority').select('authority_hrn')
36         authorities = execute_query(request, authorities_query)
37         # xxx tocheck - if authorities is empty, it's no use anyway
38         # (users won't be able to validate the form anyway)
39
40         page = Page(request)
41         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
42         page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
43
44         print 'registration view, method',request.method
45
46         if request.method == 'POST':
47             # We shall use a form here
48
49             #get_email = PendingUser.objects.get(email)
50             reg_fname = request.POST.get('firstname', '')
51             reg_lname = request.POST.get('lastname', '')
52             #reg_aff = request.POST.get('affiliation','')
53             reg_auth = request.POST.get('authority_hrn', '')
54             reg_email = request.POST.get('email','').lower()
55       
56             #POST value validation  
57             if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
58                 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
59             if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
60                 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
61             # XXX validate authority hrn !!
62             if PendingUser.objects.filter(email__iexact=reg_email):
63                 errors.append('Email already registered.Please provide a new email address.')
64
65 # XXX TODO: Factorize with portal/accountview.py
66             if 'generate' in request.POST['question']:
67                 from Crypto.PublicKey import RSA
68                 private = RSA.generate(1024)
69                 private_key = json.dumps(private.exportKey())
70                 public  = private.publickey()
71                 public_key = json.dumps(public.exportKey(format='OpenSSH'))
72
73 #                # Generate public and private keys using SFA Library
74 #                from sfa.trust.certificate  import Keypair
75 #                k = Keypair(create=True)
76 #                public_key = k.get_pubkey_string()
77 #                private_key = k.as_pem()
78 #                private_key = ''.join(private_key.split())
79 #                public_key = "ssh-rsa " + public_key
80                 # Saving to DB
81                 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + '}'
82                 #keypair = re.sub("\r", "", keypair)
83                 #keypair = re.sub("\n", "\\n", keypair)
84                 #keypair = keypair.rstrip('\r\n')
85                 #keypair = ''.join(keypair.split())
86             else: 
87                 up_file = request.FILES['user_public_key']
88                 file_content =  up_file.read()
89                 file_name = up_file.name
90                 file_extension = os.path.splitext(file_name)[1]
91                 allowed_extension =  ['.pub','.txt']
92                 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
93                     keypair = '{"user_public_key":"'+ file_content +'"}'
94                     keypair = re.sub("\r", "", keypair)
95                     keypair = re.sub("\n", "\\n",keypair)
96                     keypair = ''.join(keypair.split())
97                     # for sending email
98                     public_key = file_content
99                 else:
100                     errors.append('Please upload a valid RSA public key [.txt or .pub].')
101
102             #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
103             #                email=reg_email, password=request.POST['password'], keypair=keypair)
104             #b.save()
105             if not errors:
106                 b = PendingUser(
107                     first_name=reg_fname, 
108                     last_name=reg_lname, 
109                     #affiliation=reg_aff,
110                     authority_hrn=reg_auth,
111                     email=reg_email, 
112                     password=request.POST['password'],
113                     keypair=keypair
114                     )
115                 b.save()
116
117                 # Send email
118                 ctx = {
119                     'first_name'    : reg_fname, 
120                     'last_name'     : reg_lname, 
121                     'authority_hrn' : reg_auth,
122                     'email'         : reg_email, 
123                     'keypair'       : 'Public Key :' + public_key,
124                     'cc_myself'     : True # form.cleaned_data['cc_myself']
125                     }
126                 #not working
127                 #recipients = authority_get_pi_emails(request,reg_auth)
128                 recipients = ['devel@myslice.info']
129                 if ctx['cc_myself']:
130                     recipients.append(ctx['email'])
131
132                 msg = render_to_string('user_request_email.txt', ctx)
133                 print "tesing msg"
134                 print msg
135                 send_mail("Onelab New User request for %s submitted"%reg_email, msg, reg_email, recipients)
136
137                 return render(request, 'user_register_complete.html')
138
139         template_env = {
140           'topmenu_items': topmenu_items('Register', request),
141           'errors': errors,
142           'firstname': request.POST.get('firstname', ''),
143           'lastname': request.POST.get('lastname', ''),
144           #'affiliation': request.POST.get('affiliation', ''),
145           'authority_hrn': request.POST.get('authority_hrn', ''),
146           'email': request.POST.get('email', ''),
147           'password': request.POST.get('password', ''),           
148           'authorities': authorities,
149           }
150         template_env.update(page.prelude_env ())
151         return render(request, 'registration_view.html',template_env)