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