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