def login(request): url = request.current_route_url() login = '' password = '' error = '' if 'form.submitted' in request.POST: login = request.POST['login'] password = request.POST['password'] connector = get_ldap_connector(request) data = connector.authenticate(login, password) if data is not None: pprint.pprint(data) dn = data[0] headers = remember(request, dn) return HTTPFound('/', headers=headers) else: error = 'Invalid credentials' return dict( login_url=url, login=login, password=password, error=error, )
def login(self): loginURL = self.request.route_url('login') referrer = self.request.url if referrer == loginURL: referrer = '/' cameFrom = self.request.params.get('cameFrom', referrer) message = username = password = u'' if 'submit' in self.request.params: username, password = self.request.params['username'], self.request.params['password'] connector = get_ldap_connector(self.request) result = connector.authenticate(username, password) if result is not None: dn = result[0] fullName = result[1].get(u'cn', result[1][u'uid']) fullName = fullName[0] self.request.session['fullName'] = fullName self.request.session.flash(u'Welcome {}. You are now logged in.'.format(fullName), 'info') headers = remember(self.request, dn) return HTTPFound(location=cameFrom, headers=headers) else: message = 'Login failed' return dict( url=self.request.application_url + '/login', cameFrom=cameFrom, username=username, message=message, form=self.form.render() )
def process(request, view_items): login_url = request.route_path('login') referrer = request.url if referrer == login_url: referrer = '/' # never use the login form itself as came_from came_from = request.params.get('came_from', referrer) message = '' login = '' if 'form.submitted' in request.params: login = request.params['login'] password = request.params['password'] connector = get_ldap_connector(request) data = connector.authenticate(login, password) if data is not None: dn = data[0] groups = connector.user_groups(dn) if groups: for u in groups: # check to ensure the dn is an ET member before allowing any further... if models.members_cn == u[0]: headers = remember(request, dn) return HTTPFound(location=came_from, headers=headers) message = "Your credentials are correct but your account does not have sufficient permission to access this page. Please contact your system administrator." else: message = "Invalid username or password. Please try again or contact your system administrator." out = { 'message': message, 'url': request.route_path("login"), 'came_from': came_from, 'login': login, } return dict(view_items.items() + out.items())
def get_user_from_request(request): from c2cgeoportal.models import DBSession, Role class O(object): pass username = unauthenticated_userid(request) if username is not None: user = O() user.id = 0 user.username = username user.email = None connector = get_ldap_connector(request) cm = connector.manager # 0 means 'Tous publics' roletheme = 0 with cm.connection() as conn: result = conn.search_s("ou=portail,dc=act,dc=lu", ldap.SCOPE_SUBTREE, "(login=%s)" % username) if len(result) == 1: if "roleTheme" in result[0][1]: roletheme = result[0][1]["roleTheme"][0] if "mail" in result[0][1]: user.mail = result[0][1]["mail"][0] if "sn" in result[0][1]: user.sn = result[0][1]["sn"][0] user.role = DBSession.query(Role).filter_by(id=roletheme).one() user.functionalities = [] return user
def _handle_appstruct(self, appstruct): """ Handle LDAP login. """ username = self.request.params.get('username') password = self.request.params.get('password') # Performing ldap login from pyramid_ldap import get_ldap_connector connector = get_ldap_connector(self.request) auth = connector.authenticate(username, password) if auth is not None: # Get user name and email ldap_settings = self.request.db.ldap.find_one() name = (auth[1].get(ldap_settings['name'])[0] if ldap_settings['name'] != '' else 'Unknown') email = (auth[1].get(ldap_settings['email'])[0] if ldap_settings['email'] != '' else '') # Authentication successful return self.login_success(login_id=auth[0], name=name, email=email) # login_id=user_dn else: # Authentification failed return self.login_failure()
def ldap_user_validator(request, username, password): connector = get_ldap_connector(request) data = connector.authenticate(username, password) if data is not None: return data[0] return None
def groupfinder(dn, request): connector = get_ldap_connector(request) group_list = connector.user_groups(dn) if group_list is None: return None group_dns = [] for dn, attrs in group_list: group_dns.append(dn) return group_dns
def get_ldap_groups(dn, request): """Get the groups set in the ldap and transform them to permission .. note:: We try to only get the cn from the group and we prefix the permission with 'ldap:' """ connector = get_ldap_connector(request) group_list = connector.user_groups(dn) if group_list is None: return [] lis = [('ldap:%s' % attrs.get('cn', [dn_])[0]).encode('utf-8') for dn_, attrs in group_list] return lis
def login(request): login_url = request.current_route_url() # detectem des de quina URL ve el visitant referrer = request.url # retornem l'usuari a la home page si ha vingut directe al login if referrer == login_url: referrer = '/' # never use the login form itself as came_from came_from = request.params.get('came_from', referrer) user = authenticated_userid(request) connector = get_ldap_connector( request ) if user: lloc = came_from.split("/") message = "Ets %s, i com a tal no pots entrar a %s" % (user,came_from)#lloc[len(lloc)-1]) else: message = "Identifica't per entrar al sagrat mon d'Egipte" login = '' password = '' if 'form.submitted' in request.params: login = request.params['login'] password = request.params['password'] #connector = get_ldap_connector( request ) data = connector.authenticate( login, password ) if data is not None: # DN complert. És una mica llarg però ha de ser així dn = data[0] # Seria més còmode utilitzar el UID o CN, però llavors no lliga amb Pyramid Auth #uid = data[1]["uid"][0] #print "DADES=" + str(data) print "login OK per " + data[1]["uid"][0] + " DN:"+dn print "GRUPS per " + str(dn) +": " + str(groupfinder(dn,request)) #print str( connector.user_groups(dn) ) for g in connector.user_groups( dn ): print "\t"+ str(g[0]) headers = remember(request,data[0]) return HTTPFound( location=came_from, headers=headers ) # autenticació Pyramid sense LDAP (a esborrar) #if comprova_usuari(login,password): # headers = remember(request, login) # return HTTPFound(location = came_from, # headers = headers) message = 'Failed login' return dict( message = message, url = request.application_url + '/login', came_from = came_from, login = login, password = password, user = authenticated_userid(request), # afegim usuari autenticat si l'hi ha )
def get_user_from_request(request): from c2cgeoportal.models import DBSession, Role class O(object): pass username = unauthenticated_userid(request) if username is not None: user = O() user.id = 0 user.username = username user.email = None user.is_admin = False user.mymaps_role = 999 user.ogc_role = -1 user.sn = None connector = get_ldap_connector(request) cm = connector.manager # 0 means 'Tous publics' roletheme = 0 with cm.connection() as conn: result = conn.search_s('ou=portail,dc=act,dc=lu', ldap.SCOPE_SUBTREE, '(login=%s)' % username) if len(result) == 1: if 'roleTheme' in result[0][1]: roletheme = result[0][1]['roleTheme'][0] if 'mail' in result[0][1]: user.mail = result[0][1]['mail'][0] if 'sn' in result[0][1]: user.sn = result[0][1]['sn'][0] else: user.sn = user.mail if 'isMymapsAdmin' in result[0][1]: user.is_admin =\ "TRUE" == (result[0][1]['isMymapsAdmin'][0]).upper() if 'roleMymaps' in result[0][1]: user.mymaps_role = int(result[0][1]['roleMymaps'][0]) if 'roleOGC' in result[0][1]: user.ogc_role = result[0][1]['roleOGC'][0] try: user.role = DBSession.query(Role).filter_by(id=roletheme).one() except Exception as e: user.role = DBSession.query(Role).filter_by(id=0).one() log.exception(e) user.functionalities = [] return user
def ldap_user_validator(request, username, password): connector = get_ldap_connector(request) data = connector.authenticate(username, password) connection = Connections() connection.login = username connection.application = request.host if data is not None: connection.action = "CONNECT" PortailSession.add(connection) PortailSession.commit() return data[0] else: connection.action = "CONNECT ERROR" PortailSession.add(connection) PortailSession.commit() return None
def validate_ldap(request, login, password): """"Validate ldap login and password. We just check there is an entry in the ldap. :param request: the request :type request: pyramid.request :param login: the user login :type login: str :param password: the user password :type password: str :return: True if there is an entry for the given params in the ldap :rtype: bool """ connector = get_ldap_connector(request) data = connector.authenticate(login, password) if not data: return False return True
def get_user_from_request(request): from c2cgeoportal.models import DBSession, Role class O(object): pass username = unauthenticated_userid(request) if username is not None: user = O() user.id = 0 user.username = username user.email = None user.is_admin = False user.mymaps_role = 999 user.ogc_role = -1 connector = get_ldap_connector(request) cm = connector.manager # 0 means 'Tous publics' roletheme = 0 with cm.connection() as conn: result = conn.search_s('ou=portail,dc=act,dc=lu', ldap.SCOPE_SUBTREE, '(login=%s)' % username) if len(result) == 1: if 'roleTheme' in result[0][1]: roletheme = result[0][1]['roleTheme'][0] if 'mail' in result[0][1]: user.mail = result[0][1]['mail'][0] if 'sn' in result[0][1]: user.sn = result[0][1]['sn'][0] if 'isMymapsAdmin' in result[0][1]: user.is_admin = result[0][1]['isMymapsAdmin'][0] if 'roleMymaps' in result[0][1]: user.mymaps_role = result[0][1]['roleMymaps'][0] if 'roleOGC' in result[0][1]: user.ogc_role = result[0][1]['roleOGC'][0] user.role = DBSession.query(Role).filter_by(id=roletheme).one() user.functionalities = [] return user
def ldap_login(self): """LDAP login""" username = self.request.params.get("username") password = self.request.params.get("password") # Performing ldap login from pyramid_ldap import get_ldap_connector connector = get_ldap_connector(self.request) auth = connector.authenticate(username, password) if auth is not None: # Get user name and email ldap_settings = self.db.ldap.find_one() name = auth[1].get(ldap_settings["name"])[0] if ldap_settings["name"] != "" else "Unknown" email = auth[1].get(ldap_settings["email"])[0] if ldap_settings["email"] != "" else None # Authentication successful return self.login_success(login_id=auth[0], name=name, email=email) # userdn else: # Authentification failed return self.login_failure()
def get_user_info(self, user): connector = get_ldap_connector(self.request) cm = connector.manager with cm.connection() as conn: dn_list = conn.search_s('ou=portail,dc=act,dc=lu', ldap.SCOPE_SUBTREE, '(login=%s)' % user) if len(dn_list) != 1: return HTTPInternalServerError() dn = dn_list[0][0] attributes = conn.search_s(dn, ldap.SCOPE_BASE, '(objectClass=*)', ['mail']) if len(attributes) == 0 or len(attributes[0]) != 2: return HTTPInternalServerError() attributes = attributes[0][1] if 'mail' not in attributes or len(attributes['mail']) == 0: return HTTPNotFound() mail_address = attributes['mail'][0] if not mail_address: return HTTPNotFound() return (user, mail_address)
def _callFUT(self, request): from pyramid_ldap import get_ldap_connector return get_ldap_connector(request)
def __call__(self): c = get_ldap_connector(self.request) ldapGroups = [dn for dn, attrs in c.user_groups(u'uid=*') if not dn.startswith(u'system.')] groupNames = [_cnHunter.match(i).group(1) for i in ldapGroups if _cnHunter.match(i)] return self._getMatches(groupNames)
def login(request): page_title = 'Login' au = get_authenticated_user(request) if request.referer: referer_host = request.referer.split('/')[2] else: referer_host = None # Need to send the client a 401 so it can send a user/pass to auth. Need a second condition to check for authenticated user if request.path_info.split('/')[1][:3] == 'api': logging.debug('request came from the api, sending request to re-auth') return HTTPUnauthorized() if request.referer and referer_host == request.host and request.referer.split('/')[3][:6] != 'logout': return_url = request.referer elif request.path != '/login': return_url = request.url else: return_url = '/' login = '' password = '' error = '' if 'form.submitted' in request.POST: login = request.POST['login'] password = request.POST['password'] # Try local first, ldap second data = local_authenticate(login, password) if data is None: connector = get_ldap_connector(request) data = connector.authenticate(login, password) if data is not None: dn = data[0] encrypted = signed_serialize(login, request.registry.settings['arsenal.cookie_token']) headers = remember(request, dn) headers.append(('Set-Cookie', 'un=' + str(encrypted) + '; Max-Age=604800; Path=/')) if 'api.client' in request.POST: return HTTPOk(headers=headers) else: return HTTPFound(request.POST['return_url'], headers=headers) else: error = 'Invalid credentials' if 'api.client' in request.POST: return HTTPForbidden() if request.authenticated_userid: if request.path == '/login': error = 'You are already logged in' page_title = 'Already Logged In' else: error = 'You do not have permission to access this page' page_title = 'Access Denied' if 'api.client' in request.POST: return HTTPForbidden() return {'layout': site_layout('max'), 'page_title': page_title, 'au': au, 'return_url': return_url, 'login': login, 'password': password, 'error': error, }
def _createSchema(self, workflow): # Find the task with order 1: schema = colander.SchemaNode(colander.Mapping()) for task in workflow.tasks: if task.get('order', '-1') == '1': # build the form conf = task.get('configuration', {}) for fieldName in task.get('requiredMetFields', []): # CA-1394, LabCAS UI will generate dataset IDs if fieldName == 'DatasetId': continue title = conf.get(u'input.dataset.{}.title'.format(fieldName), u'Unknown Field') description = conf.get(u'input.dataset.{}.description'.format(fieldName), u'Not sure what to put here.') dataType = conf.get(u'input.dataset.{}.type'.format(fieldName), u'http://www.w3.org/2001/XMLSchema/string') missing = colander.required if conf.get(u'input.dataset.{}.required'.format(fieldName)) == u'true' else None # FIXME: if dataType in ( u'http://www.w3.org/2001/XMLSchema/string', u'http://edrn.nci.nih.gov/xml/schema/types.xml#discipline', u'http://edrn.nci.nih.gov/xml/schema/types.xml#organSite', ): # Check for enumerated values if u'input.dataset.{}.value.1'.format(fieldName) in conf: # Collect the values exp = re.compile(u'input.dataset.{}.value.[0-9]+'.format(fieldName)) values = [] for key, val in conf.items(): if exp.match(key) is not None: values.append((val, val)) values.sort() schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, validator=colander.OneOf([i[0] for i in values]), widget=deform.widget.RadioChoiceWidget(values=values, inline=True), missing=missing )) else: schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, missing=missing )) elif dataType == u'http://edrn.nci.nih.gov/xml/schema/types.xml#text': schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, missing=missing, widget=deform.widget.RichTextWidget() )) elif dataType == u'http://edrn.nci.nih.gov/xml/schema/types.xml#nistDatasetId': # Skip this; we generated this dataset ID based on other fields pass elif dataType == u'http://edrn.nci.nih.gov/xml/schema/types.xml#collaborativeGroup': # CA-1356 ugly fix but I'm in a hurry and these groups haven't changed in 10 years. # FIXME: correct solution: use IVocabularies schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, missing=missing, validator=colander.OneOf(_collaborativeGroups), widget=deform.widget.RadioChoiceWidget(values=[(i, i) for i in _collaborativeGroups]) )) elif dataType == u'urn:ldap:attributes:dn': principals = [ _cnHunter.match(i).group(1).strip() for i in self.request.effective_principals if i.startswith(u'cn=') ] principals.sort() c = get_ldap_connector(self.request) ldapGroups = [ _cnHunter.match(i).group(1).strip() for i, attrs in c.user_groups(u'uid=*') if i.startswith(u'cn=') ] group = colander.SchemaNode( colander.String(), widget=deform.widget.AutocompleteInputWidget(values=self.request.route_url('ldapGroups')), name='group', title=u'Group', description=u'Name of an EDRN group that should be able to access this data' ) groups = colander.SchemaNode( colander.Sequence(), group, validator=colander.ContainsOnly(ldapGroups), name=fieldName, title=title, description=description, missing=missing, default=principals ) schema.add(groups) elif dataType == u'http://edrn.nci.nih.gov/xml/schema/types.xml#principalInvestigator': schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, missing=missing, widget=deform.widget.AutocompleteInputWidget(values=self.request.route_url('people')) )) elif dataType == u'http://edrn.nci.nih.gov/xml/schema/types.xml#protocolName': schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, missing=missing, widget=deform.widget.AutocompleteInputWidget(values=self.request.route_url('protocols')) )) elif dataType == u'http://www.w3.org/2001/XMLSchema/integer': schema.add(colander.SchemaNode( colander.Int(), name=fieldName, title=title, description=description, missing=missing )) elif dataType == u'http://www.w3.org/2001/XMLSchema/boolean': schema.add(colander.SchemaNode( colander.Boolean(), name=fieldName, title=title, description=description, missing=missing )) elif dataType == u'http://www.w3.org/2001/XMLSchema/anyURI': schema.add(colander.SchemaNode( colander.String(), name=fieldName, title=title, description=description, missing=missing, validator=colander.Regex(re_python_rfc3986_URI_reference) )) elif dataType == u'http://www.w3.org/2001/XMLSchema/date': schema.add(colander.SchemaNode( colander.Date(), name=fieldName, title=title, description=description, missing=missing )) else: _logger.warn(u'Unknown data type "%s" for field "%s"', dataType, fieldName) break return schema
def login(request): page_title = 'Login' user = get_user(request) if request.referer: referer_host = request.referer.split('/')[2] else: referer_host = None if request.referer and referer_host == request.host and request.referer.split( '/')[3][:6] != 'logout': return_url = request.referer elif request.path != '/login': return_url = request.url else: return_url = '/applications' login = '' password = '' error = '' if 'form.submitted' in request.POST: login = request.POST['login'] password = request.POST['password'] # AD/LDAP if request.registry.settings['tcw.auth_mode'] == 'ldap': connector = get_ldap_connector(request) data = connector.authenticate(login, password) # LOCAL else: data = local_authenticate(login, password) if data is not None: dn = data[0] encrypted = signed_serialize( login, request.registry.settings['tcw.cookie_token']) headers = remember(request, dn) headers.append( ('Set-Cookie', 'un=' + str(encrypted) + '; Max-Age=604800; Path=/')) return HTTPFound(request.POST['return_url'], headers=headers) else: error = 'Invalid credentials' if request.authenticated_userid: if request.path == '/login': error = 'You are already logged in' page_title = 'Already Logged In' else: error = 'You do not have permission to access this page' page_title = 'Access Denied' return { 'layout': site_layout(), 'page_title': page_title, 'user': user, 'return_url': return_url, 'login': login, 'password': password, 'error': error, }