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