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