62c09347a1d1cf671a2487820e0920295a8c1111
[unfold.git] / portal / registrationview.py
1 import os.path, re
2 import json
3
4 from django.core.mail           import send_mail
5 from django.contrib.auth.models import User
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_live
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, manifold_add_user,manifold_add_account
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         # Using cache manifold-tables to get the list of authorities faster
35         authorities_query = Query.get('authority').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             # Now using Cache 
44         else:
45             print "FIREXP ENABLED"
46
47         authorities = execute_admin_query(request, authorities_query)
48         authorities = sorted(authorities)
49         # xxx tocheck - if authorities is empty, it's no use anyway
50         # (users won't be able to validate the form anyway)
51
52         page = Page(request)
53         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
54         page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
55         page.add_css_files ( [ "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
56
57         print 'registration view, method',method
58
59         user_query  = Query().get('local:user').select('user_id','email')
60         user_details = execute_admin_query(self.request, user_query)
61
62         if method == 'POST':
63             # We shall use a form here
64
65             #get_email = PendingUser.objects.get(email)
66             reg_fname  = request.POST.get('firstname', '')
67             reg_lname  = request.POST.get('lastname', '')
68             #reg_aff   = request.POST.get('affiliation','')
69             reg_auth   = request.POST.get('authority_hrn', '')
70             reg_login  = request.POST.get('login', '')
71             reg_email  = request.POST.get('email','').lower()
72             #prepare user_hrn 
73             split_email = reg_email.split("@")[0] 
74             split_email = split_email.replace(".", "_")
75             user_hrn = reg_auth + '.' + split_email
76
77             #POST value validation  
78             if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
79                 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
80             if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
81                 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
82             # XXX validate authority hrn !!
83             if PendingUser.objects.filter(email__iexact=reg_email):
84                 errors.append('Email is pending for validation. Please provide a new email address.')
85             for user_detail in user_details:
86                 if user_detail['email']==reg_email:
87                     errors.append('Email already exists in Manifold. Please provide a new email address.')
88
89 # XXX TODO: Factorize with portal/accountview.py
90             if 'generate' in request.POST['question']:
91                 from Crypto.PublicKey import RSA
92                 private = RSA.generate(1024)
93                 private_key = json.dumps(private.exportKey())
94                 public  = private.publickey()
95                 public_key = json.dumps(public.exportKey(format='OpenSSH'))
96
97 #                # Generate public and private keys using SFA Library
98 #                from sfa.trust.certificate  import Keypair
99 #                k = Keypair(create=True)
100 #                public_key = k.get_pubkey_string()
101 #                private_key = k.as_pem()
102 #                private_key = ''.join(private_key.split())
103 #                public_key = "ssh-rsa " + public_key
104                 # Saving to DB
105                 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
106                 auth_type = 'managed'
107                 #keypair = re.sub("\r", "", keypair)
108                 #keypair = re.sub("\n", "\\n", keypair)
109                 #keypair = keypair.rstrip('\r\n')
110                 #keypair = ''.join(keypair.split())
111                 #for sending email: removing existing double qoute 
112                 public_key = public_key.replace('"', '');
113             else: 
114                 up_file = request.FILES['user_public_key']
115                 file_content =  up_file.read()
116                 file_name = up_file.name
117                 file_extension = os.path.splitext(file_name)[1]
118                 allowed_extension =  ['.pub','.txt']
119                 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
120                     keypair = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
121                     keypair = re.sub("\r", "", keypair)
122                     keypair = re.sub("\n", "\\n",keypair)
123                     keypair = ''.join(keypair.split())
124                     auth_type = 'user'
125                     # for sending email
126                     public_key = file_content
127                     public_key = ''.join(public_key.split()) 
128                 else:
129                     errors.append('Please upload a valid RSA public key [.txt or .pub].')
130
131             #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
132             #                email=reg_email, password=request.POST['password'], keypair=keypair)
133             #b.save()
134             #saving to django db 'portal_pendinguser' table
135             if not errors:
136                 b = PendingUser(
137                     first_name    = reg_fname, 
138                     last_name     = reg_lname, 
139                     #affiliation  = reg_aff,
140                     authority_hrn = reg_auth,
141                     login         = reg_login,
142                     email         = reg_email, 
143                     password      = request.POST['password'],
144                     keypair       = keypair,
145                 )
146                 b.save()
147                 # saves the user to django auth_user table [needed for password reset]
148                 user = User.objects.create_user(reg_fname, reg_email, request.POST['password'])
149                 #creating user to manifold local:user
150                 config = '{"firstname":"'+ reg_fname + '", "lastname":"'+ reg_lname + '", "authority":"'+ reg_auth + '"}'
151                 user_params = {'email': reg_email, 'password': request.POST['password'], 'config': config}
152                 manifold_add_user(request,user_params)
153                 #creating local:account in manifold
154                 user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
155                 user_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': keypair}
156                 manifold_add_account(request,user_params)
157  
158                 # Send email
159                 ctx = {
160                     'first_name'    : reg_fname, 
161                     'last_name'     : reg_lname, 
162                     'authority_hrn' : reg_auth,
163                     'email'         : reg_email,
164                     'user_hrn'      : user_hrn,
165                     'keypair'       : 'Public Key: ' + public_key,
166                     'cc_myself'     : True # form.cleaned_data['cc_myself']
167                     }
168                 recipients = authority_get_pi_emails(request,reg_auth)
169
170                 if ctx['cc_myself']:
171                     recipients.append(ctx['email'])
172
173                 msg = render_to_string('user_request_email.txt', ctx)
174                 send_mail("Onelab New User request for %s submitted"%reg_email, msg, reg_email, recipients)
175                 return render(request, 'user_register_complete.html') 
176
177         template_env = {
178           'topmenu_items': topmenu_items_live('Register', page),
179           'errors': errors,
180           'firstname': request.POST.get('firstname', ''),
181           'lastname': request.POST.get('lastname', ''),
182           #'affiliation': request.POST.get('affiliation', ''),
183           'authority_hrn': request.POST.get('authority_hrn', ''),
184           'email': request.POST.get('email', ''),
185           'password': request.POST.get('password', ''),           
186           'authorities': authorities,
187           }
188         template_env.update(page.prelude_env ())
189         return render(request, 'registration_view.html',template_env)