Merge branch 'master' of ssh://git.onelab.eu/git/myslice
[myslice.git] / portal / registrationview.py
1 import os.path, re
2
3 from django.core.mail           import send_mail
4
5 from django.views.generic       import View
6 from django.template.loader     import render_to_string
7 from django.shortcuts           import render
8
9 from unfold.page                import Page
10 from ui.topmenu                 import topmenu_items
11
12 from manifold.manifoldapi       import execute_admin_query
13 from manifold.core.query        import Query
14
15 from portal.models              import PendingUser
16 from portal.actions             import authority_get_pi_emails 
17
18 # This is a rough porting from views.py
19 # the former function-based view is now made a class
20 # we redefine dispatch as it is simple
21 # and coincidentally works since we do not need LoginRequiredAutoLogoutView
22 # a second stab should redefine post and get instead
23 # also this was not thoroughly tested either, might miss some imports
24 # to be continued...
25
26 class RegistrationView (View):
27
28     def dispatch (self, request):
29
30         errors = []
31
32         authorities_query = Query.get('authority').\
33             select('name', 'authority_hrn')
34         
35         onelab_enabled_query = Query.get('local:platform').filter_by('platform', '==', 'ple-onelab').filter_by('disabled', '==', 'False')
36         onelab_enabled = not not execute_admin_query(request, onelab_enabled_query)
37         if onelab_enabled:
38             print "ONELAB ENABLED"
39             authorities_query = authorities_query.filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc'])
40         else:
41             print "FIREXP ENABLED"
42
43         authorities = execute_admin_query(request, authorities_query)
44         # xxx tocheck - if authorities is empty, it's no use anyway
45         # (users won't be able to validate the form anyway)
46
47         page = Page(request)
48         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
49         page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
50
51         print 'registration view, method',request.method
52
53         if request.method == 'POST':
54             # We shall use a form here
55
56             #get_email = PendingUser.objects.get(email)
57             reg_fname = request.POST.get('firstname', '')
58             reg_lname = request.POST.get('lastname', '')
59             #reg_aff = request.POST.get('affiliation','')
60             reg_auth = request.POST.get('authority_hrn', '')
61             reg_email = request.POST.get('email','').lower()
62       
63             #POST value validation  
64             if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
65                 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
66             if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
67                 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
68             # XXX validate authority hrn !!
69             if PendingUser.objects.filter(email__iexact=reg_email):
70                 errors.append('Email already registered.Please provide a new email address.')
71
72 # XXX TODO: Factorize with portal/accountview.py
73             if 'generate' in request.POST['question']:
74                 from Crypto.PublicKey import RSA
75                 private = RSA.generate(1024)
76                 private_key = json.dumps(private.exportKey())
77                 public  = private.publickey()
78                 public_key = json.dumps(public.exportKey(format='OpenSSH'))
79
80 #                # Generate public and private keys using SFA Library
81 #                from sfa.trust.certificate  import Keypair
82 #                k = Keypair(create=True)
83 #                public_key = k.get_pubkey_string()
84 #                private_key = k.as_pem()
85 #                private_key = ''.join(private_key.split())
86 #                public_key = "ssh-rsa " + public_key
87                 # Saving to DB
88                 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + '}'
89                 #keypair = re.sub("\r", "", keypair)
90                 #keypair = re.sub("\n", "\\n", keypair)
91                 #keypair = keypair.rstrip('\r\n')
92                 #keypair = ''.join(keypair.split())
93             else: 
94                 up_file = request.FILES['user_public_key']
95                 file_content =  up_file.read()
96                 file_name = up_file.name
97                 file_extension = os.path.splitext(file_name)[1]
98                 allowed_extension =  ['.pub','.txt']
99                 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
100                     keypair = '{"user_public_key":"'+ file_content +'"}'
101                     keypair = re.sub("\r", "", keypair)
102                     keypair = re.sub("\n", "\\n",keypair)
103                     keypair = ''.join(keypair.split())
104                     # for sending email
105                     public_key = file_content
106                 else:
107                     errors.append('Please upload a valid RSA public key [.txt or .pub].')
108
109             #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
110             #                email=reg_email, password=request.POST['password'], keypair=keypair)
111             #b.save()
112             if not errors:
113                 b = PendingUser(
114                     first_name=reg_fname, 
115                     last_name=reg_lname, 
116                     #affiliation=reg_aff,
117                     authority_hrn=reg_auth,
118                     email=reg_email, 
119                     password=request.POST['password'],
120                     keypair=keypair
121                     )
122                 b.save()
123
124                 # Send email
125                 ctx = {
126                     'first_name'    : reg_fname, 
127                     'last_name'     : reg_lname, 
128                     'authority_hrn' : reg_auth,
129                     'email'         : reg_email, 
130                     'keypair'       : 'Public Key :' + public_key,
131                     'cc_myself'     : True # form.cleaned_data['cc_myself']
132                     }
133                 #not working
134                 #recipients = authority_get_pi_emails(request,reg_auth)
135                 recipients = ['devel@myslice.info']
136                 if ctx['cc_myself']:
137                     recipients.append(ctx['email'])
138
139                 msg = render_to_string('user_request_email.txt', ctx)
140                 print "tesing msg"
141                 print msg
142                 send_mail("Onelab New User request for %s submitted"%reg_email, msg, reg_email, recipients)
143
144                 return render(request, 'user_register_complete.html')
145
146         template_env = {
147           'topmenu_items': topmenu_items('Register', request),
148           'errors': errors,
149           'firstname': request.POST.get('firstname', ''),
150           'lastname': request.POST.get('lastname', ''),
151           #'affiliation': request.POST.get('affiliation', ''),
152           'authority_hrn': request.POST.get('authority_hrn', ''),
153           'email': request.POST.get('email', ''),
154           'password': request.POST.get('password', ''),           
155           'authorities': authorities,
156           }
157         template_env.update(page.prelude_env ())
158         return render(request, 'registration_view.html',template_env)