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