Registration: user_hrn generated based on authority+email
[myslice.git] / portal / registrationview.py
1 import os.path, re
2 import json
3
4 from django.core.mail           import send_mail
5
6 from django.views.generic       import View
7 from django.template.loader     import render_to_string
8 from django.shortcuts           import render
9
10 from unfold.page                import Page
11 from unfold.loginrequired       import FreeAccessView
12 from ui.topmenu                 import topmenu_items
13
14 from manifold.manifoldapi       import execute_admin_query
15 from manifold.core.query        import Query
16
17 from portal.models              import PendingUser
18 from portal.actions             import authority_get_pi_emails 
19
20 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
21 # so let's override 'get' and 'post' instead
22 #
23 class RegistrationView (FreeAccessView):
24
25     def post (self, request):
26         return self.get_or_post (request, 'POST')
27
28     def get (self, request):
29         return self.get_or_post (request, 'GET')
30
31     def get_or_post  (self, request, method):
32         errors = []
33
34         #authorities_query = Query.get('authority').\
35         #    select('name', 'authority_hrn')
36         
37         #onelab_enabled_query = Query.get('local:platform').filter_by('platform', '==', 'ple').filter_by('disabled', '==', 'False')
38         #onelab_enabled = not not execute_admin_query(request, onelab_enabled_query)
39         #if onelab_enabled:
40         if True:
41             print "ONELAB ENABLED"
42             authorities_query = Query.get('ple:authority').select('name', 'authority_hrn').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc', 'ple.ibbtple', 'ple.nitos'])
43         else:
44             print "FIREXP ENABLED"
45
46         authorities = execute_admin_query(request, authorities_query)
47         # xxx tocheck - if authorities is empty, it's no use anyway
48         # (users won't be able to validate the form anyway)
49
50         page = Page(request)
51         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
52         page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
53
54         print 'registration view, method',method
55
56         if method == 'POST':
57             # We shall use a form here
58
59             #get_email = PendingUser.objects.get(email)
60             reg_fname  = request.POST.get('firstname', '')
61             reg_lname  = request.POST.get('lastname', '')
62             #reg_aff   = request.POST.get('affiliation','')
63             reg_auth   = request.POST.get('authority_hrn', '')
64             reg_login  = request.POST.get('login', '')
65             reg_email  = request.POST.get('email','').lower()
66             #prepare user_hrn 
67             split_email = reg_email.split("@")[0] 
68             split_email = split_email.replace(".", "_")
69             user_hrn = reg_auth + '.' + split_email
70
71             #POST value validation  
72             if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
73                 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
74             if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
75                 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
76             # XXX validate authority hrn !!
77             if PendingUser.objects.filter(email__iexact=reg_email):
78                 errors.append('Email already registered.Please provide a new email address.')
79
80 # XXX TODO: Factorize with portal/accountview.py
81             if 'generate' in request.POST['question']:
82                 from Crypto.PublicKey import RSA
83                 private = RSA.generate(1024)
84                 private_key = json.dumps(private.exportKey())
85                 public  = private.publickey()
86                 public_key = json.dumps(public.exportKey(format='OpenSSH'))
87
88 #                # Generate public and private keys using SFA Library
89 #                from sfa.trust.certificate  import Keypair
90 #                k = Keypair(create=True)
91 #                public_key = k.get_pubkey_string()
92 #                private_key = k.as_pem()
93 #                private_key = ''.join(private_key.split())
94 #                public_key = "ssh-rsa " + public_key
95                 # Saving to DB
96                 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":'+ user_hrn + '}'
97                 #keypair = re.sub("\r", "", keypair)
98                 #keypair = re.sub("\n", "\\n", keypair)
99                 #keypair = keypair.rstrip('\r\n')
100                 #keypair = ''.join(keypair.split())
101             else: 
102                 up_file = request.FILES['user_public_key']
103                 file_content =  up_file.read()
104                 file_name = up_file.name
105                 file_extension = os.path.splitext(file_name)[1]
106                 allowed_extension =  ['.pub','.txt']
107                 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
108                     keypair = '{"user_public_key":"'+ file_content +'"}'
109                     keypair = re.sub("\r", "", keypair)
110                     keypair = re.sub("\n", "\\n",keypair)
111                     keypair = ''.join(keypair.split())
112                     # for sending email
113                     public_key = file_content
114                 else:
115                     errors.append('Please upload a valid RSA public key [.txt or .pub].')
116
117             #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
118             #                email=reg_email, password=request.POST['password'], keypair=keypair)
119             #b.save()
120             if not errors:
121                 b = PendingUser(
122                     first_name    = reg_fname, 
123                     last_name     = reg_lname, 
124                     #affiliation  = reg_aff,
125                     authority_hrn = reg_auth,
126                     login         = reg_login,
127                     email         = reg_email, 
128                     password      = request.POST['password'],
129                     keypair       = keypair,
130                 )
131                 b.save()
132
133                 # Send email
134                 ctx = {
135                     'first_name'    : reg_fname, 
136                     'last_name'     : reg_lname, 
137                     'authority_hrn' : reg_auth,
138                     'email'         : reg_email, 
139                     'keypair'       : 'Public Key :' + public_key,
140                     'cc_myself'     : True # form.cleaned_data['cc_myself']
141                     }
142
143                 recipients = authority_get_pi_emails(request,reg_auth)
144
145                 if ctx['cc_myself']:
146                     recipients.append(ctx['email'])
147
148                 msg = render_to_string('user_request_email.txt', ctx)
149                 send_mail("Onelab New User request for %s submitted"%reg_email, msg, reg_email, recipients)
150
151                 return render(request, 'user_register_complete.html')
152
153         template_env = {
154           'topmenu_items': topmenu_items('Register', request),
155           'errors': errors,
156           'firstname': request.POST.get('firstname', ''),
157           'lastname': request.POST.get('lastname', ''),
158           #'affiliation': request.POST.get('affiliation', ''),
159           'authority_hrn': request.POST.get('authority_hrn', ''),
160           'email': request.POST.get('email', ''),
161           'password': request.POST.get('password', ''),           
162           'authorities': authorities,
163           }
164         template_env.update(page.prelude_env ())
165         return render(request, 'registration_view.html',template_env)