- reasons for asking an account; rnp as a catch-all island; changing email messages...
[myslice.git] / portal / registrationview.py
1 import os.path, re
2 import json
3 from random     import randint
4 from hashlib    import md5
5
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 from django.contrib.sites.models import Site
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 django.contrib.auth.models import User   #Pedro
21 #from portal.actions             import create_pending_user
22 # Edelberto - LDAP
23 from portal.actions             import create_pending_user, ldap_create_user
24
25 from myslice.theme import ThemeView
26
27 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
28 # so let's override 'get' and 'post' instead
29 #
30 class RegistrationView (FreeAccessView, ThemeView):
31     template_name = 'registration_view.html'
32     
33     def post (self, request):
34         return self.get_or_post (request, 'POST')
35
36     def get (self, request):
37         return self.get_or_post (request, 'GET')
38
39     def get_or_post(self, wsgi_request, method):
40         """
41         """
42         errors = []
43         authority_hrn = None
44         authorities_query = Query.get('authority').select('name','authority_hrn')
45         authorities = execute_admin_query(wsgi_request, authorities_query)
46         if authorities is not None:
47             authorities = sorted(authorities)
48         
49         # Page rendering
50         page = Page(wsgi_request)
51         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/jquery.qtip.min.js","js/jquery-ui.js" ] )
52         page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css" ] )
53         page.add_css_files ( [ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
54
55         if method == 'POST':
56             reg_form = {}
57             # The form has been submitted
58             
59             # get the domain url
60             current_site = Site.objects.get_current()
61             current_site = current_site.domain
62
63             #authorities_query = Query.get('authority').select('name', 'authority_hrn')
64             #authorities = execute_admin_query(wsgi_request, authorities_query)
65     
66             for authority in authorities:
67                 if authority['name'] == wsgi_request.POST.get('org_name', ''):
68                     authority_hrn = authority['authority_hrn']     
69
70             # Handle the case when the template uses only hrn and not name
71             if authority_hrn is None:
72                 authority_hrn = wsgi_request.POST.get('org_name', '')
73
74             post_email = wsgi_request.POST.get('email','').lower()
75             salt = randint(1,100000)
76             email_hash = md5(str(salt)+post_email).hexdigest()
77             #email_hash = md5(post_email).digest().encode('base64')[:-1]
78             user_request = {
79                 'first_name'    : wsgi_request.POST.get('firstname',     ''),
80                 'last_name'     : wsgi_request.POST.get('lastname',      ''),
81                 'organization'  : wsgi_request.POST.get('org_name', ''),
82                 'authority_hrn' : authority_hrn, 
83                 'email'         : post_email,
84                 'username'      : wsgi_request.POST.get('username','').lower(),
85                 'password'      : wsgi_request.POST.get('password',      ''),
86                 'reasons'       : wsgi_request.POST.get('reasons', ''),
87                 'current_site'  : current_site,
88                 'email_hash'    : email_hash,
89                 'pi'            : '',
90                 'validation_link': 'https://' + current_site + '/portal/email_activation/'+ email_hash
91             }
92
93             # Construct user_hrn from email (XXX Should use common code)
94             # split_email = user_request['email'].split("@")[0] 
95             # split_email = split_email.replace(".", "_")
96             # user_request['user_hrn'] = user_request['authority_hrn'] \
97             #         + '.' + split_email
98             
99             username = user_request['username']
100
101             if user_request['authority_hrn'] == "fibre" :
102                 user_request['username'] = user_request['username'] + "@" + "rnp" # catch-all island
103                 split_authority = user_request['authority_hrn']
104             else :
105                 split_authority = user_request['authority_hrn'].split(".")[1]
106                 user_request['username'] = user_request['username'] + '@' + split_authority
107                 split_authority = user_request['authority_hrn'].split(".")[0]
108
109             user_request['user_hrn'] = split_authority + '.' + user_request['username']
110
111             # Validate input
112             UserModel = get_user_model()
113             if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
114                 errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
115             if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
116                 errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
117             if (re.search(r'^[\w,]+$' , username) == None):
118                 errors.append('Username may contain only letters,numbers and -/_ characters.')
119             # checking in django_db !!
120             if PendingUser.objects.filter(email__iexact = user_request['email']):
121                 errors.append('Email is pending for validation. Please provide a new email address.')
122             # if UserModel._default_manager.filter(email__iexact = user_request['email']): 
123             #     errors.append('This email is not usable. Please contact the administrator or try with another email.')
124             if User.objects.filter(username__iexact = user_request['username']): 
125                 errors.append('This username is already in use, try another one')
126             # Does the user exist in Manifold?
127             user_query  = Query().get('local:user').select('user_id','email')
128             user_details = execute_admin_query(wsgi_request, user_query)
129             for user_detail in user_details:
130                 if user_detail['email'] == user_request['email']:
131                     errors.append('Email already registered in Manifold. Please provide a new email address.')
132             # Does the user exist in sfa? [query is very slow!!]
133             #user_query  = Query().get('user').select('user_hrn','user_email')
134             # XXX Test based on the user_hrn is quick
135             user_query  = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
136             user_details_sfa = execute_admin_query(wsgi_request, user_query)
137
138             # for user in user_details_sfa:
139             #     if user['user_email'] == user_request['email']:
140             #         errors.append('Email already registered in SFA registry. Please use another email.')
141             #     if user['user_hrn'] == user_request['user_hrn']:
142             #         # add random number if user_hrn already exists in the registry
143             #         user_request['user_hrn'] = user_request['authority_hrn'] \
144             #                 + '.' + split_email + str(randint(1,1000000))
145                 
146             # XXX TODO: Factorize with portal/accountview.py
147             # XXX TODO: Factorize with portal/registrationview.py
148             # XXX TODO: Factorize with portal/joinview.py
149             if 'generate' in wsgi_request.POST['question']:
150                 user_request['auth_type'] = 'managed'
151
152                 # XXX Common code, dependency ?
153                 from Crypto.PublicKey import RSA
154                 private = RSA.generate(1024)
155
156                 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
157                 # Example: public_key = 'ssh-rsa AAAAB3...'
158                 user_request['private_key'] = private.exportKey()
159                 user_request['public_key']  = private.publickey().exportKey(format='OpenSSH')
160
161             else: 
162                 user_request['auth_type'] = 'user'
163
164                 up_file        = wsgi_request.FILES['user_public_key']
165
166                 file_content   = up_file.read().strip()
167                 file_name      = up_file.name
168                 file_extension = os.path.splitext(file_name)[1]
169
170                 ALLOWED_EXTENSIONS =  ['.pub','.txt']
171                 if file_extension not in ALLOWED_EXTENSIONS or not re.search(r'ssh-rsa',file_content):
172                     errors.append('Please upload a valid RSA public key.')
173                 # user_request['private_key'] can't be Null because all db fields are set as NOT NULL
174                 user_request['private_key'] = ""
175                 user_request['public_key']  = file_content
176                 
177             if not errors:
178                 '''
179                 try:
180                     # verify if is a  LDAP 
181                     mail = user_detail['email']
182                     login = mail.split('@')[0]
183                     org = mail.split('@')[1]
184                     o = org.split('.')[-2]
185                     dc = org.split('.')[-1]
186                     # To know if user is a LDAP user - Need to has a 'dc' identifier
187                     if dc == 'br' or 'eu':
188                         # LDAP insert directly - but with userEnable = FALSE
189                         ldap_create_user(wsgi_request, user_request, user_detail)
190                    
191                 except Exception, e:
192                     print "LDAP: problem em access the LDAP with this credentail" 
193                 '''
194                 create_pending_user(wsgi_request, user_request, user_detail)
195                 self.template_name = 'user_register_complete.html'
196             
197                 return render(wsgi_request, self.template, {'theme': self.theme, 'REQINST':wsgi_request.POST.get('org_name', '').split(".")[1].upper()}) 
198
199         else:
200             user_request = {}
201             ## this is coming from onelab website onelab.eu
202             reg_form = {
203                 'first_name':  wsgi_request.GET.get('first_name', ''),
204                 'last_name': wsgi_request.GET.get('last_name', ''),
205                 'email': wsgi_request.GET.get('email', ''),
206                 }
207
208         template_env = {
209           'topmenu_items': topmenu_items_live('Register', page),
210           'errors': errors,
211           'authorities': authorities,
212           'theme': self.theme
213           }
214         template_env.update(user_request)
215         template_env.update(reg_form)
216         template_env.update(page.prelude_env ())
217         return render(wsgi_request, self.template,template_env)