455b17543dc20cb5101a9aec69e47dac44bc81f3
[myslice.git] / portal / registrationview.py
1 import os.path, re
2 import json
3 from random import randint
4
5 from django.core.mail           import send_mail
6 from django.contrib.auth.models import User
7 from django.views.generic       import View
8 from django.template.loader     import render_to_string
9 from django.shortcuts           import render
10 from django.contrib.auth        import get_user_model
11
12 from unfold.page                import Page
13 from unfold.loginrequired       import FreeAccessView
14 from ui.topmenu                 import topmenu_items_live
15
16 from manifold.manifoldapi       import execute_admin_query
17 from manifold.core.query        import Query
18
19 from portal.models              import PendingUser
20 from portal.actions             import authority_get_pi_emails, manifold_add_user,manifold_add_account
21
22 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
23 # so let's override 'get' and 'post' instead
24 #
25 class RegistrationView (FreeAccessView):
26
27     def post (self, request):
28         return self.get_or_post (request, 'POST')
29
30     def get (self, request):
31         return self.get_or_post (request, 'GET')
32
33     def get_or_post  (self, request, method):
34         errors = []
35
36         # Using cache manifold-tables to get the list of authorities faster
37         authorities_query = Query.get('authority').select('name', 'authority_hrn')
38         
39         #onelab_enabled_query = Query.get('local:platform').filter_by('platform', '==', 'ple').filter_by('disabled', '==', 'False')
40         #onelab_enabled = not not execute_admin_query(request, onelab_enabled_query)
41         #if onelab_enabled:
42         if True:
43             print "ONELAB ENABLED"
44             #authorities_query = Query.get('ple:authority').select('name', 'authority_hrn').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc', 'ple.ibbtple', 'ple.nitos'])
45             # Now using Cache 
46         else:
47             print "FIREXP ENABLED"
48
49         authorities = execute_admin_query(request, authorities_query)
50         if authorities is not None:
51             authorities = sorted(authorities)
52         # xxx tocheck - if authorities is empty, it's no use anyway
53         # (users won't be able to validate the form anyway)
54
55         page = Page(request)
56         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
57         page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
58         page.add_css_files ( [ "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
59
60         print 'registration view, method',method
61
62         user_query  = Query().get('local:user').select('user_id','email')
63         user_details = execute_admin_query(self.request, user_query)
64
65         if method == 'POST':
66             # We shall use a form here
67
68             #get_email = PendingUser.objects.get(email)
69             reg_fname  = request.POST.get('firstname', '')
70             reg_lname  = request.POST.get('lastname', '')
71             #reg_aff   = request.POST.get('affiliation','')
72             reg_auth   = request.POST.get('authority_hrn', '')
73             #reg_login  = request.POST.get('login', '')
74             reg_email  = request.POST.get('email','').lower()
75             #prepare user_hrn 
76             split_email = reg_email.split("@")[0] 
77             split_email = split_email.replace(".", "_")
78             user_hrn = reg_auth + '.' + split_email+ str(randint(1,1000000))
79             
80             UserModel = get_user_model()
81
82             #POST value validation  
83             if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
84                 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
85             if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
86                 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
87             # checking in django_db !!
88             if PendingUser.objects.filter(email__iexact=reg_email):
89                 errors.append('Email is pending for validation. Please provide a new email address.')
90             if UserModel._default_manager.filter(email__iexact=reg_email): 
91                 errors.append('This email is not usable. Please contact the administrator or try with another email.')
92             for user_detail in user_details:
93                 if user_detail['email']==reg_email:
94                     errors.append('Email already registered in Manifold. Please provide a new email address.')
95
96 # XXX TODO: Factorize with portal/accountview.py
97             if 'generate' in request.POST['question']:
98                 from Crypto.PublicKey import RSA
99                 private = RSA.generate(1024)
100                 private_key = json.dumps(private.exportKey())
101                 public  = private.publickey()
102                 public_key = json.dumps(public.exportKey(format='OpenSSH'))
103
104 #                # Generate public and private keys using SFA Library
105 #                from sfa.trust.certificate  import Keypair
106 #                k = Keypair(create=True)
107 #                public_key = k.get_pubkey_string()
108 #                private_key = k.as_pem()
109 #                private_key = ''.join(private_key.split())
110 #                public_key = "ssh-rsa " + public_key
111                 # Saving to DB
112                 account_config = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
113                 auth_type = 'managed'
114                 #keypair = re.sub("\r", "", keypair)
115                 #keypair = re.sub("\n", "\\n", keypair)
116                 #keypair = keypair.rstrip('\r\n')
117                 #keypair = ''.join(keypair.split())
118                 #for sending email: removing existing double qoute 
119                 public_key = public_key.replace('"', '');
120             else: 
121                 up_file = request.FILES['user_public_key']
122                 file_content =  up_file.read()
123                 file_name = up_file.name
124                 file_extension = os.path.splitext(file_name)[1]
125                 allowed_extension =  ['.pub','.txt']
126                 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
127                     account_config = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
128                     account_config = re.sub("\r", "", account_config)
129                     account_config = re.sub("\n", "\\n",account_config)
130                     account_config = ''.join(account_config.split())
131                     auth_type = 'user'
132                     # for sending email
133                     public_key = file_content
134                     public_key = ''.join(public_key.split()) 
135                 else:
136                     errors.append('Please upload a valid RSA public key.')
137
138             #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
139             #                email=reg_email, password=request.POST['password'], keypair=keypair)
140             #b.save()
141             #saving to django db 'portal_pendinguser' table
142             if not errors:
143                 b = PendingUser(
144                     first_name    = reg_fname, 
145                     last_name     = reg_lname, 
146                     #affiliation  = reg_aff,
147                     authority_hrn = reg_auth,
148                     #login         = reg_login,
149                     email         = reg_email, 
150                     password      = request.POST['password'],
151                     keypair       = account_config,
152                     pi            = '',
153                 )
154                 b.save()
155                 # saves the user to django auth_user table [needed for password reset]
156                 user = User.objects.create_user(reg_email, reg_email, request.POST['password'])
157                 #creating user to manifold local:user
158                 user_config = '{"firstname":"'+ reg_fname + '", "lastname":"'+ reg_lname + '", "authority":"'+ reg_auth + '"}'
159                 user_params = {'email': reg_email, 'password': request.POST['password'], 'config': user_config, 'status': 1}
160                 manifold_add_user(request,user_params)
161                 #creating local:account in manifold
162                 user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
163                 account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
164                 manifold_add_account(request,account_params)
165  
166                 # Send email
167                 ctx = {
168                     'first_name'    : reg_fname, 
169                     'last_name'     : reg_lname, 
170                     'authority_hrn' : reg_auth,
171                     'email'         : reg_email,
172                     'user_hrn'      : user_hrn,
173                     'public_key'    : public_key,
174                     }
175                 recipients = authority_get_pi_emails(request,reg_auth)
176                 
177                 # We don't need to send this email to user.
178                 # it's for the PI only
179                 #if ctx['cc_myself']:
180                 #    recipients.append(ctx['email'])
181
182                 msg = render_to_string('user_request_email.txt', ctx)
183                 send_mail("Onelab New User request for %s submitted"%reg_email, msg, 'support@myslice.info', recipients)
184                 return render(request, 'user_register_complete.html') 
185
186         template_env = {
187           'topmenu_items': topmenu_items_live('Register', page),
188           'errors': errors,
189           'firstname': request.POST.get('firstname', ''),
190           'lastname': request.POST.get('lastname', ''),
191           #'affiliation': request.POST.get('affiliation', ''),
192           'authority_hrn': request.POST.get('authority_hrn', ''),
193           'email': request.POST.get('email', ''),
194           'password': request.POST.get('password', ''),           
195           'authorities': authorities,
196           }
197         template_env.update(page.prelude_env ())
198         return render(request, 'registration_view.html',template_env)