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