1 # this somehow is not used anymore - should it not be ?
2 from django.core.context_processors import csrf
3 from django.http import HttpResponseRedirect
4 from django.contrib.auth import authenticate, login, logout, get_user_model
5 from django.template import RequestContext
6 from django.shortcuts import render_to_response
7 from django.shortcuts import render
10 from unfold.loginrequired import FreeAccessView
12 from manifold.core.query import Query
13 #from manifoldapi.manifoldapi import execute_query
14 # LDAP query admin // If transfer this code to actions.py maybe don't need more execute_admin_query
15 from manifoldapi.manifoldapi import execute_query, execute_admin_query
16 # Edelberto - LDAP XXX
17 from portal.models import PendingUser
18 from django.contrib.auth.models import User #Pedro
19 from portal.actions import create_pending_user, create_user
20 from registrationview import RegistrationView
21 from random import randint
22 from hashlib import md5
23 from django.contrib.sites.models import Site
28 from manifoldapi.manifoldresult import ManifoldResult
29 from ui.topmenu import topmenu_items, the_user
30 from myslice.configengine import ConfigEngine
32 from myslice.theme import ThemeView
34 # Edelberto LDAP authentication XXX
37 class HomeView (FreeAccessView, ThemeView):
38 template_name = 'home-view.html'
40 # expose this so we can mention the backend URL on the welcome page
41 def default_env (self):
43 'MANIFOLD_URL':ConfigEngine().manifold_url(),
46 def post (self,request):
47 env = self.default_env()
48 env['theme'] = self.theme
49 env['section'] = "Dashboard"
51 username = request.POST.get('username').lower()
52 password = request.POST.get('password')
54 # LDAP form - If FIBRE, then get the possibilite to authenticate using usernameldap
55 #if self.theme == 'fibre':
56 #usernameldap = request.POST.get('usernameldap')
57 #token = {'usernameldap': usernameldap, 'username': username ,'password': password, 'request': request}
59 ##################################################
60 ########## XXX Edelberto 010914 XXX
61 #################################################
62 ## first you must open a connection to the server
65 l = ldap.initialize("ldap://200.130.15.186:389")
66 # Bind/authenticate with a root user to search all objects
67 l.simple_bind_s("cn=Manager,dc=br,dc=fibre","fibre2013")
69 l.protocol_version = ldap.VERSION3
70 except ldap.LDAPError, e:
75 searchScope = ldap.SCOPE_SUBTREE
76 ## retrieve all attributes
77 retrieveAttributes = None
78 #retrieveAttributes = ['userEnable']
79 searchFilter = "uid=" + username
83 ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
85 result_type, result_data = l.result(ldap_result_id, 0)
86 if (result_data == []):
87 print "User doesnt exist in LDAP"
90 if result_type == ldap.RES_SEARCH_ENTRY:
91 result_set.append(result_data)
93 result_set.append(result_data)
94 # TRUE or FALSE for userEnable attribute
95 userEnable = result_set[0][0][1]['userEnable'][0]
96 if userEnable == 'TRUE':
99 print "In LDAP and Enabled"
101 dn = result_set[0][0][0]
103 l.simple_bind_s(dn,password)
105 print "User password OK"
109 print "User password WRONG"
111 if in_ldap and enabled and pwd:
112 ldap_mail = result_set[0][0][1]['mail'][0]
114 user_exists = Query().get('local:user') \
116 .filter_by('email', '==', username)
117 results = execute_admin_query(request, user_exists)
118 print "DEBUG: %s" % user_exists
120 print "DEBUG: user exists on MySlice DBs"
122 print "DEBUG: user NOT exists on MySlice DBs"
124 cn = result_set[0][0][1]['cn'][0]
126 sn = result_set[0][0][1]['sn'][0]
128 authority_hrn = 'fibre' + '.' + username.split('@')[1]
136 user_hrn = 'fibre' + '.' + username.split('@')[1] + '.' + username
139 # Based on registrationview
143 current_site = Site.objects.get_current()
144 current_site = current_site.domain
147 post_email = ldap_mail
148 salt = randint(1,100000)
149 email_hash = md5(str(salt)+post_email).hexdigest()
156 #'organization' : username.split('@')[1],
157 'organization' : authority_hrn,
158 'authority_hrn' : authority_hrn,
160 'username' : username,
161 'password' : password,
162 'current_site' : current_site,
163 'email_hash' : email_hash,
165 'user_hrn' : user_hrn,
167 'validation_link': 'https://' + current_site + '/portal/email_activation/'+ email_hash
172 UserModel = get_user_model()
173 if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
174 errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
175 if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
176 errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
177 if (re.search(r'^[\w,]+$' , username) == None):
178 errors.append('Username may contain only letters,numbers and -/_ characters.')
179 # checking in django_db !!
180 if PendingUser.objects.filter(email__iexact = user_request['email']):
181 errors.append('Email is pending for validation. Please provide a new email address.')
182 if User.objects.filter(username__iexact = user_request['username']):
183 errors.append('This username is already in use, try another one')
184 # Does the user exist in Manifold?
185 user_query = Query().get('local:user').select('user_id','email')
186 user_details = execute_admin_query(request, user_query)
187 for user_detail in user_details:
188 if user_detail['email'] == user_request['email']:
189 errors.append('Email already registered in Manifold. Please provide a new email address.')
190 # Does the user exist in sfa? [query is very slow!!]
191 #user_query = Query().get('user').select('user_hrn','user_email')
192 # XXX Test based on the user_hrn is quick
193 #user_query = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
194 user_query = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_hrn)
195 user_details_sfa = execute_admin_query(request, user_query)
197 #if 'generate' in wsgi_request.POST['question']:
198 user_request['auth_type'] = 'managed'
200 # XXX Common code, dependency ?
201 from Crypto.PublicKey import RSA
202 private = RSA.generate(1024)
204 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
205 # Example: public_key = 'ssh-rsa AAAAB3...'
206 user_request['private_key'] = private.exportKey()
207 user_request['public_key'] = private.publickey().exportKey(format='OpenSSH')
209 # XXX Verify if errors exist - After!
211 create_pending_user(request, user_request, user_detail)
213 create_user(request, user_request)
215 env['state'] = "User LDAP associated. Authenticate again."
216 return render_to_response(self.template, env, context_instance=RequestContext(request))
220 env['state'] = "Access denied. Verify LDAP userEnable and password."
221 return render_to_response(self.template, env, context_instance=RequestContext(request))
226 print "In LDAP but Disabled"
227 env['state'] = "Access denied. Verify LDAP userEnable."
228 return render_to_response(self.template, env, context_instance=RequestContext(request))
231 except ldap.LDAPError, e:
235 if in_ldap and enabled and pwd:
237 ################################################################################
238 ### XXX Edelberto LDAP auth end XXX
239 ###############################################################################
240 # Follow original code
241 ## pass request within the token, so manifold session key can be attached to the request session.
242 token = {'username': username, 'password': password, 'request': request}
244 # our authenticate function returns either
245 # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
246 # . a django User in case of success
247 # . or None if the backend could be reached but the authentication failed
248 auth_result = authenticate(token=token)
249 # use one or two columns for the layout - not logged in users will see the login prompt
250 # high-level errors, like connection refused or the like
251 if isinstance (auth_result, ManifoldResult):
252 manifoldresult = auth_result
253 # let's use ManifoldResult.__repr__
254 env['state']="%s"%manifoldresult
256 return render_to_response(self.template,env, context_instance=RequestContext(request))
257 # user was authenticated at the backend
258 elif auth_result is not None:
264 if request.user.is_authenticated():
265 env['person'] = self.request.user
266 env['username'] = self.request.user
268 ## check user is pi or not
269 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
270 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
275 platform_details = execute_query(self.request, platform_query)
276 account_details = execute_query(self.request, account_query)
277 for platform_detail in platform_details:
278 for account_detail in account_details:
279 if platform_detail['platform_id'] == account_detail['platform_id']:
280 if 'config' in account_detail and account_detail['config'] is not '':
281 account_config = json.loads(account_detail['config'])
282 if 'myslice' in platform_detail['platform']:
283 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
285 if acc_auth_cred=={} or acc_auth_cred=='N/A':
292 return render_to_response(self.template,env, context_instance=RequestContext(request))
294 env['state'] = "Your account is not active, please contact the site admin."
295 env['layout_1_or_2']="layout-unfold2.html"
297 return render_to_response(self.template,env, context_instance=RequestContext(request))
300 env['state'] = "Your username and/or password were incorrect."
302 return render_to_response(self.template, env, context_instance=RequestContext(request))
304 def get (self, request, state=None):
305 env = self.default_env()
307 if request.user.is_authenticated():
308 ## check user is pi or not
309 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
310 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
311 # XXX Something like an invalid session seems to make the execute fail sometimes, and thus gives an error on the main page
312 platform_details = execute_query(self.request, platform_query)
313 account_details = execute_query(self.request, account_query)
314 for platform_detail in platform_details:
315 for account_detail in account_details:
316 if 'platform_id' in platform_detail:
317 if platform_detail['platform_id'] == account_detail['platform_id']:
318 if 'config' in account_detail and account_detail['config'] is not '':
319 account_config = json.loads(account_detail['config'])
320 if 'myslice' in platform_detail['platform']:
321 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
323 if acc_auth_cred=={} or acc_auth_cred=='N/A':
329 env['person'] = self.request.user
333 env['theme'] = self.theme
334 env['section'] = "Dashboard"
337 env['username']=the_user(request)
338 env['topmenu_items'] = topmenu_items(None, request)
339 if state: env['state'] = state
340 elif not env['username']: env['state'] = None
341 # use one or two columns for the layout - not logged in users will see the login prompt
343 # account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
344 # account_details = execute_query(self.request, account_query)
345 # for account_detail in account_details:
346 # account_config = json.loads(account_detail['config'])
347 # platform_name = platform_detail['platform']
348 # if 'myslice' in platform_detail['platform']:
349 # acc_user_cred = account_config.get('delegated_user_credential','N/A')
350 # acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
351 # acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
353 # if 'N/A' not in acc_user_cred:
354 # exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
356 # user_exp_date = exp_date.group(1)
357 # user_cred_exp_list.append(user_exp_date)
359 # my_users = [{'cred_exp': t[0]}
360 # for t in zip(user_cred_exp_list)]
363 # if 'N/A' not in acc_slice_cred:
364 # for key, value in acc_slice_cred.iteritems():
365 # slice_list.append(key)
366 # # get cred_exp date
367 # exp_date = re.search('<expires>(.*)</expires>', value)
369 # exp_date = exp_date.group(1)
370 # slice_cred_exp_list.append(exp_date)
372 # my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
373 # for t in zip(slice_list, slice_cred_exp_list)]
375 # if 'N/A' not in acc_auth_cred:
376 # for key, value in acc_auth_cred.iteritems():
377 # auth_list.append(key)
379 # exp_date = re.search('<expires>(.*)</expires>', value)
381 # exp_date = exp_date.group(1)
382 # auth_cred_exp_list.append(exp_date)
385 return render_to_response(self.template, env, context_instance=RequestContext(request))